From a66205b7256034c27d70f09f00d22631a7a76719 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Mon, 12 Oct 2026 10:43:00 -0600 Subject: [PATCH 01/51] feat(indicadores): agregar prototipo de dashboard TEA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implementa el prototipo del dashboard de indicadores TEA. - Integra catálogo y figuras mediante WebApi. - Incorpora visualizaciones interactivas con Plotly.js. - Agrega controles de indicadores, figuras, periodos y temas. - Implementa estados de carga, errores y diseño responsive. - Incluye explicaciones para los contratos C1, C2 y C3r. - Incorpora pruebas unitarias y de integración de componentes. Prototipo para investigación con datos sintéticos. --- angular.json | 4 +- package-lock.json | 7 + package.json | 1 + proxy.conf.json | 4 + src/app/app.config.ts | 4 +- src/app/app.routes.spec.ts | 16 ++ src/app/app.routes.ts | 4 +- .../indicadores/indicadores-page.html | 79 ++++++++ .../indicadores/indicadores-page.scss | 29 +++ .../indicadores/indicadores-page.spec.ts | 170 +++++++++++++++++ .../features/indicadores/indicadores-page.ts | 119 ++++++++++++ .../indicadores/indicadores.models.spec.ts | 23 +++ .../indicadores/indicadores.models.ts | 36 ++++ .../indicadores/indicadores.service.spec.ts | 53 ++++++ .../indicadores/indicadores.service.ts | 33 ++++ src/app/shared/plotly/plotly-chart.spec.ts | 41 ++++ src/app/shared/plotly/plotly-chart.ts | 61 ++++++ .../shared/plotly/plotly-controller.spec.ts | 178 ++++++++++++++++++ src/app/shared/plotly/plotly-controller.ts | 87 +++++++++ src/app/shared/plotly/plotly-runtime.spec.ts | 23 +++ src/app/shared/plotly/plotly-runtime.ts | 20 ++ src/app/shared/plotly/plotly.d.ts | 1 + 22 files changed, 990 insertions(+), 3 deletions(-) create mode 100644 proxy.conf.json create mode 100644 src/app/app.routes.spec.ts create mode 100644 src/app/features/indicadores/indicadores-page.html create mode 100644 src/app/features/indicadores/indicadores-page.scss create mode 100644 src/app/features/indicadores/indicadores-page.spec.ts create mode 100644 src/app/features/indicadores/indicadores-page.ts create mode 100644 src/app/features/indicadores/indicadores.models.spec.ts create mode 100644 src/app/features/indicadores/indicadores.models.ts create mode 100644 src/app/features/indicadores/indicadores.service.spec.ts create mode 100644 src/app/features/indicadores/indicadores.service.ts create mode 100644 src/app/shared/plotly/plotly-chart.spec.ts create mode 100644 src/app/shared/plotly/plotly-chart.ts create mode 100644 src/app/shared/plotly/plotly-controller.spec.ts create mode 100644 src/app/shared/plotly/plotly-controller.ts create mode 100644 src/app/shared/plotly/plotly-runtime.spec.ts create mode 100644 src/app/shared/plotly/plotly-runtime.ts create mode 100644 src/app/shared/plotly/plotly.d.ts diff --git a/angular.json b/angular.json index 2b304ca..f7e3cb9 100644 --- a/angular.json +++ b/angular.json @@ -2,7 +2,8 @@ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "cli": { - "packageManager": "npm" + "packageManager": "npm", + "analytics": false }, "newProjectRoot": "projects", "projects": { @@ -59,6 +60,7 @@ }, "serve": { "builder": "@angular/build:dev-server", + "options": { "proxyConfig": "proxy.conf.json" }, "configurations": { "production": { "buildTarget": "WebApp:build:production" diff --git a/package-lock.json b/package-lock.json index 0f2ebd5..a70b188 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "@angular/material": "^22.1.7", "@angular/platform-browser": "^22.1.0", "@angular/router": "^22.1.0", + "plotly.js-cartesian-dist-min": "4.1.2", "rxjs": "~7.8.0", "tslib": "^2.3.0" }, @@ -6481,6 +6482,12 @@ "node": ">=16.20.0" } }, + "node_modules/plotly.js-cartesian-dist-min": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/plotly.js-cartesian-dist-min/-/plotly.js-cartesian-dist-min-4.1.2.tgz", + "integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==", + "license": "MIT" + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", diff --git a/package.json b/package.json index f86bd9c..62be094 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "@angular/material": "^22.1.7", "@angular/platform-browser": "^22.1.0", "@angular/router": "^22.1.0", + "plotly.js-cartesian-dist-min": "4.1.2", "rxjs": "~7.8.0", "tslib": "^2.3.0" }, diff --git a/proxy.conf.json b/proxy.conf.json new file mode 100644 index 0000000..cab47d0 --- /dev/null +++ b/proxy.conf.json @@ -0,0 +1,4 @@ +{ + "/tea/**": { "target": "http://127.0.0.1:5000", "secure": false }, + "/health": { "target": "http://127.0.0.1:5000", "secure": false } +} diff --git a/src/app/app.config.ts b/src/app/app.config.ts index e60fc79..a53188e 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -1,3 +1,4 @@ +import { provideHttpClient } from '@angular/common/http'; import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; @@ -5,6 +6,7 @@ import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideBrowserGlobalErrorListeners(), - provideRouter(routes) + provideRouter(routes), + provideHttpClient() ] }; diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts new file mode 100644 index 0000000..1642c9a --- /dev/null +++ b/src/app/app.routes.spec.ts @@ -0,0 +1,16 @@ +import { routes } from './app.routes'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresPage } from './features/indicadores/indicadores-page'; +it('permite acceso directo a /indicadores sin guard ni autenticación', async () => { + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); + const harness = await RouterTestingHarness.create(); + await harness.navigateByUrl('/indicadores', IndicadoresPage); + expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores'); + const http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); + http.verify(); +}); diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index dc39edb..1baddca 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -1,3 +1,5 @@ import { Routes } from '@angular/router'; -export const routes: Routes = []; +export const routes: Routes = [ + { path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) }, +]; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html new file mode 100644 index 0000000..bd02f06 --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.html @@ -0,0 +1,79 @@ +
+
+ Dominio TEA · Investigación +

Dashboard de indicadores

+

Explora las figuras de indicadores TEA generadas por el servicio de reportes.

+
+

Uso exclusivo de investigación. No usar para decisiones clínicas.

+ + @if (catalogLoading()) { + +

Cargando catálogo de indicadores…

+ } @else if (catalogError()) { +

{{ catalogError() }}

+
+ } @else if (!catalog().length) { +

No hay indicadores disponibles en el catálogo.

+
+ } @else { + +
+ Indicador + + @for (item of catalog(); track item.id) { {{ item.titulo }} } + + + Figura + + @for (figure of selected?.figuras ?? []; track $index) { {{ figure }} } + + + Periodos + + Todos los periodos con reporte + Selección manual + + + Tema de la figura + + ClaroOscuro + + + @if (periodMode === 'manual') { + Semestres (AAAA-S1,AAAA-S2) + + Escribe los semestres a consultar. Su disponibilidad depende de los reportes. + + } +
+ @if (periodError) { } +

Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.

+
+ @if (selected) { +
+

Cómo leer esta figura · {{ selected?.contrato }}

+
    + @for (line of interpretation; track $index) {
  • {{ line }}
  • } +
+

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
+ } + + @if (result().status === 'loading') { + +

Cargando figura…

+ } @else if (result().status === 'error') { + + } @else if (result().figure; as figure) { + @if (hasNoVisibleValues(figure)) { +

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

+ } +

{{ selected?.titulo }}

+ + } @else { +

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

+ } +
+ } +
diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss new file mode 100644 index 0000000..b570559 --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.scss @@ -0,0 +1,29 @@ +:host { display: block; } +.dashboard { max-width: 1440px; margin: 0 auto; } +h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; } +header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } +.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); } +.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; } +.filters { padding: 1.5rem; margin: 1.5rem 0; } +.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; } +.indicator { grid-column: span 2; } +.periods { grid-column: 1 / -1; margin-bottom: 1rem; } +mat-form-field { width: 100%; min-width: 0; } +.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; } +.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; } +.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); } +.interpretation ul { margin: 0; padding-left: 1.25rem; } +.interpretation li + li { margin-top: .25rem; } +.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); } +.validation { color: var(--mat-sys-error); } +.figure-card { overflow: hidden; min-width: 0; } +.figure-title { display: none; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; } +.state { padding: 1.25rem; margin: 0; } +.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } +@media (max-width: 850px) { .figure-title { display: block; } .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@media (max-width: 550px) { + .fields { grid-template-columns: minmax(0, 1fr); } + .indicator { grid-column: auto; } + .filters, .interpretation { padding: 1rem; } + h1 { font: var(--mat-sys-headline-medium); } +} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts new file mode 100644 index 0000000..3611cee --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -0,0 +1,170 @@ +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 { PlotlyFigure } from './indicadores.models'; +import { Component } from '@angular/core'; +import { IndicadoresPage } from './indicadores-page'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } +const catalog = [ + { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'] }, + { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'] }, + { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [] }, +]; +describe('IndicadoresPage', () => { + let page: IndicadoresPage; + let http: HttpTestingController; + let fixture: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresPage); + page = fixture.componentInstance; + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function load() { http.expectOne('/tea/indicadores').flush(catalog); } + function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + it('presenta carga y elige una primera figura válida desde el catálogo', () => { + expect(page.catalogLoading()).toBe(true); + load(); + expect(page.indicadorId).toBe('i1'); + expect(page.figuraId).toBe('f1'); + expect(page.result().status).toBe('loading'); + const request = figure(); + expect(request.request.params.has('periodos')).toBe(false); + request.flush({ data: [], layout: {} }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación'); + }); + it.each([ + ['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']], + ['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']], + ['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']], + ['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']], + ['toString', ['No hay una explicación específica']], + ])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => { + http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]); + figure().flush({ data: [], layout: {} }); + fixture.detectChanges(); + const help = fixture.nativeElement.querySelector('.interpretation').textContent; + for (const text of expected) expect(help).toContain(text); + if (contract === 'C3r') { + expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados'); + expect(help).not.toMatch(/serving|corrección|fase independiente/i); + } + expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.'); + expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables'); + }); + it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => { + load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson'); + page.selectIndicador('i2'); fixture.detectChanges(); + const help = fixture.nativeElement.querySelector('.interpretation').textContent; + expect(help).toContain('min/max'); expect(help).not.toContain('Wilson'); + figure().flush({ data: [], layout: {} }); + }); + it('entrega al gráfico el JSON íntegro sin modificarlo al presentar la ayuda', () => { + load(); + const received: PlotlyFigure = { + data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }], + layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true }, + config: { staticPlot: false }, frames: [], extra: { preserved: true }, + }; + const original = JSON.stringify(received); + figure().flush(received); fixture.detectChanges(); + expect(JSON.stringify(received)).toBe(original); + expect(page.result().figure).toEqual(received); + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; + expect(chart.figure).toBe(page.result().figure); + expect(JSON.stringify(chart.figure)).toBe(original); + }); + it('muestra catálogo vacío y permite recargar', () => { + http.expectOne('/tea/indicadores').flush([]); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); + page.retryCatalog(); + load(); + figure().flush({ data: [], layout: {} }); + }); + it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => { + load(); + const old = figure(); + page.selectIndicador('i2'); + expect(old.cancelled).toBe(true); + expect(page.figuraId).toBe('box'); + expect(page.result().figure).toBeUndefined(); + figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} }); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(page.result().figure?.data[0]['median']).toEqual([2]); + }); + it('soporta varias figuras, volver al indicador y selección sin figuras', () => { + load(); figure().flush({ data: [], layout: {} }); + page.selectFigura('f2'); + expect(figure().request.url).toContain('/i1/figuras/f2'); + // Cancel the previous request and verify its cancellation explicitly below. + page.selectIndicador('empty'); + expect(page.figuraId).toBe(''); + expect(page.result().status).toBe('idle'); + page.selectIndicador('i1'); + expect(page.figuraId).toBe('f1'); + figure().flush({ data: [], layout: {} }); + }); + it('valida manuales antes del HTTP y vuelve a Todos sin query', () => { + load(); figure().flush({ data: [], layout: {} }); + page.changePeriodMode('manual'); + expect(page.periodError).not.toBe(''); + http.expectNone(req => req.url.includes('/figuras/')); + page.changePeriodText('2025-S1, 2025-S2'); + const manual = figure(); + expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + page.changePeriodText('2025-S3'); + expect(manual.cancelled).toBe(true); + expect(page.result().figure).toBeUndefined(); + page.changePeriodMode('todos'); + const all = figure(); + expect(all.request.params.has('periodos')).toBe(false); + all.flush({ data: [], layout: {} }); + }); + it('cancela figuras al cambiar tema rápidamente', () => { + load(); + const old = figure(); + page.changeTema('oscuro'); + const dark = figure(); + expect(old.cancelled).toBe(true); + expect(dark.request.params.get('tema')).toBe('oscuro'); + page.changeTema('claro'); + expect(dark.cancelled).toBe(true); + figure().flush({ data: [], layout: {} }); + }); + it.each([ + [400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'], + ])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => { + load(); + figure().flush('error privado', { status: status as number, statusText: 'Error' }); + expect(page.result().status).toBe('error'); + expect(page.result().message).toContain(message); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).not.toContain('error privado'); + page.requestFigure(); + figure().flush({ data: [], layout: {} }); + expect(page.result().status).toBe('ready'); + }); + it('distingue conexión fallida y cancela HTTP al destruirse', () => { + load(); figure().error(new ProgressEvent('error')); + expect(page.result().message).toContain('conectar'); + page.requestFigure(); + const pending = figure(); + fixture.destroy(); + expect(pending.cancelled).toBe(true); + }); + it('controla errores de catálogo y puede recuperarse', () => { + http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' }); + expect(page.catalogError()).toContain('error interno'); + page.retryCatalog(); load(); figure().flush({ data: [], layout: {} }); + }); +}); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts new file mode 100644 index 0000000..0532cf8 --- /dev/null +++ b/src/app/features/indicadores/indicadores-page.ts @@ -0,0 +1,119 @@ +import { Component, DestroyRef, inject, signal } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +export function httpMessage(error: unknown, catalog = false): string { + if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.'; + if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.'; + if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.'; + if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.'; + if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.'; + return 'No se pudo completar la solicitud. Intenta nuevamente.'; +} +// Presentation only: contract semantics documented in G3 and G5C. +const CONTRACT_INTERPRETATIONS: Readonly> = { + C1: [ + 'El punto representa la proporción observada.', + 'La línea vertical representa el intervalo de confianza Wilson al 95 %.', + 'Los intervalos amplios pueden deberse a denominadores pequeños.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ], + C2: [ + 'Las barras muestran la composición porcentual de cada grupo y periodo.', + 'Las categorías corresponden a la distribución de cada grupo y periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + ], + C3r: [ + 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', + 'Los límites de dibujo no representan necesariamente extremos observados.', + 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', + ], +}; +const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.']; + +type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; message?: string }; +@Component({ + selector: 'app-indicadores-page', + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicadores-page.html', + styleUrl: './indicadores-page.scss', +}) +export class IndicadoresPage { + private readonly service = inject(IndicadoresService); + private readonly destroyRef = inject(DestroyRef); + private readonly catalogRequests = new Subject(); + private readonly figureRequests = new Subject(); + readonly catalog = signal([]); + readonly catalogLoading = signal(true); + readonly catalogError = signal(''); + readonly result = signal({ status: 'idle' }); + readonly hasNoVisibleValues = hasNoVisibleValues; + indicadorId = ''; + figuraId = ''; + periodMode: 'todos' | 'manual' = 'todos'; + periodText = ''; + periodError = ''; + tema: Tema = 'claro'; + get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); } + + get interpretation(): readonly string[] { + const contract = this.selected?.contrato; + return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) + ? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION; + } + + constructor() { + this.figureRequests.pipe(switchMap(selection => selection + ? this.service.figura(selection).pipe( + map(figure => ({ status: 'ready', figure }) as FigureState), + catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)), + startWith({ status: 'loading' } as FigureState)) + : of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef)) + .subscribe(state => this.result.set(state)); + this.catalogRequests.pipe(startWith(undefined), switchMap(() => { + this.catalogLoading.set(true); + this.catalogError.set(''); + this.catalog.set([]); + this.indicadorId = this.figuraId = ''; + this.figureRequests.next(null); + return this.service.catalogo().pipe(map(items => ({ items, error: '' })), + catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); + }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { + this.catalogLoading.set(false); + this.catalog.set(items); + this.catalogError.set(error); + if (items.length) this.selectIndicador(items[0].id); + }); + } + retryCatalog() { this.catalogRequests.next(); } + selectIndicador(id: string) { + this.indicadorId = id; + this.figuraId = this.selected?.figuras[0] ?? ''; + this.requestFigure(); + } + selectFigura(id: string) { this.figuraId = id; this.requestFigure(); } + changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); } + changePeriodText(text: string) { this.periodText = text; this.requestFigure(); } + changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); } + requestFigure() { + this.periodError = ''; + const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText) : undefined; + if (periodos === null) this.periodError = 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.'; + if (!this.selected || !this.selected.figuras.includes(this.figuraId) || periodos === null) { + this.figureRequests.next(null); + return; + } + this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos }); + } +} diff --git a/src/app/features/indicadores/indicadores.models.spec.ts b/src/app/features/indicadores/indicadores.models.spec.ts new file mode 100644 index 0000000..abe4e01 --- /dev/null +++ b/src/app/features/indicadores/indicadores.models.spec.ts @@ -0,0 +1,23 @@ +import { hasNoVisibleValues, parsePeriodos } from './indicadores.models'; + +describe('Periodos y visibilidad conservadora', () => { + it('normaliza espacios y duplicados sin inventar periodos', () => { + expect(parsePeriodos('2025-S1, 2025-S2,2025-S1')).toEqual(['2025-S1', '2025-S2']); + expect(parsePeriodos('1900-S2')).toEqual(['1900-S2']); + }); + it.each(['', '2025', '25-S1', '2025-S3', '2025-S1,', '2025-s1', '2025-S1 2025-S2'])('rechaza %s', value => { + expect(parsePeriodos(value)).toBeNull(); + }); + it('detecta trazos vacíos, nulos y cajas sin mediana', () => { + expect(hasNoVisibleValues({ data: [], layout: {} })).toBe(true); + expect(hasNoVisibleValues({ data: [{ type: 'scatter', y: [null] }, { type: 'bar', y: [] }, { type: 'box', median: [null] }], layout: {} })).toBe(true); + }); + it('conserva cero, supresión y medianas válidas como valores visibles', () => { + expect(hasNoVisibleValues({ data: [{ y: [0] }], layout: {} })).toBe(false); + expect(hasNoVisibleValues({ data: [{ type: 'box', median: [10] }], layout: {} })).toBe(false); + }); + it('no declara vacíos los formatos desconocidos o binarios', () => { + expect(hasNoVisibleValues({ data: [{ y: { bdata: 'AAAA', dtype: 'f8' } }], layout: {} })).toBe(false); + expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false); + }); +}); diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts new file mode 100644 index 0000000..6b26103 --- /dev/null +++ b/src/app/features/indicadores/indicadores.models.ts @@ -0,0 +1,36 @@ +export interface Indicador { + id: string; + titulo: string; + contrato: string; + figuras: string[]; +} + +// Keep the complete HTTP figure, including future attributes and interpretation notes. +export interface PlotlyFigure { + data: Record[]; + layout: Record; + frames?: Record[]; + config?: Record; + [key: string]: unknown; +} +export type Tema = 'claro' | 'oscuro'; +export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; } + +export function parsePeriodos(value: string): string[] | null { + const parts = value.split(',').map(part => part.trim()); + return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part)) + ? [...new Set(parts)] : null; +} + +// Only assert emptiness for known TEA traces with ordinary arrays. Unknown/binary +// representations remain indeterminate; never infer counts or suppression causes. +export function hasNoVisibleValues(figure: PlotlyFigure): boolean { + return figure.data.every(trace => { + if (trace['visible'] === false || trace['visible'] === 'legendonly') return true; + const type = trace['type'] ?? 'scatter'; + const values = type === 'box' ? trace['median'] ?? trace['y'] + : type === 'scatter' || type === 'bar' ? trace['y'] : undefined; + if (!Array.isArray(values)) return false; + return !values.some(value => typeof value === 'number' && Number.isFinite(value)); + }); +} diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts new file mode 100644 index 0000000..1b69c41 --- /dev/null +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -0,0 +1,53 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresService } from './indicadores.service'; + +describe('IndicadoresService HTTP', () => { + let service: IndicadoresService; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresService); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + it('consume un arreglo directo sin hardcodear catálogo', () => { + const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }]; + let actual: unknown; + service.catalogo().subscribe(value => actual = value); + http.expectOne('/tea/indicadores').flush(data); + expect(actual).toEqual(data); + }); + it('acepta catálogo vacío y rechaza envelope inesperado', () => { + service.catalogo().subscribe(value => expect(value).toEqual([])); + http.expectOne('/tea/indicadores').flush([]); + let error: unknown; + service.catalogo().subscribe({ error: value => error = value }); + http.expectOne('/tea/indicadores').flush({ items: [] }); + expect(error).toBeInstanceOf(Error); + }); + it('codifica segmentos y omite periodos en Todos', () => { + service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe(); + const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23'); + expect(request.request.method).toBe('GET'); + expect(request.request.params.get('tema')).toBe('claro'); + expect(request.request.params.has('periodos')).toBe(false); + request.flush({ data: [], layout: {} }); + }); + it('envía semestres y conserva atributos desconocidos, nulos y notas', () => { + const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] }; + service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] }) + .subscribe(value => expect(value).toEqual(figure)); + const request = http.expectOne(req => req.url.endsWith('/i/figuras/f')); + expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + expect(request.request.params.get('tema')).toBe('oscuro'); + request.flush(figure); + }); + it('rechaza una figura estructuralmente inválida', () => { + let error: unknown; + service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value }); + http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} }); + expect(error).toBeInstanceOf(Error); + }); +}); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts new file mode 100644 index 0000000..baf82b3 --- /dev/null +++ b/src/app/features/indicadores/indicadores.service.ts @@ -0,0 +1,33 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models'; + +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresService { + private readonly http = inject(HttpClient); + catalogo() { + return this.http.get('/tea/indicadores').pipe(map(value => { + if (!Array.isArray(value) || !value.every(item => record(item) + && typeof item['id'] === 'string' && typeof item['titulo'] === 'string' + && typeof item['contrato'] === 'string' && Array.isArray(item['figuras']) + && item['figuras'].every((figure: unknown) => typeof figure === 'string'))) { + throw new Error('Respuesta de catálogo inválida'); + } + return value as Indicador[]; + })); + } + figura(selection: FigureSelection) { + let params = new HttpParams().set('tema', selection.tema); + if (selection.periodos?.length) params = params.set('periodos', selection.periodos.join(',')); + const url = `/tea/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`; + return this.http.get(url, { params }).pipe(map(value => { + if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record) + || !record(value['layout'])) throw new Error('Respuesta de figura inválida'); + return value as unknown as PlotlyFigure; + })); + } +} diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts new file mode 100644 index 0000000..7d69942 --- /dev/null +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -0,0 +1,41 @@ +import { TestBed } from '@angular/core/testing'; +import { vi } from 'vitest'; +import { PlotlyChart } from './plotly-chart'; +import { PLOTLY_LOADER } from './plotly-runtime'; +const mocks = { load: vi.fn(), react: vi.fn(), purge: vi.fn(), resize: vi.fn() }; + +describe('PlotlyChart lifecycle', () => { + beforeEach(() => { + vi.resetAllMocks(); + mocks.react.mockResolvedValue(undefined); + mocks.resize.mockResolvedValue(undefined); + mocks.load.mockResolvedValue({ react: mocks.react, purge: mocks.purge, Plots: { resize: mocks.resize } }); + TestBed.configureTestingModule({ imports: [PlotlyChart], providers: [{ provide: PLOTLY_LOADER, useValue: mocks.load }] }); + }); + it('monta el host, actualiza inputs y desconecta ResizeObserver', async () => { + const disconnect = vi.fn(); const observe = vi.fn(); + vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; }); + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('figure', { data: [], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); + expect(observe).toHaveBeenCalledWith(fixture.nativeElement.querySelector('.plot')); + expect(mocks.react).toHaveBeenCalledTimes(1); + fixture.componentRef.setInput('figure', { data: [{ y: [1] }], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); + expect(mocks.react).toHaveBeenCalledTimes(2); + fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); + it('muestra error asíncrono y se recupera con reintento', async () => { + mocks.react.mockRejectedValueOnce(new Error('render failed')); + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('figure', { data: [], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No se pudo representar'); + fixture.nativeElement.querySelector('button').click(); + await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); + expect(fixture.componentInstance.status()).toBe('ready'); fixture.destroy(); + }); +}); + + diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts new file mode 100644 index 0000000..48b9589 --- /dev/null +++ b/src/app/shared/plotly/plotly-chart.ts @@ -0,0 +1,61 @@ +import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestroy, output, signal, ViewChild } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; +import { PlotlyController } from './plotly-controller'; +import { PLOTLY_LOADER } from './plotly-runtime'; + +@Component({ + selector: 'app-plotly-chart', + imports: [MatButtonModule, MatProgressBarModule], + template: ` + @if (status() === 'loading') { } + @if (status() === 'error') { +

No se pudo representar la figura. Puedes reintentar.

+
+ } + + @if (status() === 'ready' && notes.length) { +
+

Notas de la figura

+ @for (note of notes; track $index) {

} +
+ } + `, + styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`, +}) +export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { + @Input({ required: true }) figure!: PlotlyFigure; + @ViewChild('host', { static: true }) host!: ElementRef; + readonly renderError = output(); + readonly status = signal<'loading' | 'ready' | 'error'>('loading'); + get notes(): string[] { + const annotations = this.figure?.layout['annotations']; + if (!Array.isArray(annotations)) return []; + return annotations.flatMap(annotation => + annotation && typeof annotation.text === 'string' ? [annotation.text] : []); + } + private readonly loadPlotly = inject(PLOTLY_LOADER); + private controller?: PlotlyController; + private observer?: ResizeObserver; + private readonly windowResize = () => this.controller?.resize(); + ngAfterViewInit() { + this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { + this.status.set(state); + if (state === 'error') this.renderError.emit(); + }); + if (typeof ResizeObserver !== 'undefined') { + this.observer = new ResizeObserver(this.windowResize); + this.observer.observe(this.host.nativeElement); + } else window.addEventListener('resize', this.windowResize); + this.controller.setFigure(this.figure); + } + ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); } + retry() { this.controller?.setFigure(this.figure); } + ngOnDestroy() { + this.observer?.disconnect(); + window.removeEventListener('resize', this.windowResize); + this.controller?.destroy(); + } +} + diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts new file mode 100644 index 0000000..f71f54d --- /dev/null +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -0,0 +1,178 @@ +import { vi } from 'vitest'; +import { PlotlyController } from './plotly-controller'; +import { PlotlyRuntime } from './plotly-runtime'; +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; +function deferred() { + let resolve!: (value?: unknown) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} +async function settle() { for (let i = 0; i < 12; i++) await Promise.resolve(); } +const fig = (value: number): PlotlyFigure => ({ data: [{ type: 'scatter', y: [value, null] }], layout: { annotations: [{ text: 'No usar para decisiones clínicas' }] } }); +describe('PlotlyController async', () => { + let host: HTMLElement; + let plotly: PlotlyRuntime; + let state: ReturnType void>>; + let controller: PlotlyController; + beforeEach(() => { + host = document.createElement('div'); + plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) }, addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) }; + state = vi.fn(); + controller = new PlotlyController(host, () => Promise.resolve(plotly), state); + }); + it('conserva valores y anotaciones, aislando mutaciones de Plotly', async () => { + const figure = fig(0); + vi.mocked(plotly.react).mockImplementation(async (_host, data) => { data[0]['y'] = [123]; }); + controller.setFigure(figure); await settle(); + expect(figure.data[0]['y']).toEqual([0, null]); + expect(plotly.react).toHaveBeenCalledWith(host, expect.any(Array), figure.layout, expect.objectContaining({ displaylogo: false })); + expect(host.style.visibility).toBe('visible'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => { + const figure: PlotlyFigure = { + ...fig(1), + config: { showSendToCloud: true, displaylogo: true, scrollZoom: true, doubleClick: 'reset+autosize' }, + frames: [{ name: 'uno', data: [{ y: [2, null] }] }], + }; + const original = JSON.stringify(figure); + controller.setFigure(figure); await settle(); + expect(plotly.react).toHaveBeenCalledWith(host, figure.data, figure.layout, { + responsive: false, displaylogo: false, showSendToCloud: false, + modeBarButtonsToRemove: ['sendChartToCloud'], scrollZoom: true, doubleClick: 'reset+autosize', + }); + expect(plotly.addFrames).toHaveBeenCalledWith(host, figure.frames); + expect(JSON.stringify(figure)).toBe(original); + }); + it('elige sólo la figura reciente si la importación sigue pendiente', async () => { + const load = deferred(); + controller = new PlotlyController(host, () => load.promise as Promise, state); + controller.setFigure(fig(1)); controller.setFigure(fig(2)); + load.resolve(plotly); await settle(); + expect(plotly.react).toHaveBeenCalledTimes(1); + expect(vi.mocked(plotly.react).mock.calls[0][1][0]['y']).toEqual([2, null]); + }); + it('serializa react y oculta completados obsoletos', async () => { + const old = deferred(); const latest = deferred(); + vi.mocked(plotly.react).mockReturnValueOnce(old.promise).mockReturnValueOnce(latest.promise); + controller.setFigure(fig(1)); await settle(); + controller.setFigure(fig(2)); + expect(plotly.react).toHaveBeenCalledTimes(1); + old.resolve(); await settle(); + expect(plotly.react).toHaveBeenCalledTimes(2); + expect(host.style.visibility).toBe('hidden'); + expect(state).not.toHaveBeenCalledWith('ready'); + latest.resolve(); await settle(); + expect(host.style.visibility).toBe('visible'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('ignora rechazo antiguo y representa la siguiente figura', async () => { + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + controller.setFigure(fig(1)); await settle(); controller.setFigure(fig(2)); + pending.reject(new Error('old')); await settle(); + expect(state).not.toHaveBeenCalledWith('error'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('maneja error asíncrono y permite reintentar', async () => { + vi.mocked(plotly.react).mockRejectedValueOnce(new Error('failed')); + controller.setFigure(fig(1)); await settle(); + expect(state).toHaveBeenLastCalledWith('error'); + expect(host.style.visibility).toBe('hidden'); + controller.setFigure(fig(1)); await settle(); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('maneja importación fallida y recupera el cargador', async () => { + const load = vi.fn().mockRejectedValueOnce(new Error()).mockResolvedValue(plotly); + controller = new PlotlyController(host, load, state); + controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('error'); + controller.setFigure(fig(1)); await settle(); expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('purga al destruir y nuevamente tras terminar react pendiente', async () => { + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + controller.setFigure(fig(1)); await settle(); + controller.destroy(); expect(plotly.purge).toHaveBeenCalledTimes(1); + pending.resolve(); await settle(); expect(plotly.purge).toHaveBeenCalledTimes(2); + expect(state).not.toHaveBeenCalledWith('ready'); + controller.setFigure(fig(2)); controller.resize(); await settle(); + expect(plotly.react).toHaveBeenCalledTimes(1); + expect(plotly.Plots.resize).not.toHaveBeenCalled(); + }); + it('no renderiza tras destruir durante la importación', async () => { + const pending = deferred(); controller = new PlotlyController(host, () => pending.promise as Promise, state); + controller.setFigure(fig(1)); controller.destroy(); pending.resolve(plotly); await settle(); + expect(plotly.react).not.toHaveBeenCalled(); expect(plotly.purge).toHaveBeenCalledWith(host); + }); + it('serializa resize y el siguiente react', async () => { + controller.setFigure(fig(1)); await settle(); + const resize = deferred(); vi.mocked(plotly.Plots.resize).mockReturnValueOnce(resize.promise); + controller.resize(); await settle(); controller.setFigure(fig(2)); + expect(plotly.react).toHaveBeenCalledTimes(1); + resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2); + }); + it('conserva frames y los retira al cambiar figura', async () => { + controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle(); + expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]); + controller.setFigure(fig(2)); await settle(); + expect(plotly.deleteFrames).toHaveBeenCalledWith(host, [0]); + }); +}); + + +// Exercise the installed bundle in jsdom: no cloud action is clicked. +describe('PlotlyController con Plotly instalado', () => { + let runtime: PlotlyRuntime & { + version: string; + PlotSchema: { get(): { config: Record } }; + }; + beforeAll(async () => { + // jsdom has no canvas renderer; cartesian SVG only needs this import-time probe. + const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext') + .mockReturnValue({ measureText: () => ({ width: 0 }) } as unknown as CanvasRenderingContext2D); + try { + const module = await import('plotly.js-cartesian-dist-min'); + runtime = (module.default ?? module) as typeof runtime; + } finally { canvas.mockRestore(); } + }); + it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => { + expect(runtime.version).toBe('4.1.2'); + const config = runtime.PlotSchema.get().config; + expect(config['showSendToCloud'].valType).toBe('boolean'); + expect(config['displaylogo'].valType).toBe('boolean'); + expect(config['modeBarButtonsToRemove'].valType).toBe('any'); + }); + it.each([ + ['C1', { type: 'scatter', x: [1, 2], y: [3, 4] }], + ['C2', { type: 'bar', x: ['grupo'], y: [100] }], + ['C3r', { type: 'box', x: ['grupo'], q1: [23.5], median: [45], q3: [55], lowerfence: [23.5], upperfence: [55] }], + ])('genera la modebar %s sin envío externo y conserva zoom/pan/restauración', async (_contract, trace) => { + const host = document.createElement('div'); + document.body.append(host); + const figure: PlotlyFigure = { data: [trace], layout: { width: 600, height: 400 } }; + const original = JSON.stringify(figure); + let controller!: PlotlyController; + try { + await new Promise((resolve, reject) => { + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') resolve(); + if (state === 'error') reject(new Error('Plotly failed to render')); + }); + controller.setFigure(figure); + }); + const buttons = Array.from(host.querySelectorAll('.modebar-btn')); + const titles = buttons.map(button => button.getAttribute('data-title')); + expect(titles).not.toContain('Share chart...'); + expect(titles).toEqual(expect.arrayContaining(['Zoom', 'Pan', 'Zoom in', 'Zoom out', 'Autoscale', 'Reset axes', 'Download plot as a PNG'])); + expect(host.querySelector('.modebar a[href]')).toBeNull(); + const rendered = host as unknown as HTMLElement & { _fullLayout: { dragmode: string } }; + for (const [title, mode] of [['Pan', 'pan'], ['Zoom', 'zoom']]) { + buttons.find(button => button.getAttribute('data-title') === title)! + .dispatchEvent(new MouseEvent('click', { bubbles: true })); + await vi.waitFor(() => expect(rendered._fullLayout.dragmode).toBe(mode)); + } + expect(JSON.stringify(figure)).toBe(original); + } finally { + controller?.destroy(); host.remove(); + } + }); +}); diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts new file mode 100644 index 0000000..9ac0add --- /dev/null +++ b/src/app/shared/plotly/plotly-controller.ts @@ -0,0 +1,87 @@ +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; +import { PlotlyRuntime } from './plotly-runtime'; + +// One serialized queue owns the host. A completed stale operation cannot expose +// its graph or overwrite a newer react operation. Resize uses the same queue. +export class PlotlyController { + private desired?: PlotlyFigure; + private version = 0; + private rendered = -1; + private busy = false; + private destroyed = false; + private resizePending = false; + private plotly?: PlotlyRuntime; + private frameCount = 0; + constructor(private host: HTMLElement, private load: () => Promise, + private state: (state: 'loading' | 'ready' | 'error') => void) {} + + setFigure(figure: PlotlyFigure) { + if (this.destroyed) return; + this.desired = figure; + this.version++; + this.host.style.visibility = 'hidden'; + this.state('loading'); + void this.drain(); + } + resize() { + if (this.destroyed || this.rendered < 0) return; + this.resizePending = true; + void this.drain(); + } + destroy() { + this.destroyed = true; + this.host.style.visibility = 'hidden'; + this.plotly?.purge(this.host); + } + private async drain() { + if (this.busy || this.destroyed) return; + this.busy = true; + try { + this.plotly ??= await this.load(); + while (!this.destroyed && (this.rendered !== this.version || this.resizePending)) { + const version = this.version; + try { + if (this.rendered !== version && this.desired) { + // Plotly may mutate inputs; clone the complete JSON without changing values. + const figure = structuredClone(this.desired); + if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i)); + this.frameCount = 0; + if (this.destroyed) break; + await this.plotly.react(this.host, figure.data, figure.layout, { + ...figure.config, responsive: false, displaylogo: false, + showSendToCloud: false, + modeBarButtonsToRemove: ['sendChartToCloud'], + }); + if (this.destroyed) break; + if (version !== this.version) continue; + if (figure.frames?.length) { + await this.plotly.addFrames(this.host, figure.frames); + this.frameCount = figure.frames.length; + } + if (this.destroyed) break; + if (version !== this.version) continue; + this.rendered = version; + this.host.style.visibility = 'visible'; + this.state('ready'); + } else { + this.resizePending = false; + await this.plotly.Plots.resize(this.host); + } + } catch { + if (this.destroyed) break; + if (version !== this.version) continue; + this.rendered = version; + this.resizePending = false; + this.host.style.visibility = 'hidden'; + this.state('error'); + } + } + } catch { + if (!this.destroyed) this.state('error'); + } finally { + this.busy = false; + // A pending react can recreate internal resources after the first purge. + if (this.destroyed) this.plotly?.purge(this.host); + } + } +} diff --git a/src/app/shared/plotly/plotly-runtime.spec.ts b/src/app/shared/plotly/plotly-runtime.spec.ts new file mode 100644 index 0000000..343db46 --- /dev/null +++ b/src/app/shared/plotly/plotly-runtime.spec.ts @@ -0,0 +1,23 @@ +import { vi } from 'vitest'; +import { loadPlotly } from './plotly-runtime'; + +it('carga una sola instancia oficial con el esquema requerido por C1/C2/C3r', async () => { + // No chart rendering in jsdom. Schema inspection only needs browser globals. + const canvas = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null); + try { + const first = loadPlotly(); + expect(loadPlotly()).toBe(first); + const runtime = await first as unknown as { version: string; PlotSchema: { get(): any } }; + expect(runtime.version).toBe('4.1.2'); + const schema = runtime.PlotSchema.get(); + expect(schema.traces.scatter).toBeDefined(); + expect(schema.traces.bar).toBeDefined(); + expect(schema.traces.box).toBeDefined(); + expect(schema.traces.scatter.attributes.error_y).toBeDefined(); + expect(schema.layout.layoutAttributes.xaxis.type.values).toContain('multicategory'); + expect(schema.traces.scatter.layoutAttributes.scattermode.values).toContain('group'); + expect(schema.traces.box.layoutAttributes.boxmode.values).toContain('group'); + for (const key of ['q1', 'median', 'q3', 'lowerfence', 'upperfence']) expect(schema.traces.box.attributes[key]).toBeDefined(); + for (const key of ['annotations', 'template', 'paper_bgcolor', 'plot_bgcolor']) expect(schema.layout.layoutAttributes[key]).toBeDefined(); + } finally { canvas.mockRestore(); } +}); diff --git a/src/app/shared/plotly/plotly-runtime.ts b/src/app/shared/plotly/plotly-runtime.ts new file mode 100644 index 0000000..4179389 --- /dev/null +++ b/src/app/shared/plotly/plotly-runtime.ts @@ -0,0 +1,20 @@ +import { InjectionToken } from '@angular/core'; +import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; + +// Narrow boundary for the official partial bundle, which ships without declarations. +export interface PlotlyRuntime { + react(host: HTMLElement, data: PlotlyFigure['data'], layout: PlotlyFigure['layout'], config: Record): Promise; + purge(host: HTMLElement): void; + Plots: { resize(host: HTMLElement): Promise }; + addFrames(host: HTMLElement, frames: Record[]): Promise; + deleteFrames(host: HTMLElement, indices: number[]): Promise; +} +let runtime: Promise | undefined; +export function loadPlotly(): Promise { + return runtime ??= import('plotly.js-cartesian-dist-min') + .then(module => (module.default ?? module) as unknown as PlotlyRuntime) + .catch(error => { runtime = undefined; throw error; }); +} + +export const PLOTLY_LOADER = new InjectionToken<() => Promise>('PLOTLY_LOADER', { providedIn: 'root', factory: () => loadPlotly }); + diff --git a/src/app/shared/plotly/plotly.d.ts b/src/app/shared/plotly/plotly.d.ts new file mode 100644 index 0000000..4c7c94a --- /dev/null +++ b/src/app/shared/plotly/plotly.d.ts @@ -0,0 +1 @@ +declare module 'plotly.js-cartesian-dist-min'; From b1c4b78f322017851973999bd3cd8dddab1f52e7 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Mon, 12 Oct 2026 16:39:37 -0600 Subject: [PATCH 02/51] feat(indicadores): habilitar dashboards Angular TEA CaCu y CaMa --- proxy.conf.json | 2 + src/app/app.routes.spec.ts | 33 +- src/app/app.routes.ts | 5 +- .../indicadores/indicadores-page.html | 27 +- .../indicadores/indicadores-page.scss | 4 +- .../indicadores/indicadores-page.spec.ts | 89 +- .../features/indicadores/indicadores-page.ts | 74 +- .../indicadores/indicadores.models.spec.ts | 11 + .../indicadores/indicadores.models.ts | 18 +- .../indicadores.presentation.spec.ts | 45 + .../indicadores/indicadores.presentation.ts | 31 + .../indicadores/indicadores.service.spec.ts | 37 +- .../indicadores/indicadores.service.ts | 27 +- .../indicadores.synthetic-fixtures.ts | 4654 +++++++++++++++++ .../shared/plotly/plotly-controller.spec.ts | 20 + 15 files changed, 5036 insertions(+), 41 deletions(-) create mode 100644 src/app/features/indicadores/indicadores.presentation.spec.ts create mode 100644 src/app/features/indicadores/indicadores.presentation.ts create mode 100644 src/app/features/indicadores/indicadores.synthetic-fixtures.ts diff --git a/proxy.conf.json b/proxy.conf.json index cab47d0..35eff4c 100644 --- a/proxy.conf.json +++ b/proxy.conf.json @@ -1,4 +1,6 @@ { "/tea/**": { "target": "http://127.0.0.1:5000", "secure": false }, + "/cacu/**": { "target": "http://127.0.0.1:5000", "secure": false }, + "/cama/**": { "target": "http://127.0.0.1:5000", "secure": false }, "/health": { "target": "http://127.0.0.1:5000", "secure": false } } diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts index 1642c9a..6f041e4 100644 --- a/src/app/app.routes.spec.ts +++ b/src/app/app.routes.spec.ts @@ -1,6 +1,6 @@ import { routes } from './app.routes'; import { TestBed } from '@angular/core/testing'; -import { provideRouter } from '@angular/router'; +import { Router, provideRouter } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -9,8 +9,39 @@ it('permite acceso directo a /indicadores sin guard ni autenticación', async () TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); const harness = await RouterTestingHarness.create(); await harness.navigateByUrl('/indicadores', IndicadoresPage); + expect(TestBed.inject(Router).url).toBe('/indicadores/tea'); expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores'); const http = TestBed.inject(HttpTestingController); http.expectOne('/tea/indicadores').flush([]); http.verify(); }); + +for (const dominio of ['tea', 'cacu', 'cama']) { + it(`navega directamente al dominio ${dominio} y conserva la ruta compartida diferida`, async () => { + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); + const harness = await RouterTestingHarness.create(); + const page = await harness.navigateByUrl(`/indicadores/${dominio}`, IndicadoresPage); + expect(page.dominio).toBe(dominio); + const http = TestBed.inject(HttpTestingController); + http.expectOne(`/${dominio}/indicadores`).flush([]); + expect(harness.routeNativeElement?.querySelectorAll('nav a').length).toBe(3); + http.verify(); + }); +} +it('cancela catálogos pendientes durante navegación rápida entre dominios', async () => { + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); + const harness = await RouterTestingHarness.create(); + const http = TestBed.inject(HttpTestingController); + await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + const tea = http.expectOne('/tea/indicadores'); + await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); + const cacu = http.expectOne('/cacu/indicadores'); + const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); + expect(tea.cancelled).toBe(true); + expect(cacu.cancelled).toBe(true); + expect(() => tea.flush([])).toThrow(); + http.expectOne('/cama/indicadores').flush([]); + expect(page.dominio).toBe('cama'); + expect(page.catalog()).toEqual([]); + http.verify(); +}); diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 1baddca..dfee9b7 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -1,5 +1,8 @@ import { Routes } from '@angular/router'; +import { DOMINIOS } from './features/indicadores/indicadores.models'; +const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage); export const routes: Routes = [ - { path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) }, + { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, + ...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, data: { dominio }, loadComponent: loadIndicadores })), ]; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index bd02f06..a96810b 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -1,9 +1,14 @@
- Dominio TEA · Investigación + Dominio {{ domainLabels[dominio] }} · Investigación

Dashboard de indicadores

-

Explora las figuras de indicadores TEA generadas por el servicio de reportes.

+

Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.

+

Uso exclusivo de investigación. No usar para decisiones clínicas.

@if (catalogLoading()) { @@ -28,9 +33,16 @@ @for (figure of selected?.figuras ?? []; track $index) { {{ figure }} } + Tipo de periodo + + @for (tipo of selected?.tipos_periodo ?? []; track tipo) { + {{ tipo === 'mes' ? 'Mes' : 'Semestre' }} + } + + Periodos - Todos los periodos con reporte + Todos con reporte Selección manual @@ -40,13 +52,14 @@ @if (periodMode === 'manual') { - Semestres (AAAA-S1,AAAA-S2) + {{ periodLabel }} - Escribe los semestres a consultar. Su disponibilidad depende de los reportes. + Escribe periodos del tipo seleccionado, separados por comas. Su disponibilidad depende de los reportes. } @if (periodError) { } +

Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.

Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.

@if (selected) { @@ -69,8 +82,8 @@ @if (hasNoVisibleValues(figure)) {

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

} -

{{ selected?.titulo }}

- +

+ } @else {

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

} diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index b570559..2385f43 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -17,10 +17,10 @@ mat-form-field { width: 100%; min-width: 0; } .period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); } .validation { color: var(--mat-sys-error); } .figure-card { overflow: hidden; min-width: 0; } -.figure-title { display: none; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; } +.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; } .state { padding: 1.25rem; margin: 0; } .dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } -@media (max-width: 850px) { .figure-title { display: block; } .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@media (max-width: 850px) { .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @media (max-width: 550px) { .fields { grid-template-columns: minmax(0, 1fr); } .indicator { grid-column: auto; } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 3611cee..3a78c85 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -1,7 +1,9 @@ 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 { syntheticCatalogs } from './indicadores.synthetic-fixtures'; import { PlotlyFigure } from './indicadores.models'; import { Component } from '@angular/core'; import { IndicadoresPage } from './indicadores-page'; @@ -10,16 +12,16 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; @Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' }) class ChartStub { figure?: PlotlyFigure; } const catalog = [ - { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'] }, - { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'] }, - { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [] }, + { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }, + { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] }, + { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] }, ]; describe('IndicadoresPage', () => { let page: IndicadoresPage; let http: HttpTestingController; let fixture: ReturnType>; beforeEach(() => { - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; @@ -28,6 +30,75 @@ describe('IndicadoresPage', () => { afterEach(() => { fixture.destroy(); http.verify(); }); function load() { http.expectOne('/tea/indicadores').flush(catalog); } function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + + it('cancela figura y catálogo antiguos al cambiar dominios rápidamente', () => { + load(); const oldFigure = figure(); + page.changeDominio('cacu'); + expect(oldFigure.cancelled).toBe(true); + expect(page.result().figure).toBeUndefined(); + expect(page.catalog()).toEqual([]); + const oldCatalog = http.expectOne('/cacu/indicadores'); + page.changeDominio('cama'); + expect(oldCatalog.cancelled).toBe(true); + http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama); + const current = http.expectOne(r => r.url.startsWith('/cama/indicadores/') && r.url.includes('/figuras/')); + current.flush({ data: [{ y: [null, 42] }], layout: {} }); + expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); + expect(() => oldFigure.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(page.dominio).toBe('cama'); + expect(page.result().figure?.data[0]['y']).toEqual([null, 42]); + }); + it.each(['cacu', 'cama'] as const)('usa meses publicados y ayuda sin Wilson efectivo en %s', dominio => { + http.expectOne('/tea/indicadores').flush([]); + page.changeDominio(dominio); + http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]); + const initial = http.expectOne(r => r.url.includes('/figuras/')); + page.changeTipoPeriodo('mes'); + expect(initial.cancelled).toBe(true); + expect(page.periodMode).toBe('manual'); + expect(page.periodText).toBe(''); + expect(page.result().status).toBe('idle'); + page.changePeriodText('2025-01,2025-02,2025-01'); + const monthly = http.expectOne(r => r.url.includes('/figuras/')); + expect(monthly.request.params.get('periodos')).toBe('2025-01,2025-02'); + page.changePeriodText('2025-13'); + expect(monthly.cancelled).toBe(true); + expect(page.periodError).toContain('01 al 12'); + page.changePeriodText('2025-01,2025-S1'); + http.expectNone(r => r.url.includes('/figuras/')); + page.changePeriodMode('todos'); + expect(page.periodError).toContain('primer tipo publicado'); + http.expectNone(r => r.url.includes('/figuras/')); + page.changeTipoPeriodo('semestre'); + const semesters = http.expectOne(r => r.url.includes('/figuras/')); + expect(semesters.request.params.has('periodos')).toBe(false); + semesters.flush({ data: [{ y: [null, 0] }], layout: {} }); + fixture.detectChanges(); + const help = fixture.nativeElement.querySelector('.interpretation').textContent; + expect(help).toContain('no entregan intervalos Wilson efectivos'); + expect(help).toContain('eje horizontal muestra el periodo'); + expect(help).toContain('suprimidos no representan tasas observadas de 0 %'); + expect(help).not.toContain('La línea vertical representa el intervalo'); + }); + it('acepta futuros indicadores y figuras desde catálogo sin fijar cantidades ni contratos por dominio', () => { + http.expectOne('/tea/indicadores').flush([]); + page.changeDominio('cama'); + const future = [ + ...syntheticCatalogs.cama, + { id: 'synthetic_future', titulo: 'Fixture futuro', contrato: 'C2', figuras: ['fig_c2_apiladas', 'fig_c1_puntos'], tipos_periodo: ['mes', 'semestre'] }, + ]; + http.expectOne('/cama/indicadores').flush(future); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + page.selectIndicador('synthetic_future'); + expect(page.tipoPeriodo).toBe('mes'); + const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas')); + expect(req.request.params.has('periodos')).toBe(false); + req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } }); + expect(page.interpretation.join(' ')).toContain('composición porcentual'); + page.selectFigura('fig_c1_puntos'); + http.expectOne(r => r.url.includes('/fig_c1_puntos')).flush({ data: [], layout: {} }); + expect(page.interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos'); + }); it('presenta carga y elige una primera figura válida desde el catálogo', () => { expect(page.catalogLoading()).toBe(true); load(); @@ -68,7 +139,7 @@ describe('IndicadoresPage', () => { expect(help).toContain('min/max'); expect(help).not.toContain('Wilson'); figure().flush({ data: [], layout: {} }); }); - it('entrega al gráfico el JSON íntegro sin modificarlo al presentar la ayuda', () => { + it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => { load(); const received: PlotlyFigure = { data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }], @@ -80,8 +151,12 @@ describe('IndicadoresPage', () => { expect(JSON.stringify(received)).toBe(original); expect(page.result().figure).toEqual(received); const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; - expect(chart.figure).toBe(page.result().figure); - expect(JSON.stringify(chart.figure)).toBe(original); + expect(chart.figure).toBe(page.result().presentationFigure); + expect(chart.figure).not.toBe(page.result().figure); + expect(chart.figure?.data).toEqual(received.data); + expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } }); + expect(JSON.stringify(page.result().figure)).toBe(original); + expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); }); it('muestra catálogo vacío y permite recargar', () => { http.expectOne('/tea/indicadores').flush([]); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 0532cf8..1172899 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -1,6 +1,7 @@ import { Component, DestroyRef, inject, signal } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ActivatedRoute, RouterLink } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; @@ -9,8 +10,9 @@ import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; -import { FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models'; +import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; +import { figureTitle, presentationFigure } from './indicadores.presentation'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; export function httpMessage(error: unknown, catalog = false): string { @@ -25,7 +27,7 @@ export function httpMessage(error: unknown, catalog = false): string { const CONTRACT_INTERPRETATIONS: Readonly> = { C1: [ 'El punto representa la proporción observada.', - 'La línea vertical representa el intervalo de confianza Wilson al 95 %.', + 'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.', 'Los intervalos amplios pueden deberse a denominadores pequeños.', 'Un porcentaje observado del 100 % no implica certeza poblacional.', ], @@ -42,16 +44,21 @@ const CONTRACT_INTERPRETATIONS: Readonly> = { }; const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.']; -type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; message?: string }; +type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; message?: string }; @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); + private readonly route = inject(ActivatedRoute, { optional: true }); + readonly dominios = DOMINIOS; + dominio: Dominio = 'tea'; + readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; + tipoPeriodo: TipoPeriodo = 'semestre'; private readonly catalogRequests = new Subject(); private readonly figureRequests = new Subject(); readonly catalog = signal([]); @@ -59,6 +66,7 @@ export class IndicadoresPage { readonly catalogError = signal(''); readonly result = signal({ status: 'idle' }); readonly hasNoVisibleValues = hasNoVisibleValues; + readonly figureTitle = figureTitle; indicadorId = ''; figuraId = ''; periodMode: 'todos' | 'manual' = 'todos'; @@ -68,15 +76,30 @@ export class IndicadoresPage { get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); } get interpretation(): readonly string[] { - const contract = this.selected?.contrato; + const contract = this.figuraId.startsWith('fig_c1') ? 'C1' + : this.figuraId.startsWith('fig_c2') ? 'C2' + : this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato; + if (contract === 'C2' && this.dominio !== 'tea') return [ + 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.', + ]; + if (contract === 'C1' && this.dominio !== 'tea') return [ + 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.', + 'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.', + 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ]; return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) - ? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION; + ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION; } constructor() { + const initialDomain: unknown = this.route?.snapshot.data['dominio']; + if (isDominio(initialDomain)) this.dominio = initialDomain; this.figureRequests.pipe(switchMap(selection => selection ? this.service.figura(selection).pipe( - map(figure => ({ status: 'ready', figure }) as FigureState), + map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState), catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)), startWith({ status: 'loading' } as FigureState)) : of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef)) @@ -86,8 +109,9 @@ export class IndicadoresPage { this.catalogError.set(''); this.catalog.set([]); this.indicadorId = this.figuraId = ''; + this.resetPeriodos('semestre'); this.figureRequests.next(null); - return this.service.catalogo().pipe(map(items => ({ items, error: '' })), + return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })), catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { this.catalogLoading.set(false); @@ -96,10 +120,31 @@ export class IndicadoresPage { if (items.length) this.selectIndicador(items[0].id); }); } + changeDominio(dominio: Dominio) { + if (!isDominio(dominio) || dominio === this.dominio) return; + this.dominio = dominio; + this.catalogRequests.next(); + } + private resetPeriodos(tipo: TipoPeriodo) { + this.tipoPeriodo = tipo; + this.periodText = this.periodError = ''; + this.periodMode = 'todos'; + } + changeTipoPeriodo(tipo: TipoPeriodo) { + if (!this.selected?.tipos_periodo.includes(tipo)) return; + this.resetPeriodos(tipo); + if (tipo !== this.selected.tipos_periodo[0]) this.periodMode = 'manual'; + this.requestFigure(); + } + get periodLabel(): string { return this.tipoPeriodo === 'mes' ? 'Meses (AAAA-MM)' : 'Semestres (AAAA-S1,AAAA-S2)'; } retryCatalog() { this.catalogRequests.next(); } selectIndicador(id: string) { this.indicadorId = id; this.figuraId = this.selected?.figuras[0] ?? ''; + if (!this.selected?.tipos_periodo.includes(this.tipoPeriodo) + || (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0])) { + this.resetPeriodos(this.selected?.tipos_periodo[0] ?? 'semestre'); + } this.requestFigure(); } selectFigura(id: string) { this.figuraId = id; this.requestFigure(); } @@ -108,12 +153,17 @@ export class IndicadoresPage { changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); } requestFigure() { this.periodError = ''; - const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText) : undefined; - if (periodos === null) this.periodError = 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.'; - if (!this.selected || !this.selected.figuras.includes(this.figuraId) || periodos === null) { + const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText, this.tipoPeriodo) : undefined; + if (periodos === null) this.periodError = this.tipoPeriodo === 'mes' + ? 'Introduce meses AAAA-MM del 01 al 12 separados por comas.' + : 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.'; + if (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0]) { + this.periodError = 'Selecciona periodos explícitos para este tipo; el servicio usa solo el primer tipo publicado al omitir periodos.'; + } + if (!this.selected || !this.selected.figuras.includes(this.figuraId) || !this.selected.tipos_periodo.includes(this.tipoPeriodo) || periodos === null || !!this.periodError) { this.figureRequests.next(null); return; } - this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos }); + this.figureRequests.next({ dominio: this.dominio, tipoPeriodo: this.tipoPeriodo, indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos }); } } diff --git a/src/app/features/indicadores/indicadores.models.spec.ts b/src/app/features/indicadores/indicadores.models.spec.ts index abe4e01..820dcf4 100644 --- a/src/app/features/indicadores/indicadores.models.spec.ts +++ b/src/app/features/indicadores/indicadores.models.spec.ts @@ -21,3 +21,14 @@ describe('Periodos y visibilidad conservadora', () => { expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false); }); }); + +it('deduplica meses en orden estable y valida el calendario sin mezclar tipos', () => { + expect(parsePeriodos('2025-12, 2025-01,2025-12', 'mes')).toEqual(['2025-12', '2025-01']); + for (const value of ['', '2025-00', '2025-13', '2025-1', '2025-S1', '2025-01,2025-S1']) { + expect(parsePeriodos(value, 'mes')).toBeNull(); + } + expect(parsePeriodos('2025-S1,2025-01', 'semestre')).toBeNull(); +}); +it('no interpreta NaN ni null como porcentajes cero', () => { + expect(hasNoVisibleValues({ data: [{ y: [NaN, null] }], layout: {} })).toBe(true); +}); diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 6b26103..07d8bd1 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -1,8 +1,19 @@ +export const DOMINIOS = ['tea', 'cacu', 'cama'] as const; +export type Dominio = typeof DOMINIOS[number]; +export type TipoPeriodo = 'semestre' | 'mes'; +export function isDominio(value: unknown): value is Dominio { + return typeof value === 'string' && DOMINIOS.some(domain => domain === value); +} +export function requireDominio(value: unknown): Dominio { + if (!isDominio(value)) throw new Error('Dominio no permitido'); + return value; +} export interface Indicador { id: string; titulo: string; contrato: string; figuras: string[]; + tipos_periodo: TipoPeriodo[]; } // Keep the complete HTTP figure, including future attributes and interpretation notes. @@ -14,11 +25,12 @@ export interface PlotlyFigure { [key: string]: unknown; } export type Tema = 'claro' | 'oscuro'; -export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; } +export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; indicador: string; figura: string; tema: Tema; periodos?: string[]; } -export function parsePeriodos(value: string): string[] | null { +export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null { + if (tipo !== 'semestre' && tipo !== 'mes') return null; const parts = value.split(',').map(part => part.trim()); - return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part)) + return parts.length && parts.every(part => (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part)) ? [...new Set(parts)] : null; } diff --git a/src/app/features/indicadores/indicadores.presentation.spec.ts b/src/app/features/indicadores/indicadores.presentation.spec.ts new file mode 100644 index 0000000..4e22749 --- /dev/null +++ b/src/app/features/indicadores/indicadores.presentation.spec.ts @@ -0,0 +1,45 @@ +import { figureTitle, presentationFigure } from './indicadores.presentation'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; + +const selection: FigureSelection = { dominio: 'cacu', figura: 'fig_c1_puntos', indicador: 'x', tipoPeriodo: 'mes', tema: 'claro' }; +const monthly: PlotlyFigure = { + data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01', '2025-02'], y: [100, null, 0], customdata: [[1, 1], [null, null], [0, 1]] }], + layout: { title: { text: 'Título completo
con contexto', font: { size: 18 } }, xaxis: { gridcolor: 'gray' }, annotations: [{ text: 'Nota' }] }, + frames: [{ name: 'original' }], config: { displayModeBar: true }, future: { preserved: true }, +}; +describe('Dashboard presentation', () => { + it.each(['cacu', 'cama'] as const)('ordena ticks mensuales de %s sin cambiar observaciones ni HTTP', dominio => { + const original = structuredClone(monthly); + const adapted = presentationFigure(monthly, { ...selection, dominio }); + expect(monthly).toEqual(original); + expect(adapted.data).toEqual(original.data); + expect(adapted.data).not.toBe(monthly.data); + expect(adapted.frames).toEqual(original.frames); + expect(adapted.config).toEqual(original.config); + expect(adapted['future']).toEqual(original['future']); + expect(adapted.layout['annotations']).toEqual(original.layout['annotations']); + expect(adapted.layout['xaxis']).toEqual({ gridcolor: 'gray', type: 'category', categoryorder: 'array', categoryarray: ['2025-01', '2025-02', '2025-03'], tickmode: 'array', tickvals: ['2025-01', '2025-02', '2025-03'], ticktext: ['2025-01', '2025-02', '2025-03'], tickangle: 0, automargin: true }); + expect(figureTitle(monthly, 'catálogo')).toBe('Título completo
con contexto'); + expect(adapted.layout['title']).toEqual({ text: '', font: { size: 18 } }); + }); + it.each(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c3r_caja'])('preserva ejes y trazas de %s', figura => { + const adapted = presentationFigure(monthly, { ...selection, figura }); + expect(adapted.layout['xaxis']).toEqual(monthly.layout['xaxis']); + expect(adapted.data).toEqual(monthly.data); + }); + it('conserva semestres, TEA, representaciones binarias y figuras vacías', () => { + for (const input of [monthly, { data: [], layout: {} }, { data: [{ type: 'scatter', mode: 'markers', x: ['2025-S1', '2025-S2'], y: { dtype: 'f8', bdata: 'AAAAAAAAVEAAAAAAAABJQA==' } }], layout: { xaxis: { type: 'category' } } }] as PlotlyFigure[]) { + const original = structuredClone(input); + for (const request of [{ ...selection, tipoPeriodo: 'semestre' as const }, { ...selection, dominio: 'tea' as const }, selection]) { + const adapted = presentationFigure(input, request); + expect(adapted.data).toEqual(original.data); + if (input !== monthly || request !== selection) expect(adapted.layout['xaxis']).toEqual(original.layout['xaxis']); + } + expect(input).toEqual(original); + } + }); + it('conserva títulos string y usa catálogo cuando no hay título', () => { + expect(figureTitle({ data: [], layout: { title: 'Título completo' } }, 'fallback')).toBe('Título completo'); + expect(figureTitle({ data: [], layout: { title: { text: '' } } }, 'Catálogo')).toBe('Catálogo'); + }); +}); diff --git a/src/app/features/indicadores/indicadores.presentation.ts b/src/app/features/indicadores/indicadores.presentation.ts new file mode 100644 index 0000000..acaac56 --- /dev/null +++ b/src/app/features/indicadores/indicadores.presentation.ts @@ -0,0 +1,31 @@ +import { FigureSelection, PlotlyFigure } from './indicadores.models'; + +export function figureTitle(figure: PlotlyFigure, fallback: string): string { + const title = figure.layout['title']; + if (typeof title === 'string' && title.trim()) return title; + if (title && typeof title === 'object' && 'text' in title + && typeof title.text === 'string' && title.text.trim()) return title.text; + return fallback; +} + +// Adapt only the dashboard copy; HTTP figures and all observations stay intact. +export function presentationFigure(original: PlotlyFigure, selection: FigureSelection): PlotlyFigure { + const figure = structuredClone(original); + const title = figure.layout['title']; + figure.layout['title'] = title && typeof title === 'object' ? { ...title, text: '' } : { text: '' }; + if ((selection.dominio === 'cacu' || selection.dominio === 'cama') + && selection.figura === 'fig_c1_puntos' && selection.tipoPeriodo === 'mes' + && figure.data.length > 0 + && figure.data.every(trace => trace['type'] === 'scatter' && trace['mode'] === 'markers' + && Array.isArray(trace['x']) && trace['x'].length > 0 + && trace['x'].every(x => typeof x === 'string' && /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(x)))) { + const periods = [...new Set(figure.data.flatMap(trace => trace['x'] as string[]))].sort(); + figure.layout['xaxis'] = { + ...(figure.layout['xaxis'] as Record | undefined), + type: 'category', categoryorder: 'array', categoryarray: periods, + tickmode: 'array', tickvals: periods, ticktext: periods, + tickangle: 0, automargin: true, + }; + } + return figure; +} diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 1b69c41..97f7a16 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -1,6 +1,8 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Dominio } from './indicadores.models'; +import { syntheticCatalogs, syntheticFigures } from './indicadores.synthetic-fixtures'; import { IndicadoresService } from './indicadores.service'; describe('IndicadoresService HTTP', () => { @@ -12,8 +14,41 @@ describe('IndicadoresService HTTP', () => { http = TestBed.inject(HttpTestingController); }); afterEach(() => http.verify()); + + it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => { + service.catalogo(dominio).subscribe(items => { + expect(items).toEqual(syntheticCatalogs[dominio]); + expect(items.length).toBe(dominio === 'tea' ? 18 : 1); + expect(items[0].tipos_periodo).toEqual(dominio === 'tea' ? ['semestre'] : ['semestre', 'mes']); + }); + http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]); + }); + it.each(['tea', 'cacu', 'cama'] as const)('usa la URL de figura del dominio %s', dominio => { + service.figura({ dominio, indicador: 'i', figura: 'f', tema: 'oscuro', tipoPeriodo: dominio === 'tea' ? 'semestre' : 'mes', periodos: [dominio === 'tea' ? '2025-S1' : '2025-01'] }).subscribe(); + const req = http.expectOne(r => r.url === `/${dominio}/indicadores/i/figuras/f`); + expect(req.request.params.get('periodos')).toBe(dominio === 'tea' ? '2025-S1' : '2025-01'); + req.flush({ data: [], layout: {} }); + }); + it('rechaza dominios arbitrarios y periodos mezclados antes de HTTP', () => { + expect(() => service.catalogo('otro' as Dominio)).toThrow('Dominio no permitido'); + expect(() => service.figura({ dominio: '../otro' as Dominio, indicador: 'i', figura: 'f', tema: 'claro' })).toThrow(); + for (const periodos of [['2025-01', '2025-S1'], ['2025-13'], ['2025-00']]) { + expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow(); + } + http.expectNone(() => true); + }); + it.each([{ tipos_periodo: undefined }, { tipos_periodo: [] }, { tipos_periodo: ['anual'] }, { tipos_periodo: ['mes', 'mes'] }])('rechaza tipos de periodo inválidos $tipos_periodo', ({ tipos_periodo }) => { + let error: unknown; + service.catalogo('cacu').subscribe({ error: value => error = value }); + http.expectOne('/cacu/indicadores').flush([{ ...syntheticCatalogs.cacu[0], tipos_periodo }]); + expect(error).toBeInstanceOf(Error); + }); + it.each(syntheticFigures)('conserva el JSON sintético $name con arrays, nulos, anotaciones y bdata', ({ figure }) => { + service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe(value => expect(value).toEqual(figure)); + http.expectOne(r => r.url.includes('/figuras/')).flush(figure); + }); it('consume un arreglo directo sin hardcodear catálogo', () => { - const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }]; + const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }]; let actual: unknown; service.catalogo().subscribe(value => actual = value); http.expectOne('/tea/indicadores').flush(data); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index baf82b3..bf330bb 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -1,7 +1,7 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; -import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models'; +import { Dominio, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models'; function record(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); @@ -9,21 +9,34 @@ function record(value: unknown): value is Record { @Injectable({ providedIn: 'root' }) export class IndicadoresService { private readonly http = inject(HttpClient); - catalogo() { - return this.http.get('/tea/indicadores').pipe(map(value => { + catalogo(dominio: Dominio = 'tea') { + const domain = requireDominio(dominio); + return this.http.get(`/${domain}/indicadores`).pipe(map(value => { if (!Array.isArray(value) || !value.every(item => record(item) - && typeof item['id'] === 'string' && typeof item['titulo'] === 'string' + && typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string' && typeof item['contrato'] === 'string' && Array.isArray(item['figuras']) - && item['figuras'].every((figure: unknown) => typeof figure === 'string'))) { + && item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0) + && Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0 + && item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes') + && new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) { throw new Error('Respuesta de catálogo inválida'); } + if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados'); return value as Indicador[]; })); } figura(selection: FigureSelection) { + const dominio = requireDominio(selection.dominio ?? 'tea'); + if (selection.periodos?.length) { + const text = selection.periodos.join(','); + const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const); + if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) { + throw new Error('Periodos inválidos o de tipos mezclados'); + } + } let params = new HttpParams().set('tema', selection.tema); - if (selection.periodos?.length) params = params.set('periodos', selection.periodos.join(',')); - const url = `/tea/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`; + if (selection.periodos?.length) params = params.set('periodos', [...new Set(selection.periodos.map(periodo => periodo.trim()))].join(',')); + const url = `/${dominio}/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`; return this.http.get(url, { params }).pipe(map(value => { if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record) || !record(value['layout'])) throw new Error('Respuesta de figura inválida'); diff --git a/src/app/features/indicadores/indicadores.synthetic-fixtures.ts b/src/app/features/indicadores/indicadores.synthetic-fixtures.ts new file mode 100644 index 0000000..d43c35d --- /dev/null +++ b/src/app/features/indicadores/indicadores.synthetic-fixtures.ts @@ -0,0 +1,4654 @@ +// Synthetic HTTP-only extracts from G7D.2B query_data.json. +// Source SHA256: 9b04eb5350b73171a7fac5ae498a34712781a598c0a1e6d50a55112587fbdd09 +import { Dominio, Indicador, PlotlyFigure } from './indicadores.models'; + +export const syntheticCatalogs: Record = { + "tea": [ + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K01_evaluacion_3_meses", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Evaluaci\u00f3n iniciada a \u2264 3 meses de la referencia" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K02_evaluacion_auditiva", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Evaluaci\u00f3n auditiva realizada" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K03_evaluacion_desarrollo", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Evaluaci\u00f3n del desarrollo realizada" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K04_ados2_eeg_30_dias", + "tipos_periodo": [ + "semestre" + ], + "titulo": "ADOS-2 y EEG a \u2264 30 d\u00edas" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K05_eeg_20_minutos", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG con \u2265 20 min de registro" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K06_eeg_utilizable", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG utilizable para el an\u00e1lisis" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K07_eeg_fotoestimulacion", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG con fotoestimulaci\u00f3n" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "K08_eeg_sueno", + "tipos_periodo": [ + "semestre" + ], + "titulo": "EEG con sue\u00f1o registrado" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M02_sexo", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Sexo" + }, + { + "contrato": "C3r", + "figuras": [ + "fig_c3r_caja" + ], + "id": "M04_dias_entrevista_ados2", + "tipos_periodo": [ + "semestre" + ], + "titulo": "D\u00edas de la entrevista inicial al ADOS-2" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M05_resultado_mchat", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Resultado del M-CHAT" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M10_clasificacion_ados2_ventana", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Clasificaci\u00f3n del ADOS-2 por ventana" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M12_perfil_ramos", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Perfil de desarrollo por \u00e1rea (Ramos)" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "M12b_sospecha_rgd", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Sospecha de retraso global del desarrollo" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M15_grado_hipoacusia", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Grado de hipoacusia" + }, + { + "contrato": "C2", + "figuras": [ + "fig_c2_apiladas" + ], + "id": "M17_apgar_5min", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Apgar a los cinco minutos" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "M18_ingreso_ucin", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Ingreso a cuidados intensivos neonatales" + }, + { + "contrato": "C1", + "figuras": [ + "fig_c1_grupos" + ], + "id": "M19_antecedentes_maternos", + "tipos_periodo": [ + "semestre" + ], + "titulo": "Antecedentes maternos m\u00e1s frecuentes" + } + ], + "cacu": [ + { + "contrato": "C1", + "figuras": [ + "fig_c1_puntos" + ], + "id": "cacu_eu8", + "tipos_periodo": [ + "semestre", + "mes" + ], + "titulo": "Tasa de referencia a repetir citolog\u00eda" + } + ], + "cama": [ + { + "contrato": "C1", + "figuras": [ + "fig_c1_puntos" + ], + "id": "cama_eu8", + "tipos_periodo": [ + "semestre", + "mes" + ], + "titulo": "Proporci\u00f3n de ex\u00e1menes t\u00e9cnicamente aceptables" + } + ] +}; + +export const syntheticFigures: { name: string; figure: PlotlyFigure }[] = [ + { + "name": "tea_C1", + "figure": { + "data": [ + { + "customdata": [ + [ + 4, + 4 + ], + [ + 1, + 3 + ], + [ + 5, + 7 + ] + ], + "error_y": { + "array": [ + -1.4210854715202004e-14, + 45.90070678588425, + 20.349536246500236 + ], + "arrayminus": [ + 48.989084039692145, + 27.184138931240252, + 35.53512647546602 + ], + "color": "#2a78d6", + "thickness": 2, + "type": "data" + }, + "hovertemplate": "2025-S1
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})", + "marker": { + "color": "#2a78d6", + "line": { + "color": "#fcfcfb", + "width": 2 + }, + "size": 10 + }, + "mode": "markers", + "name": "2025-S1", + "showlegend": true, + "x": [ + "16 a 23 meses", + "24 a 30 meses", + "Total" + ], + "y": [ + 100.0, + 33.33333333333333, + 71.42857142857143 + ], + "type": "scatter" + }, + { + "customdata": [], + "error_y": { + "array": [], + "arrayminus": [], + "color": "#eb6834", + "thickness": 2, + "type": "data" + }, + "hovertemplate": "2025-S2
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})", + "marker": { + "color": "#eb6834", + "line": { + "color": "#fcfcfb", + "width": 2 + }, + "size": 10 + }, + "mode": "markers", + "name": "2025-S2", + "showlegend": true, + "x": [], + "y": [], + "type": "scatter" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "xaxis": { + "type": "category", + "categoryorder": "array", + "categoryarray": [ + "16 a 23 meses", + "24 a 30 meses", + "31 a 36 meses", + "Total" + ], + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "scattermode": "group", + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 150 + }, + "title": { + "text": "Evaluaci\u00f3n iniciada a \u2264 3 meses de la referencia" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "annotations": [ + { + "align": "left", + "font": { + "color": "#52514e", + "size": 11 + }, + "showarrow": false, + "text": "Indicador de calidad para el hospital; no forma parte del tablero del m\u00e9dico. Est\u00e1ndar: inicio de la evaluaci\u00f3n diagn\u00f3stica a \u2264 3 meses de la referencia (NICE QS51, enunciado 1).
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + }, + { + "name": "cacu_C1", + "figure": { + "data": [ + { + "hovertemplate": "%{x}
dato suprimido (conteo bajo)", + "marker": { + "color": "#c3c2b7", + "size": 10, + "symbol": "x" + }, + "mode": "markers", + "name": "suprimido", + "showlegend": false, + "x": [ + "2025-S1", + "2025-S2" + ], + "y": [ + 0, + 0 + ], + "type": "scatter" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 50 + }, + "title": { + "text": "Tasa de referencia a repetir citolog\u00eda" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + } + } + } + }, + { + "name": "cama_C1", + "figure": { + "data": [ + { + "customdata": { + "dtype": "i1", + "bdata": "BAU=", + "shape": "1, 2" + }, + "error_y": { + "array": { + "dtype": "f8", + "bdata": "AAAAAAAA+H8=" + }, + "arrayminus": { + "dtype": "f8", + "bdata": "AAAAAAAA+H8=" + }, + "color": "#2a78d6", + "thickness": 2, + "type": "data" + }, + "hovertemplate": "%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})", + "marker": { + "color": "#2a78d6", + "size": 10 + }, + "mode": "markers", + "name": "valor", + "showlegend": false, + "x": [ + "2025-S1" + ], + "y": { + "dtype": "f8", + "bdata": "AAAAAAAAVEA=" + }, + "type": "scatter" + }, + { + "hovertemplate": "%{x}
dato suprimido (conteo bajo)", + "marker": { + "color": "#c3c2b7", + "size": 10, + "symbol": "x" + }, + "mode": "markers", + "name": "suprimido", + "showlegend": false, + "x": [ + "2025-S2" + ], + "y": [ + 0 + ], + "type": "scatter" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 50 + }, + "title": { + "text": "Proporci\u00f3n de ex\u00e1menes t\u00e9cnicamente aceptables" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + } + } + } + }, + { + "name": "tea_C2", + "figure": { + "data": [ + { + "customdata": [ + 5, + 0 + ], + "hovertemplate": "Femenino
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#E0A030", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Femenino", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 45.45454545454545, + null + ], + "type": "bar" + }, + { + "customdata": [ + 4, + 0 + ], + "hovertemplate": "Masculino
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#2F6DB3", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Masculino", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 36.36363636363637, + null + ], + "type": "bar" + }, + { + "customdata": [ + 1, + 0 + ], + "hovertemplate": "Indeterminado
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#8A9199", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Indeterminado", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 9.090909090909092, + null + ], + "type": "bar" + }, + { + "customdata": [ + 1, + 0 + ], + "hovertemplate": "Sin dato
%{x}
%{y:.1f}% (%{customdata})", + "marker": { + "color": "#C9CDD2", + "line": { + "color": "#fcfcfb", + "width": 2 + } + }, + "name": "Sin dato", + "x": [ + [ + "2025-S1", + "2025-S2" + ], + [ + "Cohorte", + "Cohorte" + ] + ], + "y": [ + 9.090909090909092, + null + ], + "type": "bar" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "legend": { + "traceorder": "normal" + }, + "barmode": "stack", + "yaxis": { + "range": [ + 0, + 100 + ], + "ticksuffix": "%", + "title": { + "text": "porcentaje" + }, + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 150 + }, + "title": { + "text": "Sexo" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "annotations": [ + { + "align": "left", + "font": { + "color": "#52514e", + "size": 11 + }, + "showarrow": false, + "text": "Sexo registrado en el expediente del ni\u00f1o. \u00abSin dato\u00bb: el expediente no lo consigna.
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + }, + { + "name": "tea_C3r", + "figure": { + "data": [ + { + "customdata": [ + 7 + ], + "hovertemplate": "2025-S1
%{x}
n = %{customdata}", + "line": { + "width": 2 + }, + "lowerfence": [ + 23.5 + ], + "marker": { + "color": "#2a78d6" + }, + "median": [ + 45.0 + ], + "name": "2025-S1", + "q1": [ + 23.5 + ], + "q3": [ + 55.0 + ], + "showlegend": true, + "upperfence": [ + 55.0 + ], + "x": [ + "Entrevista inicial \u2192 ADOS-2" + ], + "type": "box" + } + ], + "layout": { + "template": { + "data": { + "histogram2dcontour": [ + { + "type": "histogram2dcontour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "choropleth": [ + { + "type": "choropleth", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "histogram2d": [ + { + "type": "histogram2d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "heatmap": [ + { + "type": "heatmap", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "contourcarpet": [ + { + "type": "contourcarpet", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "contour": [ + { + "type": "contour", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "surface": [ + { + "type": "surface", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + }, + "colorscale": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ] + } + ], + "mesh3d": [ + { + "type": "mesh3d", + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + ], + "scatter": [ + { + "fillpattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + }, + "type": "scatter" + } + ], + "parcoords": [ + { + "type": "parcoords", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolargl": [ + { + "type": "scatterpolargl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "bar": [ + { + "error_x": { + "color": "#2a3f5f" + }, + "error_y": { + "color": "#2a3f5f" + }, + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "bar" + } + ], + "scattergeo": [ + { + "type": "scattergeo", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterpolar": [ + { + "type": "scatterpolar", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "histogram": [ + { + "marker": { + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "histogram" + } + ], + "scattergl": [ + { + "type": "scattergl", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatter3d": [ + { + "type": "scatter3d", + "line": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattermap": [ + { + "type": "scattermap", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scatterternary": [ + { + "type": "scatterternary", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "scattercarpet": [ + { + "type": "scattercarpet", + "marker": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + } + } + ], + "carpet": [ + { + "aaxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "baxis": { + "endlinecolor": "#2a3f5f", + "gridcolor": "white", + "linecolor": "white", + "minorgridcolor": "white", + "startlinecolor": "#2a3f5f" + }, + "type": "carpet" + } + ], + "table": [ + { + "cells": { + "fill": { + "color": "#EBF0F8" + }, + "line": { + "color": "white" + } + }, + "header": { + "fill": { + "color": "#C8D4E3" + }, + "line": { + "color": "white" + } + }, + "type": "table" + } + ], + "barpolar": [ + { + "marker": { + "line": { + "color": "#E5ECF6", + "width": 0.5 + }, + "pattern": { + "fillmode": "overlay", + "size": 10, + "solidity": 0.2 + } + }, + "type": "barpolar" + } + ], + "pie": [ + { + "automargin": true, + "type": "pie" + } + ] + }, + "layout": { + "autotypenumbers": "strict", + "colorway": [ + "#636efa", + "#EF553B", + "#00cc96", + "#ab63fa", + "#FFA15A", + "#19d3f3", + "#FF6692", + "#B6E880", + "#FF97FF", + "#FECB52" + ], + "font": { + "color": "#2a3f5f" + }, + "hovermode": "closest", + "hoverlabel": { + "align": "left" + }, + "paper_bgcolor": "white", + "plot_bgcolor": "#E5ECF6", + "polar": { + "bgcolor": "#E5ECF6", + "angularaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "radialaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "ternary": { + "bgcolor": "#E5ECF6", + "aaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "baxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + }, + "caxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "" + } + }, + "coloraxis": { + "colorbar": { + "outlinewidth": 0, + "ticks": "" + } + }, + "colorscale": { + "sequential": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "sequentialminus": [ + [ + 0.0, + "#0d0887" + ], + [ + 0.1111111111111111, + "#46039f" + ], + [ + 0.2222222222222222, + "#7201a8" + ], + [ + 0.3333333333333333, + "#9c179e" + ], + [ + 0.4444444444444444, + "#bd3786" + ], + [ + 0.5555555555555556, + "#d8576b" + ], + [ + 0.6666666666666666, + "#ed7953" + ], + [ + 0.7777777777777778, + "#fb9f3a" + ], + [ + 0.8888888888888888, + "#fdca26" + ], + [ + 1.0, + "#f0f921" + ] + ], + "diverging": [ + [ + 0, + "#8e0152" + ], + [ + 0.1, + "#c51b7d" + ], + [ + 0.2, + "#de77ae" + ], + [ + 0.3, + "#f1b6da" + ], + [ + 0.4, + "#fde0ef" + ], + [ + 0.5, + "#f7f7f7" + ], + [ + 0.6, + "#e6f5d0" + ], + [ + 0.7, + "#b8e186" + ], + [ + 0.8, + "#7fbc41" + ], + [ + 0.9, + "#4d9221" + ], + [ + 1, + "#276419" + ] + ] + }, + "xaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "yaxis": { + "gridcolor": "white", + "linecolor": "white", + "ticks": "", + "title": { + "standoff": 15 + }, + "zerolinecolor": "white", + "automargin": true, + "zerolinewidth": 2 + }, + "scene": { + "xaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "yaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + }, + "zaxis": { + "backgroundcolor": "#E5ECF6", + "gridcolor": "white", + "linecolor": "white", + "showbackground": true, + "ticks": "", + "zerolinecolor": "white", + "gridwidth": 2 + } + }, + "shapedefaults": { + "line": { + "color": "#2a3f5f" + } + }, + "annotationdefaults": { + "arrowcolor": "#2a3f5f", + "arrowhead": 0, + "arrowwidth": 1 + }, + "geo": { + "bgcolor": "white", + "landcolor": "#E5ECF6", + "subunitcolor": "white", + "showland": true, + "showlakes": true, + "lakecolor": "white" + }, + "title": { + "x": 0.05 + } + } + }, + "yaxis": { + "title": { + "text": "d\u00edas" + }, + "rangemode": "tozero", + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "boxmode": "group", + "font": { + "color": "#0b0b0b", + "family": "system-ui, -apple-system, sans-serif" + }, + "margin": { + "l": 60, + "r": 30, + "t": 50, + "b": 150 + }, + "title": { + "text": "D\u00edas de la entrevista inicial al ADOS-2" + }, + "paper_bgcolor": "#fcfcfb", + "plot_bgcolor": "#fcfcfb", + "xaxis": { + "tickfont": { + "color": "#898781" + }, + "gridcolor": "#e1e0d9", + "zerolinecolor": "#c3c2b7", + "linecolor": "#c3c2b7" + }, + "annotations": [ + { + "align": "left", + "font": { + "color": "#52514e", + "size": 11 + }, + "showarrow": false, + "text": "D\u00edas de la entrevista inicial de psicolog\u00eda a la aplicaci\u00f3n del ADOS-2. La caja va del primer al tercer cuartil y la l\u00ednea es la mediana; no se dibuja cada ni\u00f1o.
Base depurada del proyecto TEA \u00b7 Centro M\u00e9dico ISSSTELE\u00d3N \u2013 UANL \u00b7 Fecha de corte: 2025-08-01
Uso exclusivo de investigaci\u00f3n. No usar para decisiones cl\u00ednicas.", + "x": 0, + "xanchor": "left", + "xref": "paper", + "y": -0.22, + "yanchor": "top", + "yref": "paper" + } + ] + } + } + } +]; diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts index f71f54d..7d6e7cf 100644 --- a/src/app/shared/plotly/plotly-controller.spec.ts +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -1,3 +1,4 @@ +import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures'; import { vi } from 'vitest'; import { PlotlyController } from './plotly-controller'; import { PlotlyRuntime } from './plotly-runtime'; @@ -175,4 +176,23 @@ describe('PlotlyController con Plotly instalado', () => { controller?.destroy(); host.remove(); } }); + it.each(syntheticFigures)('renderiza el JSON G7D.2B $name sin convertir nulos, IC ni bdata', async ({ figure }) => { + const host = document.createElement('div'); + document.body.append(host); + const original = JSON.stringify(figure); + let controller!: PlotlyController; + try { + await new Promise((resolve, reject) => { + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') resolve(); + if (state === 'error') reject(new Error('Plotly synthetic fixture failed')); + }); + controller.setFigure(figure); + }); + expect(host.querySelector('.main-svg')).not.toBeNull(); + expect(host.style.visibility).toBe('visible'); + expect(JSON.stringify(figure)).toBe(original); + } finally { controller?.destroy(); host.remove(); } + }); + }); From ae5e4c5db55d9fc80b97c055aa9fdb5eb48c4b46 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Mon, 12 Oct 2026 23:33:40 -0600 Subject: [PATCH 03/51] refactor(indicadores): extraer componente de figura UX-03 --- .../indicadores/indicador-figure-card.html | 27 ++++ .../indicadores/indicador-figure-card.scss | 12 ++ .../indicadores/indicador-figure-card.spec.ts | 131 ++++++++++++++++++ .../indicadores/indicador-figure-card.ts | 74 ++++++++++ .../indicadores/indicadores-page.html | 29 +--- .../indicadores/indicadores-page.scss | 10 +- .../indicadores/indicadores-page.spec.ts | 11 +- .../features/indicadores/indicadores-page.ts | 51 +------ 8 files changed, 259 insertions(+), 86 deletions(-) create mode 100644 src/app/features/indicadores/indicador-figure-card.html create mode 100644 src/app/features/indicadores/indicador-figure-card.scss create mode 100644 src/app/features/indicadores/indicador-figure-card.spec.ts create mode 100644 src/app/features/indicadores/indicador-figure-card.ts diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html new file mode 100644 index 0000000..cbd23cb --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -0,0 +1,27 @@ +@if (selected) { +
+

Cómo leer esta figura · {{ selected?.contrato }}

+
    + @for (line of interpretation; track $index) {
  • {{ line }}
  • } +
+

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
+} + + @if (state.status === 'loading') { + +

Cargando figura…

+ } @else if (state.status === 'error') { + + } @else if (state.figure; as figure) { + @if (hasNoVisibleValues(figure)) { +

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

+ } +

+

Figura: {{ figuraId }}

+ + } @else { +

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

+ } +
diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss new file mode 100644 index 0000000..576c8a6 --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -0,0 +1,12 @@ +:host { display: block; min-width: 0; } +.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; } +.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); } +.interpretation ul { margin: 0; padding-left: 1.25rem; } +.interpretation li + li { margin-top: .25rem; } +.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); } +.figure-card { overflow: hidden; min-width: 0; } +.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; } +.state { padding: 1.25rem; margin: 0; } +.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } +.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; } +@media (max-width: 550px) { .interpretation { padding: 1rem; } } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts new file mode 100644 index 0000000..d2e4d6d --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -0,0 +1,131 @@ +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { vi } from 'vitest'; +import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; +import { Indicador, PlotlyFigure } from './indicadores.models'; +import { presentationFigure } from './indicadores.presentation'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +describe('IndicadorFigureCard', () => { + const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] }; + let fixture: ReturnType>; + let react: ReturnType; + let purge: ReturnType; + let disconnect: ReturnType; + let observe: ReturnType; + beforeEach(() => { + react = vi.fn().mockResolvedValue(undefined); + purge = vi.fn(); + disconnect = vi.fn(); + observe = vi.fn(); + vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; }); + TestBed.configureTestingModule({ + imports: [IndicadorFigureCard], + providers: [{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ + react, purge, Plots: { resize: vi.fn().mockResolvedValue(undefined) }, + addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined), + }) }], + }); + fixture = TestBed.createComponent(IndicadorFigureCard); + fixture.componentRef.setInput('selected', selected); + fixture.componentRef.setInput('figuraId', 'fig_c1_puntos'); + fixture.componentRef.setInput('dominio', 'tea'); + fixture.componentRef.setInput('tema', 'claro'); + fixture.componentRef.setInput('state', { status: 'idle' }); + }); + afterEach(() => { fixture.destroy(); vi.unstubAllGlobals(); }); + function state(value: FigureState) { fixture.componentRef.setInput('state', value); fixture.detectChanges(); } + async function settle() { + await fixture.whenStable(); + for (let i = 0; i < 12; i++) await Promise.resolve(); + fixture.detectChanges(); + } + function ready(original: PlotlyFigure) { + const copy = presentationFigure(original, { indicador: selected.id, figura: 'fig_c1_puntos', tema: 'claro' }); + state({ status: 'ready', figure: original, presentationFigure: copy }); + return copy; + } + it('muestra carga, error y emite reintento sin coordinar HTTP', () => { + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true'); + expect(fixture.nativeElement.textContent).toContain('Cargando figura'); + const retry = vi.fn(); + fixture.componentInstance.retry.subscribe(retry); + state({ status: 'error', message: 'La figura o los reportes no están disponibles para esta selección.' }); + expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('reportes no están disponibles'); + fixture.nativeElement.querySelector('button').click(); + expect(retry).toHaveBeenCalledTimes(1); + expect(fixture.debugElement.query(By.directive(PlotlyChart))).toBeNull(); + }); + it('presenta selección incompleta y un indicador sin figuras', () => { + state({ status: 'idle' }); + expect(fixture.nativeElement.textContent).toContain('Completa una selección válida'); + fixture.componentRef.setInput('selected', { ...selected, figuras: [] }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles'); + }); + it('presenta título del JSON, identificación secundaria y conserva datos incluso si Plotly los muta', async () => { + const original: PlotlyFigure = { + data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }], + layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] }, + config: { staticPlot: false }, frames: [], extra: { preserved: true }, + }; + const snapshot = JSON.stringify(original); + react.mockImplementation(async (_host, data, layout) => { + data[0].y[0] = 0; + layout.annotations[0].text = 'Cambio interno de Plotly'; + }); + const copy = ready(original); + await settle(); + expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado'); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toContain('fig_c1_puntos'); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy); + expect(JSON.stringify(original)).toBe(snapshot); + expect(copy.data).toEqual(original.data); + expect(copy.layout['annotations']).toEqual(original.layout['annotations']); + }); + it('distingue resultado sin puntos del error y mantiene valores binarios indeterminados', async () => { + ready({ data: [{ y: [null] }], layout: {} }); + await settle(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + expect(fixture.debugElement.query(By.directive(PlotlyChart))).not.toBeNull(); + ready({ data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' } }], layout: {} }); + await settle(); + expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles'); + }); + it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => { + fixture.componentRef.setInput('dominio', dominio); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('no entregan intervalos Wilson efectivos'); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %'); + }); + it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => { + react.mockRejectedValueOnce(new Error('render')); + ready({ data: [{ y: [42] }], layout: {} }); + await settle(); + expect(fixture.nativeElement.textContent).toContain('No se pudo representar la figura'); + const retry = vi.fn(); + fixture.componentInstance.retry.subscribe(retry); + fixture.nativeElement.querySelector('button').click(); + await settle(); + expect(react).toHaveBeenCalledTimes(2); + expect(retry).not.toHaveBeenCalled(); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready'); + }); + it('destruye Plotly al abandonar el resultado y al destruir la card', async () => { + ready({ data: [{ y: [42] }], layout: {} }); + await settle(); + const firstHost = fixture.nativeElement.querySelector('.plot'); + expect(observe).toHaveBeenCalledWith(firstHost); + state({ status: 'loading' }); + expect(purge).toHaveBeenCalledWith(firstHost); + expect(disconnect).toHaveBeenCalledTimes(1); + ready({ data: [{ y: [50] }], layout: {} }); + await settle(); + const secondHost = fixture.nativeElement.querySelector('.plot'); + fixture.destroy(); + expect(purge).toHaveBeenCalledWith(secondHost); + expect(disconnect).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts new file mode 100644 index 0000000..70ce42d --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -0,0 +1,74 @@ +import { Component, Input, output } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; +import { figureTitle } from './indicadores.presentation'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +// The page owns requests; the card receives the original and its presentation copy. +export interface FigureState { + status: 'idle' | 'loading' | 'ready' | 'error'; + figure?: PlotlyFigure; + presentationFigure?: PlotlyFigure; + message?: string; +} + +// Presentation only: contract semantics documented in G3 and G5C. +const CONTRACT_INTERPRETATIONS: Readonly> = { + C1: [ + 'El punto representa la proporción observada.', + 'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.', + 'Los intervalos amplios pueden deberse a denominadores pequeños.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ], + C2: [ + 'Las barras muestran la composición porcentual de cada grupo y periodo.', + 'Las categorías corresponden a la distribución de cada grupo y periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + ], + C3r: [ + 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', + 'Los límites de dibujo no representan necesariamente extremos observados.', + 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', + ], +}; +const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.']; + +@Component({ + selector: 'app-indicador-figure-card', + standalone: true, + imports: [MatButtonModule, MatCardModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicador-figure-card.html', + styleUrl: './indicador-figure-card.scss', +}) +export class IndicadorFigureCard { + @Input({ required: true }) state!: FigureState; + @Input() selected?: Indicador; + @Input({ required: true }) figuraId!: string; + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) tema!: Tema; + readonly retry = output(); + readonly hasNoVisibleValues = hasNoVisibleValues; + readonly figureTitle = figureTitle; + + get interpretation(): readonly string[] { + const contract = this.figuraId.startsWith('fig_c1') ? 'C1' + : this.figuraId.startsWith('fig_c2') ? 'C2' + : this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato; + if (contract === 'C2' && this.dominio !== 'tea') return [ + 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.', + ]; + if (contract === 'C1' && this.dominio !== 'tea') return [ + 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.', + 'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.', + 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ]; + return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) + ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION; + } + +} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a96810b..f13df21 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -62,31 +62,8 @@

Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.

Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.

- @if (selected) { -
-

Cómo leer esta figura · {{ selected?.contrato }}

-
    - @for (line of interpretation; track $index) {
  • {{ line }}
  • } -
-

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

-
- } - - @if (result().status === 'loading') { - -

Cargando figura…

- } @else if (result().status === 'error') { - - } @else if (result().figure; as figure) { - @if (hasNoVisibleValues(figure)) { -

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

- } -

- - } @else { -

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

- } -
+ }
diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index 2385f43..121a972 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -10,20 +10,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .periods { grid-column: 1 / -1; margin-bottom: 1rem; } mat-form-field { width: 100%; min-width: 0; } .contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; } -.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; } -.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); } -.interpretation ul { margin: 0; padding-left: 1.25rem; } -.interpretation li + li { margin-top: .25rem; } -.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); } .validation { color: var(--mat-sys-error); } -.figure-card { overflow: hidden; min-width: 0; } -.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; } .state { padding: 1.25rem; margin: 0; } -.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } @media (max-width: 850px) { .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @media (max-width: 550px) { .fields { grid-template-columns: minmax(0, 1fr); } .indicator { grid-column: auto; } - .filters, .interpretation { padding: 1rem; } + .filters { padding: 1rem; } h1 { font: var(--mat-sys-headline-medium); } } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 3a78c85..11c3fa6 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -7,6 +7,7 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; import { PlotlyFigure } from './indicadores.models'; import { Component } from '@angular/core'; import { IndicadoresPage } from './indicadores-page'; +import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; @Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' }) @@ -22,7 +23,7 @@ describe('IndicadoresPage', () => { let fixture: ReturnType>; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); - TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); @@ -94,10 +95,12 @@ describe('IndicadoresPage', () => { const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas')); expect(req.request.params.has('periodos')).toBe(false); req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } }); - expect(page.interpretation.join(' ')).toContain('composición porcentual'); + fixture.detectChanges(); + expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('composición porcentual'); page.selectFigura('fig_c1_puntos'); http.expectOne(r => r.url.includes('/fig_c1_puntos')).flush({ data: [], layout: {} }); - expect(page.interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos'); + fixture.detectChanges(); + expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos'); }); it('presenta carga y elige una primera figura válida desde el catálogo', () => { expect(page.catalogLoading()).toBe(true); @@ -225,7 +228,7 @@ describe('IndicadoresPage', () => { expect(page.result().message).toContain(message); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toContain('error privado'); - page.requestFigure(); + fixture.nativeElement.querySelector('app-indicador-figure-card button').click(); figure().flush({ data: [], layout: {} }); expect(page.result().status).toBe('ready'); }); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 1172899..5ef81fa 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -10,10 +10,10 @@ import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; -import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models'; +import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, Indicador, parsePeriodos, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { figureTitle, presentationFigure } from './indicadores.presentation'; -import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { presentationFigure } from './indicadores.presentation'; +import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; export function httpMessage(error: unknown, catalog = false): string { if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.'; @@ -23,31 +23,9 @@ export function httpMessage(error: unknown, catalog = false): string { if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.'; return 'No se pudo completar la solicitud. Intenta nuevamente.'; } -// Presentation only: contract semantics documented in G3 and G5C. -const CONTRACT_INTERPRETATIONS: Readonly> = { - C1: [ - 'El punto representa la proporción observada.', - 'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.', - 'Los intervalos amplios pueden deberse a denominadores pequeños.', - 'Un porcentaje observado del 100 % no implica certeza poblacional.', - ], - C2: [ - 'Las barras muestran la composición porcentual de cada grupo y periodo.', - 'Las categorías corresponden a la distribución de cada grupo y periodo.', - 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', - ], - C3r: [ - 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', - 'Los límites de dibujo no representan necesariamente extremos observados.', - 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', - ], -}; -const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.']; - -type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; message?: string }; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -65,8 +43,6 @@ export class IndicadoresPage { readonly catalogLoading = signal(true); readonly catalogError = signal(''); readonly result = signal({ status: 'idle' }); - readonly hasNoVisibleValues = hasNoVisibleValues; - readonly figureTitle = figureTitle; indicadorId = ''; figuraId = ''; periodMode: 'todos' | 'manual' = 'todos'; @@ -75,25 +51,6 @@ export class IndicadoresPage { tema: Tema = 'claro'; get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); } - get interpretation(): readonly string[] { - const contract = this.figuraId.startsWith('fig_c1') ? 'C1' - : this.figuraId.startsWith('fig_c2') ? 'C2' - : this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato; - if (contract === 'C2' && this.dominio !== 'tea') return [ - 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.', - 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', - 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.', - ]; - if (contract === 'C1' && this.dominio !== 'tea') return [ - 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.', - 'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.', - 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.', - 'Un porcentaje observado del 100 % no implica certeza poblacional.', - ]; - return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) - ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION; - } - constructor() { const initialDomain: unknown = this.route?.snapshot.data['dominio']; if (isDominio(initialDomain)) this.dominio = initialDomain; From ea91b31b173a95ee031129c76c6873923c370852 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 13 Oct 2026 00:29:46 -0600 Subject: [PATCH 04/51] feat(indicadores): implementar filtros hibridos y memoria UX-04 --- .../indicadores/indicador-period-filters.html | 50 ++++ .../indicadores/indicador-period-filters.scss | 5 + .../indicador-period-filters.spec.ts | 116 ++++++++ .../indicadores/indicador-period-filters.ts | 73 +++++ .../indicadores/indicadores-memory.spec.ts | 91 +++++++ .../indicadores/indicadores-memory.ts | 73 +++++ .../indicadores-navigation.spec.ts | 74 +++++ .../indicadores/indicadores-page.html | 25 +- .../indicadores/indicadores-page.spec.ts | 253 ++++++++++++++++-- .../features/indicadores/indicadores-page.ts | 107 +++++--- .../indicadores/indicadores.models.spec.ts | 11 + .../indicadores/indicadores.models.ts | 2 +- .../indicadores/indicadores.service.spec.ts | 13 + .../indicadores/indicadores.service.ts | 3 +- 14 files changed, 803 insertions(+), 93 deletions(-) create mode 100644 src/app/features/indicadores/indicador-period-filters.html create mode 100644 src/app/features/indicadores/indicador-period-filters.scss create mode 100644 src/app/features/indicadores/indicador-period-filters.spec.ts create mode 100644 src/app/features/indicadores/indicador-period-filters.ts create mode 100644 src/app/features/indicadores/indicadores-memory.spec.ts create mode 100644 src/app/features/indicadores/indicadores-memory.ts create mode 100644 src/app/features/indicadores/indicadores-navigation.spec.ts diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html new file mode 100644 index 0000000..7ae2e89 --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -0,0 +1,50 @@ +
+
+ @if (types.length > 1) { + Granularidad + + @for (tipo of types; track tipo) { {{ tipo === 'mes' ? 'Mes' : 'Semestre' }} } + + + } + @if (state.tipo === types[0]) { + Modalidad + + Todos los {{ state.tipo === 'mes' ? 'meses' : 'semestres' }} con reporte + Elegir periodos + + + } + @if (entry.draft.mode !== 'todos') { + Periodos seleccionados + + @for (period of entry.added; track period) { {{ period }} } + + Disponibilidad desconocida hasta consultar. + + } +
+@if (entry.draft.mode !== 'todos') { +

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

+
+ Año + {{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }} + + @for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { {{ value }} } + + + +
+
+ @for (period of entry.added; track period) { + + } +
+} +@if (error) { } +

Selección en edición: {{ summary }}

+@if (!canApply) {

Selecciona al menos un periodo válido para aplicar.

} +@if (hasPending) {

Hay cambios sin aplicar.

} + +

Filtros de la consulta aplicada: {{ appliedSummary }}

+
diff --git a/src/app/features/indicadores/indicador-period-filters.scss b/src/app/features/indicadores/indicador-period-filters.scss new file mode 100644 index 0000000..b45eef7 --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.scss @@ -0,0 +1,5 @@ +:host { display: block; margin: 1rem 0; } +.fields { display: flex; flex-wrap: wrap; align-items: start; gap: 1rem; } +mat-form-field { flex: 1; min-width: 160px; } +.error { color: var(--mat-sys-error); } +.remove { display: flex; flex-wrap: wrap; gap: .5rem; } diff --git a/src/app/features/indicadores/indicador-period-filters.spec.ts b/src/app/features/indicadores/indicador-period-filters.spec.ts new file mode 100644 index 0000000..89ccc2a --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.spec.ts @@ -0,0 +1,116 @@ +import { TestBed } from '@angular/core/testing'; +import { NgModel } from '@angular/forms'; +import { By } from '@angular/platform-browser'; +import { MatSelect } from '@angular/material/select'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; + +describe('UX-04 control asistido', () => { + let control: IndicadorPeriodFilters; + let fixture: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorPeriodFilters] }); + fixture = TestBed.createComponent(IndicadorPeriodFilters); + fixture.componentRef.setInput('types', ['semestre', 'mes']); + fixture.componentRef.setInput('state', { tipo: 'semestre', editors: { + semestre: { added: [], draft: { mode: 'todos' } }, mes: { added: [], draft: { mode: 'empty' } }, + }, applied: { tipo: 'semestre', selection: { mode: 'todos' } } }); + fixture.detectChanges(); + control = fixture.componentInstance; + }); + afterEach(() => fixture.destroy()); + 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'); + fixture.detectChanges(); + await Promise.resolve(); + const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; + const model = select.injector.get(NgModel); + const writes = vi.spyOn(model.control, 'setValue'); + const edits = vi.spyOn(control.edited, 'emit'); + for (let i = 0; i < 4; i++) { + fixture.detectChanges(); + await Promise.resolve(); + } + expect(model.control.value).toEqual([]); + 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 () => { + 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 model = select.injector.get(NgModel); + const writes = vi.spyOn(model.control, 'setValue'); + for (let i = 0; i < 3; i++) { + select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.componentInstance.panelOpen).toBe(true); + select.componentInstance.close(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.componentInstance.panelOpen).toBe(false); + } + expect(writes).not.toHaveBeenCalled(); + expect(control.entry.draft.mode).toBe('empty'); + expect(control.state.applied?.tipo).toBe('semestre'); + expect(control.canApply).toBe(false); + }); + it('normaliza el año y rechaza agregar duplicados', () => { + control.changeMode('manual'); + control.year = '1'; control.unit = 'S1'; control.add(); + expect(control.selectedPeriods).toEqual(['0001-S1']); + control.add(); + expect(control.error).toContain('ya está agregado'); + 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(); + expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false); + }); + it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => { + control.changeTipo('mes'); control.year = '2025'; control.unit = unit; control.add(); + 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.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(); + control.unit = 'S2'; control.add(); + control.select(['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(); + expect(select.nativeElement.querySelector('button')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2'); + fixture.nativeElement.querySelector('.remove button').click(); + fixture.detectChanges(); + expect(control.entry.draft.mode).toBe('empty'); + expect(fixture.nativeElement.querySelector('button[mat-flat-button]').disabled).toBe(true); + }); + 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(); + expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled(); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar'); + expect(fixture.nativeElement.textContent).toContain('no es un inventario de reportes'); + expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres'); + 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'); + }); +}); diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts new file mode 100644 index 0000000..abd8749 --- /dev/null +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -0,0 +1,73 @@ +import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; +import { parsePeriodos, TipoPeriodo } from './indicadores.models'; +import { describePeriods, newEditor, FilterState, pending, validDraft } from './indicadores-memory'; + +@Component({ + selector: 'app-indicador-period-filters', + imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule], + templateUrl: './indicador-period-filters.html', + styleUrl: './indicador-period-filters.scss', +}) +export class IndicadorPeriodFilters implements OnChanges { + @Input({ required: true }) state!: FilterState; + @Input({ required: true }) types!: TipoPeriodo[]; + @Output() edited = new EventEmitter(); + @Output() apply = new EventEmitter(); + year = ''; + unit = ''; + error = ''; + readonly months = Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')); + 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. + private readonly emptyPeriods: string[] = []; + get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; } + get canApply() { return validDraft(this.entry.draft, this.state.tipo, this.types); } + 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'; } + 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 = ''; + this.edited.emit(); + } + changeMode(mode: 'todos' | 'manual') { + if (mode === 'todos' && this.state.tipo !== this.types[0]) return; + this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' }; + this.error = ''; + this.edited.emit(); + } + select(values: string[]) { + const unique = [...new Set(values)]; + if (unique.some(p => !this.entry.added.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(); + } + add() { + this.error = ''; + const year = /^\d{1,4}$/.test(this.year) ? this.year.padStart(4, '0') : ''; + const period = year + '-' + this.unit; + if (!parsePeriodos(period, this.state.tipo)) { + this.error = 'Introduce un año entre 0001 y 9999 y una unidad válida.'; + 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]); + } + 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(); + } +} diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts new file mode 100644 index 0000000..d9bdbfb --- /dev/null +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -0,0 +1,91 @@ +import { TestBed } from '@angular/core/testing'; +import { Indicador, TipoPeriodo } from './indicadores.models'; +import { FilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; + +const indicador: Indicador = { id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre', 'mes'] }; +describe('UX-04 memoria temporal', () => { + let memory: IndicadoresMemory; + beforeEach(() => { TestBed.configureTestingModule({}); memory = TestBed.inject(IndicadoresMemory); }); + it('inicia con Todos en el primer tipo del catálogo y vacío independiente en el otro', () => { + const state = memory.restore('tea', indicador, 'f'); + expect(state.editors.semestre?.draft).toEqual({ mode: 'todos' }); + expect(state.editors.mes?.draft).toEqual({ mode: 'empty' }); + expect(state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } }); + expect(pending(state)).toBe(false); + expect(memory.restore('tea', { ...indicador, tipos_periodo: ['mes', 'semestre'] }, 'g').applied?.tipo).toBe('mes'); + }); + it('restaura copias de borradores y aplicación sin compartir referencias', () => { + const state = memory.restore('tea', indicador, 'f'); + state.tipo = 'mes'; + state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } }; + memory.save('tea', 'i', 'f', state); + state.editors.mes.added.push('2025-02'); + const restored = memory.restore('tea', indicador, 'f'); + expect(restored.editors.mes?.added).toEqual(['2025-01']); + expect(restored.applied?.tipo).toBe('semestre'); + expect(pending(restored)).toBe(true); + restored.editors.mes!.added.length = 0; + expect(memory.restore('tea', indicador, 'f').editors.mes?.added).toEqual(['2025-01']); + }); + it('aísla dominios, indicadores y figuras', () => { + const state = memory.restore('tea', indicador, 'f'); + state.editors.semestre = { added: ['2025-S1'], draft: { mode: 'explicit', periodos: ['2025-S1'] } }; + memory.save('tea', 'i', 'f', state); + for (const [domain, item, figure] of [ + ['cacu', indicador, 'f'], ['tea', { ...indicador, id: 'otro' }, 'f'], ['tea', indicador, 'g'], + ] as const) expect(memory.restore(domain, item, figure).editors.semestre?.draft.mode).toBe('todos'); + }); + it('recuerda indicador, tema y figura por indicador', () => { + memory.remember('cacu', 'i', 'g', 'oscuro'); + memory.remember('cacu', 'otro', 'f', 'claro'); + expect(memory.navigation('cacu')).toEqual({ indicador: 'otro', tema: 'claro' }); + expect(memory.selectedFigure('cacu', 'i')).toBe('g'); + expect(memory.navigation('tea')).toBeUndefined(); + }); + it('una instancia nueva reinicia las selecciones y no lee ni escribe almacenamiento', () => { + const localRead = vi.spyOn(Storage.prototype, 'getItem'); + const localWrite = vi.spyOn(Storage.prototype, 'setItem'); + memory.remember('tea', 'otro', 'g', 'oscuro'); + memory.save('tea', 'i', 'f', { tipo: 'mes', editors: { mes: { added: [], draft: { mode: 'empty' } } } }); + const fresh = new IndicadoresMemory(); + expect(fresh.navigation('tea')).toBeUndefined(); + expect(fresh.restore('tea', indicador, 'f').tipo).toBe('semestre'); + expect(localRead).not.toHaveBeenCalled(); expect(localWrite).not.toHaveBeenCalled(); + localRead.mockRestore(); localWrite.mockRestore(); + }); + it('descarta preferencias que dejaron de ser válidas en el catálogo', () => { + const state: FilterState = { tipo: 'mes', editors: { mes: { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } } }, + applied: { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01'] } } }; + memory.save('tea', 'i', 'f', state); + const restored = memory.restore('tea', { ...indicador, tipos_periodo: ['semestre'] }, 'f'); + expect(restored.tipo).toBe('semestre'); + expect(restored.editors.mes).toBeUndefined(); + expect(restored.applied).toBeUndefined(); + expect(pending(restored)).toBe(true); + }); +}); +describe('UX-04 selección discriminada', () => { + it('permite Todos solo en el primer tipo publicado', () => { + expect(validDraft({ mode: 'todos' }, 'semestre', ['semestre', 'mes'])).toBe(true); + expect(validDraft({ mode: 'todos' }, 'mes', ['semestre', 'mes'])).toBe(false); + expect(validDraft({ mode: 'todos' }, 'mes', ['mes', 'semestre'])).toBe(true); + }); + it.each([ + ['semestre', ['2025-S1']], ['semestre', ['0001-S1', '9999-S2']], + ['mes', ['2025-01']], ['mes', ['2025-01', '2025-12']], + ] as [TipoPeriodo, [string, ...string[]]][])('acepta explícitos %s %j', (tipo, periodos) => { + expect(validDraft({ mode: 'explicit', periodos }, tipo, ['semestre', 'mes'])).toBe(true); + }); + it.each([ + ['semestre', ['0000-S1']], ['mes', ['2025-00']], ['mes', ['2025-13']], + ['semestre', ['2025-S3']], ['mes', ['2025-01', '2025-S1']], ['mes', ['2025-01', '2025-01']], + ['semestre', ['2025-S1', '2025-S1']], ['mes', [' 2025-01']], + ] as [TipoPeriodo, [string, ...string[]]][])('rechaza explícitos %s %j', (tipo, periodos) => { + expect(validDraft({ mode: 'explicit', periodos }, tipo, ['semestre', 'mes'])).toBe(false); + }); + it('bloquea vacío, incluso un arreglo vacío forzado en tiempo de ejecución', () => { + expect(validDraft({ mode: 'empty' }, 'semestre', ['semestre'])).toBe(false); + expect(validDraft({ mode: 'explicit', periodos: [] as unknown as [string, ...string[]] }, 'semestre', ['semestre'])).toBe(false); + expect(validDraft({ mode: 'explicit', periodos: ['2025-01'] }, 'mes', ['semestre'])).toBe(false); + }); +}); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts new file mode 100644 index 0000000..9a249c7 --- /dev/null +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -0,0 +1,73 @@ +import { Injectable } from '@angular/core'; +import { Dominio, Indicador, parsePeriodos, Tema, TipoPeriodo } from './indicadores.models'; + +export type PeriodDraft = + | { mode: 'todos' } + | { mode: 'empty' } + | { mode: 'explicit'; periodos: [string, ...string[]] }; +export type AppliedPeriods = Exclude; +export interface PeriodEditor { added: string[]; draft: PeriodDraft; } +export interface FilterState { + tipo: TipoPeriodo; + editors: Partial>; + applied?: { tipo: TipoPeriodo; selection: AppliedPeriods }; +} +export function newEditor(tipo: TipoPeriodo, first: TipoPeriodo): PeriodEditor { + return { added: [], draft: tipo === first ? { mode: 'todos' } : { mode: 'empty' } }; +} +export function validDraft(draft: PeriodDraft, tipo: TipoPeriodo, types: TipoPeriodo[]): draft is AppliedPeriods { + if (!types.includes(tipo) || draft.mode === 'empty') return false; + if (draft.mode === 'todos') return tipo === types[0]; + const parsed = parsePeriodos(draft.periodos.join(','), tipo); + return parsed !== null && parsed.length === draft.periodos.length + && parsed.every((p, i) => p === draft.periodos[i]); +} +export function describePeriods(tipo: TipoPeriodo, draft: PeriodDraft): string { + return draft.mode === 'todos' ? 'Todos los ' + (tipo === 'mes' ? 'meses' : 'semestres') + ' con reporte' + : draft.mode === 'empty' ? 'Sin periodos seleccionados' : draft.periodos.join(', '); +} +export function pending(state: FilterState): boolean { + const applied = state.applied; + const draft = state.editors[state.tipo]!.draft; + if (!applied || applied.tipo !== state.tipo || applied.selection.mode !== draft.mode) return true; + if (draft.mode !== 'explicit' || applied.selection.mode !== 'explicit') return false; + const periodos = applied.selection.periodos; + return draft.periodos.length !== periodos.length + || draft.periodos.some(p => !periodos.includes(p)); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresMemory { + private readonly domains = new Map(); + private readonly figures = new Map(); + private readonly filters = new Map(); + navigation(domain: Dominio) { return this.domains.get(domain); } + selectedFigure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); } + remember(domain: Dominio, indicador: string, figura: string, tema: Tema) { + this.domains.set(domain, { indicador, tema }); + this.figures.set(JSON.stringify([domain, indicador]), figura); + } + private key(domain: Dominio, indicador: string, figura: string) { + return JSON.stringify([domain, indicador, figura]); + } + save(domain: Dominio, indicador: string, figura: string, state: FilterState) { + this.filters.set(this.key(domain, indicador, figura), structuredClone(state)); + } + restore(domain: Dominio, indicador: Indicador, figura: string): FilterState { + const stored = this.filters.get(this.key(domain, indicador.id, figura)); + const first = indicador.tipos_periodo[0]; + const state: FilterState = stored ? structuredClone(stored) : { tipo: first, editors: {} }; + if (!indicador.tipos_periodo.includes(state.tipo)) state.tipo = first; + for (const tipo of ['semestre', 'mes'] as const) { + if (!indicador.tipos_periodo.includes(tipo)) { delete state.editors[tipo]; continue; } + const entry = state.editors[tipo] ?? newEditor(tipo, first); + entry.added = [...new Set(entry.added.filter(p => parsePeriodos(p, tipo)?.[0] === p))]; + if (entry.draft.mode !== 'empty' && !validDraft(entry.draft, tipo, indicador.tipos_periodo)) entry.draft = { mode: 'empty' }; + if (entry.draft.mode === 'explicit' && entry.draft.periodos.some(p => !entry.added.includes(p))) entry.draft = { mode: 'empty' }; + state.editors[tipo] = entry; + } + if (state.applied && !validDraft(state.applied.selection, state.applied.tipo, indicador.tipos_periodo)) delete state.applied; + // Only a new identity receives an initial application. A restored pending draft stays pending. + if (!stored) state.applied = { tipo: first, selection: { mode: 'todos' } }; + return state; + } +} diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts new file mode 100644 index 0000000..5a87c18 --- /dev/null +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -0,0 +1,74 @@ +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, Router } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { By } from '@angular/platform-browser'; +import { routes } from '../../app.routes'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from './indicadores.models'; +import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } + +describe('UX-04 navegación Angular', () => { + let http: HttpTestingController; + async function setup() { + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + return RouterTestingHarness.create(); + } + function load(domain: 'tea' | 'cacu' | 'cama') { + http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]); + const req = http.expectOne(r => r.url.includes('/figuras/')); + req.flush({ data: [{ y: [0, null] }], layout: {} }); + return req; + } + afterEach(() => http.verify()); + it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => { + const harness = await setup(); + const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + load('tea'); harness.detectChanges(); + const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + tea.applyFilters(); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + control.unit = 'S2'; control.add(); + await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu'); + await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama'); + const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + const req = load('tea'); + expect(req.request.params.get('periodos')).toBe('2025-S1'); + expect(restored.filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }); + expect(TestBed.inject(Router).url).toBe('/indicadores/tea'); + }); + it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => { + let harness = await setup(); + const page = await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); + load('cacu'); harness.detectChanges(); + page.changeTema('oscuro'); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add(); + page.applyFilters(); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + const url = TestBed.inject(Router).url; + http.verify(); TestBed.resetTestingModule(); + harness = await setup(); + const restarted = await harness.navigateByUrl(url, IndicadoresPage); + const req = load('cacu'); + expect(TestBed.inject(Router).url).toBe('/indicadores/cacu'); + expect(restarted.indicadorId).toBe(syntheticCatalogs.cacu[0].id); + expect(restarted.tema).toBe('claro'); + expect(restarted.filters?.tipo).toBe('semestre'); + expect(restarted.filters?.editors.mes?.draft.mode).toBe('empty'); + expect(req.request.params.has('periodos')).toBe(false); + expect(req.request.params.get('tema')).toBe('claro'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index f13df21..bebe306 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -33,33 +33,16 @@ @for (figure of selected?.figuras ?? []; track $index) { {{ figure }} } - Tipo de periodo - - @for (tipo of selected?.tipos_periodo ?? []; track tipo) { - {{ tipo === 'mes' ? 'Mes' : 'Semestre' }} - } - - - Periodos - - Todos con reporte - Selección manual - - Tema de la figura ClaroOscuro - @if (periodMode === 'manual') { - {{ periodLabel }} - - Escribe periodos del tipo seleccionado, separados por comas. Su disponibilidad depende de los reportes. - - } - @if (periodError) { } -

Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.

+ @if (filters; as state) { + + }

Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.

{ http = TestBed.inject(HttpTestingController); }); afterEach(() => { fixture.destroy(); http.verify(); }); + function filters() { + fixture.detectChanges(); + return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + } function load() { http.expectOne('/tea/indicadores').flush(catalog); } function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: Material se estabiliza al editar y restaurar %s sin HTTP', async id => { + http.expectOne('/tea/indicadores').flush(syntheticCatalogs.tea); + figure().flush({ data: [], layout: {} }); + page.selectIndicador(id); + figure().flush({ data: [{ type: 'bar', y: [50, 50] }], layout: { barmode: 'stack' } }); + fixture.detectChanges(); + await fixture.whenStable(); + if (id === 'M02_sexo') expect(page.figuraId).toBe('fig_c2_apiladas'); + const result = page.result(); + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; + const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save'); + const child = () => fixture.debugElement.query(By.directive(IndicadorPeriodFilters)); + const mode = () => child().queryAll(By.directive(MatSelect))[0].componentInstance as MatSelect; + async function choose(value: string) { + const select = mode(); + select.open(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.panelOpen).toBe(true); + const option = select.options.find(o => o.value === value)!; + (document.getElementById(option.id) as HTMLElement).click(); + fixture.detectChanges(); await fixture.whenStable(); + expect(select.panelOpen).toBe(false); + } + async function togglePanel() { + const count = saves.mock.calls.length; + for (let i = 0; i < 3; i++) { + const select = mode(); + select.open(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.panelOpen).toBe(true); + select.close(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.panelOpen).toBe(false); + } + expect(saves).toHaveBeenCalledTimes(count); + http.expectNone(() => true); + expect(page.result()).toBe(result); + expect(chart.figure).toBe(result.presentationFigure); + } + await togglePanel(); + await choose('manual'); + expect(filters().entry.draft.mode).toBe('empty'); + expect(filters().canApply).toBe(false); + await togglePanel(); + await choose('todos'); + await choose('manual'); + expect(saves).toHaveBeenCalledTimes(3); + // Restoring the empty pending draft must also settle. + const other = id === 'M02_sexo' ? 'K01_evaluacion_3_meses' : 'M02_sexo'; + page.selectIndicador(other); figure().flush({ data: [], layout: {} }); + page.selectIndicador(id); + const returned = figure(); expect(returned.request.params.has('periodos')).toBe(false); + returned.flush({ data: [], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); + let control = filters(); expect(control.entry.draft.mode).toBe('empty'); + control.year = '2025'; control.unit = 'S1'; control.add(); + fixture.detectChanges(); await fixture.whenStable(); + http.expectNone(() => true); + expect(control.state.applied?.selection.mode).toBe('todos'); + page.selectIndicador(other); figure().flush({ data: [], layout: {} }); + page.selectIndicador(id); + const restored = figure(); expect(restored.request.params.has('periodos')).toBe(false); + restored.flush({ data: [], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); + control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1']); + expect(control.hasPending).toBe(true); + http.expectNone(() => true); + }); it('cancela figura y catálogo antiguos al cambiar dominios rápidamente', () => { load(); const oldFigure = figure(); page.changeDominio('cacu'); @@ -49,28 +121,33 @@ describe('IndicadoresPage', () => { expect(page.dominio).toBe('cama'); expect(page.result().figure?.data[0]['y']).toEqual([null, 42]); }); - it.each(['cacu', 'cama'] as const)('usa meses publicados y ayuda sin Wilson efectivo en %s', dominio => { + it.each(['cacu', 'cama'] as const)('edita meses sin HTTP y conserva ayuda sin Wilson efectivo en %s', dominio => { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(dominio); - http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]); - const initial = http.expectOne(r => r.url.includes('/figuras/')); - page.changeTipoPeriodo('mes'); - expect(initial.cancelled).toBe(true); - expect(page.periodMode).toBe('manual'); - expect(page.periodText).toBe(''); - expect(page.result().status).toBe('idle'); - page.changePeriodText('2025-01,2025-02,2025-01'); + http.expectOne('/' + dominio + '/indicadores').flush(syntheticCatalogs[dominio]); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ y: [null, 0] }], layout: {} }); + const control = filters(); + control.changeTipo('mes'); + expect(control.entry.draft.mode).toBe('empty'); + expect(page.result().status).toBe('ready'); + control.year = '2025'; control.unit = '01'; control.add(); + control.unit = '02'; control.add(); + control.unit = '01'; control.add(); + expect(control.error).toContain('ya está agregado'); + http.expectNone(r => r.url.includes('/figuras/')); + page.applyFilters(); const monthly = http.expectOne(r => r.url.includes('/figuras/')); expect(monthly.request.params.get('periodos')).toBe('2025-01,2025-02'); - page.changePeriodText('2025-13'); + control.unit = '13'; control.add(); + expect(control.error).toContain('unidad válida'); + expect(monthly.cancelled).toBe(false); + control.changeMode('todos'); + expect(control.entry.draft.mode).toBe('explicit'); + control.changeTipo('semestre'); + expect(control.entry.draft.mode).toBe('todos'); + expect(monthly.cancelled).toBe(false); + page.applyFilters(); expect(monthly.cancelled).toBe(true); - expect(page.periodError).toContain('01 al 12'); - page.changePeriodText('2025-01,2025-S1'); - http.expectNone(r => r.url.includes('/figuras/')); - page.changePeriodMode('todos'); - expect(page.periodError).toContain('primer tipo publicado'); - http.expectNone(r => r.url.includes('/figuras/')); - page.changeTipoPeriodo('semestre'); const semesters = http.expectOne(r => r.url.includes('/figuras/')); expect(semesters.request.params.has('periodos')).toBe(false); semesters.flush({ data: [{ y: [null, 0] }], layout: {} }); @@ -91,7 +168,7 @@ describe('IndicadoresPage', () => { http.expectOne('/cama/indicadores').flush(future); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); page.selectIndicador('synthetic_future'); - expect(page.tipoPeriodo).toBe('mes'); + expect(page.filters?.tipo).toBe('mes'); const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas')); expect(req.request.params.has('periodos')).toBe(false); req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } }); @@ -189,21 +266,31 @@ describe('IndicadoresPage', () => { expect(page.figuraId).toBe(''); expect(page.result().status).toBe('idle'); page.selectIndicador('i1'); - expect(page.figuraId).toBe('f1'); + expect(page.figuraId).toBe('f2'); figure().flush({ data: [], layout: {} }); }); - it('valida manuales antes del HTTP y vuelve a Todos sin query', () => { + it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => { load(); figure().flush({ data: [], layout: {} }); - page.changePeriodMode('manual'); - expect(page.periodError).not.toBe(''); + const control = filters(); + control.changeMode('manual'); + expect(control.canApply).toBe(false); + page.applyFilters(); http.expectNone(req => req.url.includes('/figuras/')); - page.changePeriodText('2025-S1, 2025-S2'); + control.year = '2025'; control.unit = 'S1'; control.add(); + control.unit = 'S2'; control.add(); + http.expectNone(req => req.url.includes('/figuras/')); + expect(page.filters?.applied?.selection.mode).toBe('todos'); + page.applyFilters(); const manual = figure(); expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2'); - page.changePeriodText('2025-S3'); + control.select([]); + expect(manual.cancelled).toBe(false); + expect(control.canApply).toBe(false); + page.applyFilters(); + http.expectNone(req => req.url.includes('/figuras/')); + control.changeMode('todos'); + page.applyFilters(); expect(manual.cancelled).toBe(true); - expect(page.result().figure).toBeUndefined(); - page.changePeriodMode('todos'); const all = figure(); expect(all.request.params.has('periodos')).toBe(false); all.flush({ data: [], layout: {} }); @@ -245,4 +332,118 @@ describe('IndicadoresPage', () => { expect(page.catalogError()).toContain('error interno'); page.retryCatalog(); load(); figure().flush({ data: [], layout: {} }); }); + it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => { + load(); figure().flush({ data: [{ y: [0, null] }], layout: {} }); + const control = filters(); control.changeMode('manual'); + control.year = '2025'; control.unit = 'S1'; control.add(); + fixture.detectChanges(); + expect(page.result().figure?.data[0]['y']).toEqual([0, null]); + expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar'); + expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres con reporte'); + http.expectNone(r => r.url.includes('/figuras/')); + }); + it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => { + load(); figure().flush({ data: [{ y: [42] }], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; + for (const period of periodos) { control.unit = period.slice(-2); control.add(); } + page.applyFilters(); + const req = figure(); + expect(page.result().figure).toBeUndefined(); + req.flush('private', { status: 404, statusText: 'Not Found' }); + expect(page.result().status).toBe('error'); + expect(page.result().figure).toBeUndefined(); + expect(page.result().message).toContain('esta selección'); + expect(page.result().message).not.toContain('2025'); + if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos'); + expect(control.selectedPeriods).toEqual(periodos); + control.select([]); + page.requestFigure(); + const retry = figure(); + expect(retry.request.params.get('periodos')).toBe(periodos.join(',')); + retry.flush({ data: [{ y: [null] }], layout: {} }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + expect(control.entry.draft.mode).toBe('empty'); + }); + it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => { + load(); figure().flush({ data: [], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + page.applyFilters(); figure().flush({ data: [{ y: [20] }], layout: {} }); + control.unit = 'S2'; control.add(); + page.changeTema('oscuro'); + const themed = figure(); + expect(themed.request.params.get('periodos')).toBe('2025-S1'); + expect(themed.request.params.get('tema')).toBe('oscuro'); + themed.flush('error', { status: 500, statusText: 'Server Error' }); + page.requestFigure(); + const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1'); + retry.flush({ data: [], layout: {} }); + expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + }); + it('descarta respuestas obsoletas de aplicaciones sucesivas', () => { + load(); figure().flush({ data: [], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + page.applyFilters(); const old = figure(); + control.unit = 'S2'; control.add(); + expect(old.cancelled).toBe(false); + page.applyFilters(); const current = figure(); + expect(old.cancelled).toBe(true); + expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + current.flush({ data: [{ y: [12] }], layout: {} }); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(page.result().figure?.data[0]['y']).toEqual([12]); + }); + it('restaura borrador pendiente y consulta la aplicación al regresar a indicador y figura', () => { + load(); figure().flush({ data: [], layout: {} }); + let control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + page.applyFilters(); figure().flush({ data: [], layout: {} }); + control.unit = 'S2'; control.add(); + page.selectFigura('f2'); figure().flush({ data: [], layout: {} }); + page.selectFigura('f1'); + const restored = figure(); expect(restored.request.params.get('periodos')).toBe('2025-S1'); + restored.flush({ data: [], layout: {} }); + control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + page.selectIndicador('i2'); figure().flush({ data: [], layout: {} }); + page.selectIndicador('i1'); + const returned = figure(); expect(returned.request.params.get('periodos')).toBe('2025-S1'); + returned.flush({ data: [], layout: {} }); + control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + expect(control.hasPending).toBe(true); + }); + it('restaura dominio, indicador, figura y tema sin aplicar el borrador mensual pendiente', () => { + http.expectOne('/tea/indicadores').flush([]); + page.changeDominio('cacu'); + http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + const id = page.indicadorId; const fig = page.figuraId; + page.changeTema('oscuro'); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + let control = filters(); control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add(); + page.changeDominio('cama'); + http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama); + http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); + page.changeDominio('cacu'); + http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu); + const restored = http.expectOne(r => r.url.includes('/figuras/')); + expect(restored.request.params.has('periodos')).toBe(false); + expect(restored.request.params.get('tema')).toBe('oscuro'); + restored.flush({ data: [], layout: {} }); + expect(page.indicadorId).toBe(id); expect(page.figuraId).toBe(fig); + control = filters(); expect(control.state.tipo).toBe('mes'); + expect(control.selectedPeriods).toEqual(['2025-01']); + expect(control.state.applied?.tipo).toBe('semestre'); + }); + it('conserva memoria al destruir y recrear la página dentro de la aplicación', () => { + load(); figure().flush({ data: [], layout: {} }); + page.selectIndicador('i2'); figure().flush({ data: [], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S2'; control.add(); + fixture.destroy(); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + load(); + const restored = figure(); + expect(restored.request.url).toContain('/i2/figuras/box'); + expect(restored.request.params.has('periodos')).toBe(false); + restored.flush({ data: [], layout: {} }); + expect(filters().selectedPeriods).toEqual(['2025-S2']); + expect(filters().hasPending).toBe(true); + }); }); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 5ef81fa..273ef58 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -6,14 +6,15 @@ import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; -import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, Indicador, parsePeriodos, Tema } from './indicadores.models'; +import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { Dominio, DOMINIOS, isDominio, FigureSelection, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; import { presentationFigure } from './indicadores.presentation'; import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; +import { FilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; export function httpMessage(error: unknown, catalog = false): string { if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.'; @@ -25,18 +26,18 @@ export function httpMessage(error: unknown, catalog = false): string { } @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard, IndicadorPeriodFilters], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { private readonly service = inject(IndicadoresService); + private readonly memory = inject(IndicadoresMemory); private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute, { optional: true }); readonly dominios = DOMINIOS; dominio: Dominio = 'tea'; readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; - tipoPeriodo: TipoPeriodo = 'semestre'; private readonly catalogRequests = new Subject(); private readonly figureRequests = new Subject(); readonly catalog = signal([]); @@ -45,19 +46,22 @@ export class IndicadoresPage { readonly result = signal({ status: 'idle' }); indicadorId = ''; figuraId = ''; - periodMode: 'todos' | 'manual' = 'todos'; - periodText = ''; - periodError = ''; tema: Tema = 'claro'; + filters?: FilterState; get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); } constructor() { const initialDomain: unknown = this.route?.snapshot.data['dominio']; if (isDominio(initialDomain)) this.dominio = initialDomain; this.figureRequests.pipe(switchMap(selection => selection - ? this.service.figura(selection).pipe( + ? defer(() => this.service.figura(selection)).pipe( map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState), - catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)), + catchError(error => of({ + status: 'error', + message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 + && (selection.periodos?.length ?? 0) > 1 + ? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''), + } as FigureState)), startWith({ status: 'loading' } as FigureState)) : of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef)) .subscribe(state => this.result.set(state)); @@ -66,7 +70,7 @@ export class IndicadoresPage { this.catalogError.set(''); this.catalog.set([]); this.indicadorId = this.figuraId = ''; - this.resetPeriodos('semestre'); + this.filters = undefined; this.figureRequests.next(null); return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })), catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); @@ -74,53 +78,68 @@ export class IndicadoresPage { this.catalogLoading.set(false); this.catalog.set(items); this.catalogError.set(error); - if (items.length) this.selectIndicador(items[0].id); + const navigation = this.memory.navigation(this.dominio); + this.tema = navigation?.tema ?? 'claro'; + if (items.length) this.selectIndicador(items.some(i => i.id === navigation?.indicador) ? navigation!.indicador : items[0].id); }); } + filtersEdited() { + if (!this.filters || !this.selected) return; + this.memory.save(this.dominio, this.indicadorId, this.figuraId, this.filters); + this.memory.remember(this.dominio, this.indicadorId, this.figuraId, this.tema); + } changeDominio(dominio: Dominio) { if (!isDominio(dominio) || dominio === this.dominio) return; + this.filtersEdited(); this.dominio = dominio; this.catalogRequests.next(); } - private resetPeriodos(tipo: TipoPeriodo) { - this.tipoPeriodo = tipo; - this.periodText = this.periodError = ''; - this.periodMode = 'todos'; - } - changeTipoPeriodo(tipo: TipoPeriodo) { - if (!this.selected?.tipos_periodo.includes(tipo)) return; - this.resetPeriodos(tipo); - if (tipo !== this.selected.tipos_periodo[0]) this.periodMode = 'manual'; - this.requestFigure(); - } - get periodLabel(): string { return this.tipoPeriodo === 'mes' ? 'Meses (AAAA-MM)' : 'Semestres (AAAA-S1,AAAA-S2)'; } - retryCatalog() { this.catalogRequests.next(); } + retryCatalog() { this.filtersEdited(); this.catalogRequests.next(); } selectIndicador(id: string) { + if (!this.catalog().some(i => i.id === id)) return; + this.filtersEdited(); this.indicadorId = id; - this.figuraId = this.selected?.figuras[0] ?? ''; - if (!this.selected?.tipos_periodo.includes(this.tipoPeriodo) - || (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0])) { - this.resetPeriodos(this.selected?.tipos_periodo[0] ?? 'semestre'); - } + const remembered = this.memory.selectedFigure(this.dominio, id); + this.figuraId = this.selected!.figuras.includes(remembered ?? '') ? remembered! : this.selected!.figuras[0] ?? ''; + this.restoreFilters(); + } + selectFigura(id: string) { + if (!this.selected?.figuras.includes(id)) return; + this.filtersEdited(); + this.figuraId = id; + this.restoreFilters(); + } + private restoreFilters() { + this.filters = this.memory.restore(this.dominio, this.selected!, this.figuraId); + this.filtersEdited(); this.requestFigure(); } - selectFigura(id: string) { this.figuraId = id; this.requestFigure(); } - changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); } - changePeriodText(text: string) { this.periodText = text; this.requestFigure(); } - changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); } + applyFilters() { + if (!this.filters || !this.selected) return; + const draft = this.filters.editors[this.filters.tipo]!.draft; + if (!validDraft(draft, this.filters.tipo, this.selected.tipos_periodo)) return; + this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) }; + this.filtersEdited(); + this.requestFigure(); + } + changeTema(tema: Tema) { + if (tema !== 'claro' && tema !== 'oscuro') return; + this.tema = tema; + this.filtersEdited(); + this.requestFigure(); + } + // Navigation, retry and theme all use the last application, never the pending editor. requestFigure() { - this.periodError = ''; - const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText, this.tipoPeriodo) : undefined; - if (periodos === null) this.periodError = this.tipoPeriodo === 'mes' - ? 'Introduce meses AAAA-MM del 01 al 12 separados por comas.' - : 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.'; - if (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0]) { - this.periodError = 'Selecciona periodos explícitos para este tipo; el servicio usa solo el primer tipo publicado al omitir periodos.'; - } - if (!this.selected || !this.selected.figuras.includes(this.figuraId) || !this.selected.tipos_periodo.includes(this.tipoPeriodo) || periodos === null || !!this.periodError) { + const applied = this.filters?.applied; + if (!this.selected?.figuras.includes(this.figuraId) || !applied + || !validDraft(applied.selection, applied.tipo, this.selected.tipos_periodo)) { this.figureRequests.next(null); return; } - this.figureRequests.next({ dominio: this.dominio, tipoPeriodo: this.tipoPeriodo, indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos }); + this.figureRequests.next({ + dominio: this.dominio, tipoPeriodo: applied.tipo, indicador: this.indicadorId, + figura: this.figuraId, tema: this.tema, + periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined, + }); } } diff --git a/src/app/features/indicadores/indicadores.models.spec.ts b/src/app/features/indicadores/indicadores.models.spec.ts index 820dcf4..20fc84e 100644 --- a/src/app/features/indicadores/indicadores.models.spec.ts +++ b/src/app/features/indicadores/indicadores.models.spec.ts @@ -32,3 +32,14 @@ it('deduplica meses en orden estable y valida el calendario sin mezclar tipos', it('no interpreta NaN ni null como porcentajes cero', () => { expect(hasNoVisibleValues({ data: [{ y: [NaN, null] }], layout: {} })).toBe(true); }); + +it.each(['0000-S1', '0000-S2', '10000-S1'])('rechaza año fuera de rango %s', value => { + expect(parsePeriodos(value)).toBeNull(); +}); +it.each(['0000-01', '10000-01', '2025-00', '2025-13'])('rechaza mes o año fuera de rango %s', value => { + expect(parsePeriodos(value, 'mes')).toBeNull(); +}); +it('acepta extremos canónicos de año', () => { + expect(parsePeriodos('0001-S1,9999-S2')).toEqual(['0001-S1', '9999-S2']); + expect(parsePeriodos('0001-01,9999-12', 'mes')).toEqual(['0001-01', '9999-12']); +}); diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 07d8bd1..1f1a083 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -30,7 +30,7 @@ export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null { if (tipo !== 'semestre' && tipo !== 'mes') return null; const parts = value.split(',').map(part => part.trim()); - return parts.length && parts.every(part => (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part)) + return parts.length && parts.every(part => part.slice(0, 4) !== '0000' && (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part)) ? [...new Set(parts)] : null; } diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 97f7a16..4538e78 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -86,3 +86,16 @@ describe('IndicadoresService HTTP', () => { expect(error).toBeInstanceOf(Error); }); }); + +describe('UX-04 validación defensiva HTTP', () => { + it('bloquea explícitos vacíos antes de construir una petición', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const service = TestBed.inject(IndicadoresService); + const http = TestBed.inject(HttpTestingController); + expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos: [] })).toThrow('Selección explícita vacía'); + for (const periodos of [['0000-S1'], ['0000-01'], ['10000-01']]) { + expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow(); + } + http.expectNone(() => true); http.verify(); + }); +}); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index bf330bb..fe92a76 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -27,7 +27,8 @@ export class IndicadoresService { } figura(selection: FigureSelection) { const dominio = requireDominio(selection.dominio ?? 'tea'); - if (selection.periodos?.length) { + if (selection.periodos !== undefined) { + if (!selection.periodos.length) throw new Error('Selección explícita vacía'); const text = selection.periodos.join(','); const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const); if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) { From 91832cc6ff790884e27b528c45887b6e53688cf5 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 13 Oct 2026 10:14:27 -0600 Subject: [PATCH 05/51] feat(indicadores): implementar catalogo expandible UX-05B --- .../indicadores/indicador-catalog-card.ts | 65 ++ .../indicadores/indicador-figure-card.html | 4 +- .../indicadores/indicador-figure-card.ts | 2 +- .../indicador-figure-panel.spec.ts | 200 ++++++ .../indicadores/indicador-figure-panel.ts | 98 +++ .../indicadores-catalog-contract.spec.ts | 22 + .../features/indicadores/indicadores-http.ts | 10 + .../indicadores-identities.spec.ts | 9 + .../indicadores/indicadores-identities.ts | 12 + .../indicadores/indicadores-memory.spec.ts | 20 +- .../indicadores/indicadores-memory.ts | 16 +- .../indicadores-navigation.spec.ts | 35 +- .../indicadores/indicadores-page.html | 37 +- .../indicadores/indicadores-page.scss | 16 +- .../indicadores/indicadores-page.spec.ts | 607 ++++++------------ .../features/indicadores/indicadores-page.ts | 109 +--- .../indicadores-plotly-lifecycle.spec.ts | 61 ++ .../indicadores/indicadores.service.ts | 1 + src/app/shared/plotly/plotly-chart.ts | 3 +- 19 files changed, 741 insertions(+), 586 deletions(-) create mode 100644 src/app/features/indicadores/indicador-catalog-card.ts create mode 100644 src/app/features/indicadores/indicador-figure-panel.spec.ts create mode 100644 src/app/features/indicadores/indicador-figure-panel.ts create mode 100644 src/app/features/indicadores/indicadores-catalog-contract.spec.ts create mode 100644 src/app/features/indicadores/indicadores-http.ts create mode 100644 src/app/features/indicadores/indicadores-identities.spec.ts create mode 100644 src/app/features/indicadores/indicadores-identities.ts create mode 100644 src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts new file mode 100644 index 0000000..5e8af4b --- /dev/null +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -0,0 +1,65 @@ +import { DOCUMENT } from '@angular/common'; +import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, ViewChild } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { Dominio, Indicador, Tema } from './indicadores.models'; +import { IndicadoresMemory } from './indicadores-memory'; +import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; + +@Component({ + selector: 'app-indicador-catalog-card', + imports: [MatButtonModule, MatCardModule, IndicadorFigurePanel], + template: ` + +
+

{{ indicador.titulo }}

+

{{ indicador.id }} · Contrato {{ indicador.contrato }} · {{ indicador.figuras.length }} figuras publicadas

+ +
+
+ @if (expanded) { + @for (figure of indicador.figuras; track panelIdentity(figure)) { + + } @empty {

El indicador no tiene figuras disponibles.

} + } +
+
+ `, + styles: ':host { display: block; margin: 1rem 0; } mat-card { padding: 1.25rem; } h2, p { overflow-wrap: anywhere; } h2 { margin-top: 0; }', +}) +export class IndicadorCatalogCard implements OnChanges { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) initialExpanded!: boolean; + @ViewChild('toggleButton', { read: ElementRef }) toggleButton!: ElementRef; + @ViewChild('content') content!: ElementRef; + private readonly changeDetector = inject(ChangeDetectorRef); + private readonly memory = inject(IndicadoresMemory); + private readonly document = inject(DOCUMENT); + private identity = ''; + expanded = false; + titleId = ''; + contentId = ''; + panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); } + ngOnChanges() { + const identity = indicatorIdentity(this.dominio, this.indicador.id); + if (identity === this.identity) return; + this.identity = identity; + const id = identityElementId(identity); + this.titleId = id + '-title'; + this.contentId = id + '-content'; + this.expanded = this.memory.expanded(this.dominio, this.indicador.id) ?? this.initialExpanded; + } + toggle() { + if (this.expanded && this.content.nativeElement.contains(this.document.activeElement)) { + this.toggleButton.nativeElement.focus(); + } + this.expanded = !this.expanded; + this.memory.rememberExpansion(this.dominio, this.indicador.id, this.expanded); + this.changeDetector.markForCheck(); + } +} diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index cbd23cb..d0971ec 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -7,7 +7,7 @@

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

} - + @if (state.status === 'loading') {

Cargando figura…

@@ -20,7 +20,7 @@ }

Figura: {{ figuraId }}

- + } @else {

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

} diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 70ce42d..625fd70 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -6,7 +6,7 @@ import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './in import { figureTitle } from './indicadores.presentation'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -// The page owns requests; the card receives the original and its presentation copy. +// The panel owns requests; the card receives the original and its presentation copy. export interface FigureState { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; diff --git a/src/app/features/indicadores/indicador-figure-panel.spec.ts b/src/app/features/indicadores/indicador-figure-panel.spec.ts new file mode 100644 index 0000000..bd479ff --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-panel.spec.ts @@ -0,0 +1,200 @@ +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 { PlotlyFigure } from './indicadores.models'; +import { Component } from '@angular/core'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } +const catalog = [ + { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }, + { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] }, + { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] }, +]; +describe('IndicadorFigurePanel', () => { + let page: IndicadorFigurePanel; + let http: HttpTestingController; + let fixture: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadorFigurePanel); + fixture.componentRef.setInput('dominio', 'tea'); + fixture.componentRef.setInput('indicador', catalog[0]); + fixture.componentRef.setInput('figuraId', 'f1'); + fixture.componentRef.setInput('tema', 'claro'); + page = fixture.componentInstance; + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function filters() { + fixture.detectChanges(); + return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + } + function load() { fixture.detectChanges(); } + function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + + it.each([ + ['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']], + ['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']], + ['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']], + ['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']], + ['toString', ['No hay una explicación específica']], + ])('explica el contrato %s y la distinción entre reporte y valores representables', (contract, expected) => { + fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: contract, figuras: ['f1'] }); load(); + figure().flush({ data: [], layout: {} }); + fixture.detectChanges(); + const help = fixture.nativeElement.querySelector('.interpretation').textContent; + for (const text of expected) expect(help).toContain(text); + if (contract === 'C3r') { + expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados'); + expect(help).not.toMatch(/serving|corrección|fase independiente/i); + } + expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables'); + }); + it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => { + load(); + const received: PlotlyFigure = { + data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }], + layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true }, + config: { staticPlot: false }, frames: [], extra: { preserved: true }, + }; + const original = JSON.stringify(received); + figure().flush(received); fixture.detectChanges(); + expect(JSON.stringify(received)).toBe(original); + expect(page.result().figure).toEqual(received); + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; + expect(chart.figure).toBe(page.result().presentationFigure); + expect(chart.figure).not.toBe(page.result().figure); + expect(chart.figure?.data).toEqual(received.data); + expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } }); + expect(JSON.stringify(page.result().figure)).toBe(original); + expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); + }); + it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => { + load(); figure().flush({ data: [], layout: {} }); + const control = filters(); + control.changeMode('manual'); + expect(control.canApply).toBe(false); + page.applyFilters(); + http.expectNone(req => req.url.includes('/figuras/')); + control.year = '2025'; control.unit = 'S1'; control.add(); + control.unit = 'S2'; control.add(); + http.expectNone(req => req.url.includes('/figuras/')); + expect(page.filters?.applied?.selection.mode).toBe('todos'); + page.applyFilters(); + const manual = figure(); + expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + control.select([]); + expect(manual.cancelled).toBe(false); + expect(control.canApply).toBe(false); + page.applyFilters(); + http.expectNone(req => req.url.includes('/figuras/')); + control.changeMode('todos'); + page.applyFilters(); + expect(manual.cancelled).toBe(true); + const all = figure(); + expect(all.request.params.has('periodos')).toBe(false); + all.flush({ data: [], layout: {} }); + }); + it('cancela figuras al cambiar tema rápidamente', () => { + load(); + const old = figure(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + const dark = figure(); + expect(old.cancelled).toBe(true); + expect(dark.request.params.get('tema')).toBe('oscuro'); + fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges(); + expect(dark.cancelled).toBe(true); + figure().flush({ data: [], layout: {} }); + }); + it.each([ + [400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'], + ])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => { + load(); + figure().flush('error privado', { status: status as number, statusText: 'Error' }); + expect(page.result().status).toBe('error'); + expect(page.result().message).toContain(message); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).not.toContain('error privado'); + fixture.nativeElement.querySelector('app-indicador-figure-card button').click(); + figure().flush({ data: [], layout: {} }); + expect(page.result().status).toBe('ready'); + }); + it('distingue conexión fallida y cancela HTTP al destruirse', () => { + load(); figure().error(new ProgressEvent('error')); + expect(page.result().message).toContain('conectar'); + page.requestFigure(); + const pending = figure(); + fixture.destroy(); + expect(pending.cancelled).toBe(true); + }); + it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => { + load(); figure().flush({ data: [{ y: [0, null] }], layout: {} }); + const control = filters(); control.changeMode('manual'); + control.year = '2025'; control.unit = 'S1'; control.add(); + fixture.detectChanges(); + expect(page.result().figure?.data[0]['y']).toEqual([0, null]); + expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar'); + expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres con reporte'); + http.expectNone(r => r.url.includes('/figuras/')); + }); + it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => { + load(); figure().flush({ data: [{ y: [42] }], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; + for (const period of periodos) { control.unit = period.slice(-2); control.add(); } + page.applyFilters(); + const req = figure(); + expect(page.result().figure).toBeUndefined(); + req.flush('private', { status: 404, statusText: 'Not Found' }); + expect(page.result().status).toBe('error'); + expect(page.result().figure).toBeUndefined(); + expect(page.result().message).toContain('esta selección'); + expect(page.result().message).not.toContain('2025'); + if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos'); + expect(control.selectedPeriods).toEqual(periodos); + control.select([]); + page.requestFigure(); + const retry = figure(); + expect(retry.request.params.get('periodos')).toBe(periodos.join(',')); + retry.flush({ data: [{ y: [null] }], layout: {} }); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + expect(control.entry.draft.mode).toBe('empty'); + }); + it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => { + load(); figure().flush({ data: [], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + page.applyFilters(); figure().flush({ data: [{ y: [20] }], layout: {} }); + control.unit = 'S2'; control.add(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + const themed = figure(); + expect(themed.request.params.get('periodos')).toBe('2025-S1'); + expect(themed.request.params.get('tema')).toBe('oscuro'); + themed.flush('error', { status: 500, statusText: 'Server Error' }); + page.requestFigure(); + const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1'); + retry.flush({ data: [], layout: {} }); + expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + }); + it('descarta respuestas obsoletas de aplicaciones sucesivas', () => { + load(); figure().flush({ data: [], layout: {} }); + const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); + page.applyFilters(); const old = figure(); + control.unit = 'S2'; control.add(); + expect(old.cancelled).toBe(false); + page.applyFilters(); const current = figure(); + expect(old.cancelled).toBe(true); + expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + current.flush({ data: [{ y: [12] }], layout: {} }); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(page.result().figure?.data[0]['y']).toEqual([12]); + }); + +}); diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts new file mode 100644 index 0000000..8dd0b7b --- /dev/null +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -0,0 +1,98 @@ +import { Component, DestroyRef, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; +import { presentationFigure } from './indicadores.presentation'; +import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; +import { FilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { httpMessage } from './indicadores-http'; +import { figureIdentity, identityElementId } from './indicadores-identities'; + +@Component({ + selector: 'app-indicador-figure-panel', + imports: [IndicadorPeriodFilters, IndicadorFigureCard], + template: ` +
+

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

+ @if (filters; as state) { + + } + +
+ `, + styles: ':host { display: block; min-width: 0; } section { margin-top: 1.5rem; } h3 { overflow-wrap: anywhere; }', +}) +export class IndicadorFigurePanel implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) figuraId!: string; + @Input({ required: true }) tema!: Tema; + private readonly service = inject(IndicadoresService); + private readonly memory = inject(IndicadoresMemory); + private readonly destroyRef = inject(DestroyRef); + private readonly figureRequests = new Subject(); + private identity = ''; + titleId = ''; + filters?: FilterState; + readonly result = signal({ status: 'idle' }); + constructor() { + this.figureRequests.pipe(switchMap(selection => selection + ? defer(() => this.service.figura(selection)).pipe( + map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState), + catchError(error => of({ + status: 'error', + message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 + && (selection.periodos?.length ?? 0) > 1 + ? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''), + } as FigureState)), + startWith({ status: 'loading' } as FigureState)) + : of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef)) + .subscribe(state => this.result.set(state)); + } + ngOnChanges(changes: SimpleChanges) { + const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); + if (identity !== this.identity || changes['indicador']) { + // Save the departing identity before accepting a new catalog object. + this.saveCurrent(); + this.identity = identity; + this.titleId = identityElementId(identity) + '-title'; + this.filters = this.indicador.figuras.includes(this.figuraId) + ? this.memory.restore(this.dominio, this.indicador, this.figuraId) : undefined; + this.filtersEdited(); + this.requestFigure(); + } else if (changes['tema']) this.requestFigure(); + } + private saveCurrent() { + if (!this.filters || !this.identity) return; + const [domain, indicator, figure] = JSON.parse(this.identity) as [Dominio, string, string]; + this.memory.save(domain, indicator, figure, this.filters); + } + filtersEdited() { this.saveCurrent(); } + applyFilters() { + if (!this.filters) return; + const draft = this.filters.editors[this.filters.tipo]!.draft; + if (!validDraft(draft, this.filters.tipo, this.indicador.tipos_periodo)) return; + this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) }; + this.filtersEdited(); + this.requestFigure(); + } + requestFigure() { + const applied = this.filters?.applied; + if (!this.indicador.figuras.includes(this.figuraId) || !applied + || !validDraft(applied.selection, applied.tipo, this.indicador.tipos_periodo)) { + this.figureRequests.next(null); + return; + } + this.figureRequests.next({ + dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId, + tipoPeriodo: applied.tipo, tema: this.tema, + periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined, + }); + } + ngOnDestroy() { this.saveCurrent(); } +} diff --git a/src/app/features/indicadores/indicadores-catalog-contract.spec.ts b/src/app/features/indicadores/indicadores-catalog-contract.spec.ts new file mode 100644 index 0000000..29da740 --- /dev/null +++ b/src/app/features/indicadores/indicadores-catalog-contract.spec.ts @@ -0,0 +1,22 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresService } from './indicadores.service'; +describe('UX-05B contrato de figuras del catálogo', () => { + it.each([{ figuras: [] }, { figuras: ['f'] }, { figuras: ['f', 'g'] }])('acepta figuras publicadas $figuras', ({ figuras }) => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const http = TestBed.inject(HttpTestingController); + let actual: unknown; + TestBed.inject(IndicadoresService).catalogo('tea').subscribe(value => actual = value); + const items = [{ id: 'i', titulo: 'I', contrato: 'C1', figuras, tipos_periodo: ['mes'] }]; + http.expectOne('/tea/indicadores').flush(items); expect(actual).toEqual(items); http.verify(); + }); + it('rechaza figuras duplicadas dentro de un indicador', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const http = TestBed.inject(HttpTestingController); + let error: unknown; let emitted = false; + TestBed.inject(IndicadoresService).catalogo('tea').subscribe({ next: () => emitted = true, error: e => error = e }); + http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'f'], tipos_periodo: ['mes'] }]); + expect(error).toBeInstanceOf(Error); expect(emitted).toBe(false); http.verify(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-http.ts b/src/app/features/indicadores/indicadores-http.ts new file mode 100644 index 0000000..58d1fe3 --- /dev/null +++ b/src/app/features/indicadores/indicadores-http.ts @@ -0,0 +1,10 @@ +import { HttpErrorResponse } from '@angular/common/http'; + +export function httpMessage(error: unknown, catalog = false): string { + if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.'; + if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.'; + if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.'; + if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.'; + if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.'; + return 'No se pudo completar la solicitud. Intenta nuevamente.'; +} diff --git a/src/app/features/indicadores/indicadores-identities.spec.ts b/src/app/features/indicadores/indicadores-identities.spec.ts new file mode 100644 index 0000000..a1cbf7f --- /dev/null +++ b/src/app/features/indicadores/indicadores-identities.spec.ts @@ -0,0 +1,9 @@ +import { figureIdentity, indicatorIdentity, identityElementId } from './indicadores-identities'; +describe('UX-05B identidades', () => { + it('separa dominios, indicadores y figuras sin colisiones por delimitadores', () => { + const ids = [indicatorIdentity('tea', 'a/b'), indicatorIdentity('cacu', 'a/b'), figureIdentity('tea', 'a/b', 'c'), figureIdentity('tea', 'a', 'b/c'), figureIdentity('tea', 'a', 'á')]; + expect(new Set(ids).size).toBe(ids.length); + expect(new Set(ids.map(identityElementId)).size).toBe(ids.length); + expect(ids.map(identityElementId).every(id => /^[a-z0-9-]+$/.test(id))).toBe(true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-identities.ts b/src/app/features/indicadores/indicadores-identities.ts new file mode 100644 index 0000000..fdfcb61 --- /dev/null +++ b/src/app/features/indicadores/indicadores-identities.ts @@ -0,0 +1,12 @@ +import { Dominio } from './indicadores.models'; + +// JSON tuples preserve identity even when published IDs contain separators. +export function indicatorIdentity(domain: Dominio, indicator: string): string { + return JSON.stringify([domain, indicator]); +} +export function figureIdentity(domain: Dominio, indicator: string, figure: string): string { + return JSON.stringify([domain, indicator, figure]); +} +export function identityElementId(identity: string): string { + return 'indicadores-' + Array.from(identity, char => char.codePointAt(0)!.toString(16)).join('-'); +} diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts index d9bdbfb..f0913ac 100644 --- a/src/app/features/indicadores/indicadores-memory.spec.ts +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -35,20 +35,24 @@ describe('UX-04 memoria temporal', () => { ['cacu', indicador, 'f'], ['tea', { ...indicador, id: 'otro' }, 'f'], ['tea', indicador, 'g'], ] as const) expect(memory.restore(domain, item, figure).editors.semestre?.draft.mode).toBe('todos'); }); - it('recuerda indicador, tema y figura por indicador', () => { - memory.remember('cacu', 'i', 'g', 'oscuro'); - memory.remember('cacu', 'otro', 'f', 'claro'); - expect(memory.navigation('cacu')).toEqual({ indicador: 'otro', tema: 'claro' }); - expect(memory.selectedFigure('cacu', 'i')).toBe('g'); - expect(memory.navigation('tea')).toBeUndefined(); + it('distingue ausencia de expansión, true y false y aísla dominios', () => { + expect(memory.expanded('tea', 'i')).toBeUndefined(); + memory.rememberExpansion('tea', 'i', false); + memory.rememberExpansion('cacu', 'i', true); + expect(memory.expanded('tea', 'i')).toBe(false); + expect(memory.expanded('cacu', 'i')).toBe(true); + expect(memory.expanded('tea', 'otro')).toBeUndefined(); + memory.rememberTheme('cacu', 'oscuro'); + expect(memory.theme('cacu')).toBe('oscuro'); + expect(memory.theme('tea')).toBe('claro'); }); it('una instancia nueva reinicia las selecciones y no lee ni escribe almacenamiento', () => { const localRead = vi.spyOn(Storage.prototype, 'getItem'); const localWrite = vi.spyOn(Storage.prototype, 'setItem'); - memory.remember('tea', 'otro', 'g', 'oscuro'); + memory.rememberTheme('tea', 'oscuro'); memory.rememberExpansion('tea', 'i', false); memory.save('tea', 'i', 'f', { tipo: 'mes', editors: { mes: { added: [], draft: { mode: 'empty' } } } }); const fresh = new IndicadoresMemory(); - expect(fresh.navigation('tea')).toBeUndefined(); + expect(fresh.theme('tea')).toBe('claro'); expect(fresh.expanded('tea', 'i')).toBeUndefined(); expect(fresh.restore('tea', indicador, 'f').tipo).toBe('semestre'); expect(localRead).not.toHaveBeenCalled(); expect(localWrite).not.toHaveBeenCalled(); localRead.mockRestore(); localWrite.mockRestore(); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index 9a249c7..e6ca0ac 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -37,14 +37,16 @@ export function pending(state: FilterState): boolean { } @Injectable({ providedIn: 'root' }) export class IndicadoresMemory { - private readonly domains = new Map(); - private readonly figures = new Map(); + private readonly themes = new Map(); + private readonly expansions = new Map(); private readonly filters = new Map(); - navigation(domain: Dominio) { return this.domains.get(domain); } - selectedFigure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); } - remember(domain: Dominio, indicador: string, figura: string, tema: Tema) { - this.domains.set(domain, { indicador, tema }); - this.figures.set(JSON.stringify([domain, indicador]), figura); + theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; } + rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); } + expanded(domain: Dominio, indicador: string): boolean | undefined { + return this.expansions.get(JSON.stringify([domain, indicador])); + } + rememberExpansion(domain: Dominio, indicador: string, expanded: boolean) { + this.expansions.set(JSON.stringify([domain, indicador]), expanded); } private key(domain: Dominio, indicador: string, figura: string) { return JSON.stringify([domain, indicador, figura]); diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index 5a87c18..2a6a6a0 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -6,6 +6,8 @@ import { provideRouter, Router } from '@angular/router'; import { RouterTestingHarness } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; import { routes } from '../../app.routes'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadoresPage } from './indicadores-page'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorPeriodFilters } from './indicador-period-filters'; @@ -13,7 +15,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; -@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' }) +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' }) class ChartStub { figure?: PlotlyFigure; } describe('UX-04 navegación Angular', () => { @@ -24,8 +26,11 @@ describe('UX-04 navegación Angular', () => { http = TestBed.inject(HttpTestingController); return RouterTestingHarness.create(); } - function load(domain: 'tea' | 'cacu' | 'cama') { + function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) { http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]); + harness.detectChanges(); + const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; + if (!card.expanded) { card.toggle(); harness.detectChanges(); } const req = http.expectOne(r => r.url.includes('/figuras/')); req.flush({ data: [{ y: [0, null] }], layout: {} }); return req; @@ -34,40 +39,40 @@ describe('UX-04 navegación Angular', () => { it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => { const harness = await setup(); const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); - load('tea'); harness.detectChanges(); + load('tea', harness); harness.detectChanges(); const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); - tea.applyFilters(); + (harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).applyFilters(); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); control.unit = 'S2'; control.add(); - await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu'); - await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama'); + await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu', harness); + await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama', harness); const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); - const req = load('tea'); + const req = load('tea', harness); expect(req.request.params.get('periodos')).toBe('2025-S1'); - expect(restored.filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }); + expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }); expect(TestBed.inject(Router).url).toBe('/indicadores/tea'); }); it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => { let harness = await setup(); const page = await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); - load('cacu'); harness.detectChanges(); - page.changeTema('oscuro'); + load('cacu', harness); harness.detectChanges(); + page.changeTema('oscuro'); harness.detectChanges(); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add(); - page.applyFilters(); + (harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).applyFilters(); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); const url = TestBed.inject(Router).url; http.verify(); TestBed.resetTestingModule(); harness = await setup(); const restarted = await harness.navigateByUrl(url, IndicadoresPage); - const req = load('cacu'); + const req = load('cacu', harness); expect(TestBed.inject(Router).url).toBe('/indicadores/cacu'); - expect(restarted.indicadorId).toBe(syntheticCatalogs.cacu[0].id); + expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).expanded).toBe(true); expect(restarted.tema).toBe('claro'); - expect(restarted.filters?.tipo).toBe('semestre'); - expect(restarted.filters?.editors.mes?.draft.mode).toBe('empty'); + expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.tipo).toBe('semestre'); + expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.editors.mes?.draft.mode).toBe('empty'); expect(req.request.params.has('periodos')).toBe(false); expect(req.request.params.get('tema')).toBe('claro'); }); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index bebe306..1b1c416 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -21,32 +21,15 @@

No hay indicadores disponibles en el catálogo.

} @else { - -
- Indicador - - @for (item of catalog(); track item.id) { {{ item.titulo }} } - - - Figura - - @for (figure of selected?.figuras ?? []; track $index) { {{ figure }} } - - - Tema de la figura - - ClaroOscuro - - -
- @if (filters; as state) { - - } -

Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.

-
- + Tema del dominio + + ClaroOscuro + + +

{{ catalog().length }} indicadores publicados

+ @for (item of catalog(); track cardIdentity(item)) { + + } } diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index 121a972..2fa9f71 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -4,18 +4,6 @@ h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; } header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); } .notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; } -.filters { padding: 1.5rem; margin: 1.5rem 0; } -.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; } -.indicator { grid-column: span 2; } -.periods { grid-column: 1 / -1; margin-bottom: 1rem; } -mat-form-field { width: 100%; min-width: 0; } -.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; } -.validation { color: var(--mat-sys-error); } .state { padding: 1.25rem; margin: 0; } -@media (max-width: 850px) { .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } } -@media (max-width: 550px) { - .fields { grid-template-columns: minmax(0, 1fr); } - .indicator { grid-column: auto; } - .filters { padding: 1rem; } - h1 { font: var(--mat-sys-headline-medium); } -} +mat-form-field { width: 100%; max-width: 24rem; } +@media (max-width: 550px) { h1 { font: var(--mat-sys-headline-medium); } } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index d4c3982..e552372 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -1,449 +1,220 @@ +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 { MatSelect } from '@angular/material/select'; -import { IndicadoresMemory } from './indicadores-memory'; import { By } from '@angular/platform-browser'; -import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; -import { PlotlyFigure } from './indicadores.models'; -import { Component } from '@angular/core'; import { IndicadoresPage } from './indicadores-page'; -import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { MatSelect } from '@angular/material/select'; +import { NgModel } from '@angular/forms'; +import { IndicadoresMemory } from './indicadores-memory'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Indicador, PlotlyFigure } from './indicadores.models'; +import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; -@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' }) +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' }) class ChartStub { figure?: PlotlyFigure; } -const catalog = [ - { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }, - { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] }, - { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] }, -]; -describe('IndicadoresPage', () => { +const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] }; +const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] }; +describe('UX-05B catálogo expandible', () => { + let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; - let fixture: ReturnType>; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); - fixture = TestBed.createComponent(IndicadoresPage); - page = fixture.componentInstance; + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); }); afterEach(() => { fixture.destroy(); http.verify(); }); - function filters() { - fixture.detectChanges(); - return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; + function load(items: Indicador[] = [item, second], domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } - function load() { http.expectOne('/tea/indicadores').flush(catalog); } - function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + function toggle(index = 0) { cards()[index].toggle(); fixture.detectChanges(); } + function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } + function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } + function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } - it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: Material se estabiliza al editar y restaurar %s sin HTTP', async id => { - http.expectOne('/tea/indicadores').flush(syntheticCatalogs.tea); - figure().flush({ data: [], layout: {} }); - page.selectIndicador(id); - figure().flush({ data: [{ type: 'bar', y: [50, 50] }], layout: { barmode: 'stack' } }); - fixture.detectChanges(); - await fixture.whenStable(); - if (id === 'M02_sexo') expect(page.figuraId).toBe('fig_c2_apiladas'); - const result = page.result(); - const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; - const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save'); - const child = () => fixture.debugElement.query(By.directive(IndicadorPeriodFilters)); - const mode = () => child().queryAll(By.directive(MatSelect))[0].componentInstance as MatSelect; - async function choose(value: string) { - const select = mode(); - select.open(); fixture.detectChanges(); await fixture.whenStable(); - expect(select.panelOpen).toBe(true); - const option = select.options.find(o => o.value === value)!; - (document.getElementById(option.id) as HTMLElement).click(); - fixture.detectChanges(); await fixture.whenStable(); - expect(select.panelOpen).toBe(false); - } - async function togglePanel() { - const count = saves.mock.calls.length; - for (let i = 0; i < 3; i++) { - const select = mode(); - select.open(); fixture.detectChanges(); await fixture.whenStable(); - expect(select.panelOpen).toBe(true); - select.close(); fixture.detectChanges(); await fixture.whenStable(); - expect(select.panelOpen).toBe(false); - } - expect(saves).toHaveBeenCalledTimes(count); - http.expectNone(() => true); - expect(page.result()).toBe(result); - expect(chart.figure).toBe(result.presentationFigure); - } - await togglePanel(); - await choose('manual'); - expect(filters().entry.draft.mode).toBe('empty'); - expect(filters().canApply).toBe(false); - await togglePanel(); - await choose('todos'); - await choose('manual'); - expect(saves).toHaveBeenCalledTimes(3); - // Restoring the empty pending draft must also settle. - const other = id === 'M02_sexo' ? 'K01_evaluacion_3_meses' : 'M02_sexo'; - page.selectIndicador(other); figure().flush({ data: [], layout: {} }); - page.selectIndicador(id); - const returned = figure(); expect(returned.request.params.has('periodos')).toBe(false); - returned.flush({ data: [], layout: {} }); - fixture.detectChanges(); await fixture.whenStable(); - let control = filters(); expect(control.entry.draft.mode).toBe('empty'); - control.year = '2025'; control.unit = 'S1'; control.add(); - fixture.detectChanges(); await fixture.whenStable(); - http.expectNone(() => true); - expect(control.state.applied?.selection.mode).toBe('todos'); - page.selectIndicador(other); figure().flush({ data: [], layout: {} }); - page.selectIndicador(id); - const restored = figure(); expect(restored.request.params.has('periodos')).toBe(false); - restored.flush({ data: [], layout: {} }); - fixture.detectChanges(); await fixture.whenStable(); - control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1']); - expect(control.hasPending).toBe(true); - http.expectNone(() => true); + it.each([0, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { + const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i })); + load(items); + expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); + expect(cards().every(c => !c.expanded)).toBe(true); + expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/')); + if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); - it('cancela figura y catálogo antiguos al cambiar dominios rápidamente', () => { - load(); const oldFigure = figure(); - page.changeDominio('cacu'); - expect(oldFigure.cancelled).toBe(true); - expect(page.result().figure).toBeUndefined(); - expect(page.catalog()).toEqual([]); - const oldCatalog = http.expectOne('/cacu/indicadores'); - page.changeDominio('cama'); - expect(oldCatalog.cancelled).toBe(true); - http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama); - const current = http.expectOne(r => r.url.startsWith('/cama/indicadores/') && r.url.includes('/figuras/')); - current.flush({ data: [{ y: [null, 42] }], layout: {} }); - expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); - expect(() => oldFigure.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); - expect(page.dominio).toBe('cama'); - expect(page.result().figure?.data[0]['y']).toEqual([null, 42]); + it('un indicador se abre y consulta exactamente una vez cada figura publicada', () => { + load([item]); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(2); + request('f1').flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} }); + fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true); }); - it.each(['cacu', 'cama'] as const)('edita meses sin HTTP y conserva ayuda sin Wilson efectivo en %s', dominio => { - http.expectOne('/tea/indicadores').flush([]); - page.changeDominio(dominio); - http.expectOne('/' + dominio + '/indicadores').flush(syntheticCatalogs[dominio]); - http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ y: [null, 0] }], layout: {} }); - const control = filters(); - control.changeTipo('mes'); - expect(control.entry.draft.mode).toBe('empty'); - expect(page.result().status).toBe('ready'); - control.year = '2025'; control.unit = '01'; control.add(); - control.unit = '02'; control.add(); - control.unit = '01'; control.add(); - expect(control.error).toContain('ya está agregado'); - http.expectNone(r => r.url.includes('/figuras/')); - page.applyFilters(); - const monthly = http.expectOne(r => r.url.includes('/figuras/')); - expect(monthly.request.params.get('periodos')).toBe('2025-01,2025-02'); - control.unit = '13'; control.add(); - expect(control.error).toContain('unidad válida'); - expect(monthly.cancelled).toBe(false); - control.changeMode('todos'); - expect(control.entry.draft.mode).toBe('explicit'); - control.changeTipo('semestre'); - expect(control.entry.draft.mode).toBe('todos'); - expect(monthly.cancelled).toBe(false); - page.applyFilters(); - expect(monthly.cancelled).toBe(true); - const semesters = http.expectOne(r => r.url.includes('/figuras/')); - expect(semesters.request.params.has('periodos')).toBe(false); - semesters.flush({ data: [{ y: [null, 0] }], layout: {} }); - fixture.detectChanges(); - const help = fixture.nativeElement.querySelector('.interpretation').textContent; - expect(help).toContain('no entregan intervalos Wilson efectivos'); - expect(help).toContain('eje horizontal muestra el periodo'); - expect(help).toContain('suprimidos no representan tasas observadas de 0 %'); - expect(help).not.toContain('La línea vertical representa el intervalo'); + it('la preferencia false prevalece sobre apertura automática al volver', () => { + load([item]); flushAll(); toggle(); + fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + load([item]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); }); - it('acepta futuros indicadores y figuras desde catálogo sin fijar cantidades ni contratos por dominio', () => { - http.expectOne('/tea/indicadores').flush([]); - page.changeDominio('cama'); - const future = [ - ...syntheticCatalogs.cama, - { id: 'synthetic_future', titulo: 'Fixture futuro', contrato: 'C2', figuras: ['fig_c2_apiladas', 'fig_c1_puntos'], tipos_periodo: ['mes', 'semestre'] }, - ]; - http.expectOne('/cama/indicadores').flush(future); - http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); - page.selectIndicador('synthetic_future'); - expect(page.filters?.tipo).toBe('mes'); - const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas')); - expect(req.request.params.has('periodos')).toBe(false); - req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } }); - fixture.detectChanges(); - expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('composición porcentual'); - page.selectFigura('fig_c1_puntos'); - http.expectOne(r => r.url.includes('/fig_c1_puntos')).flush({ data: [], layout: {} }); - fixture.detectChanges(); - expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos'); + it('indicador sin figuras informa y no consulta HTTP', () => { + load([{ ...item, figuras: [] }]); expect(cards()[0].expanded).toBe(true); + expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles'); + expect(panels()).toHaveLength(0); http.expectNone(() => true); }); - it('presenta carga y elige una primera figura válida desde el catálogo', () => { - expect(page.catalogLoading()).toBe(true); - load(); - expect(page.indicadorId).toBe('i1'); - expect(page.figuraId).toBe('f1'); - expect(page.result().status).toBe('loading'); - const request = figure(); - expect(request.request.params.has('periodos')).toBe(false); - request.flush({ data: [], layout: {} }); - fixture.detectChanges(); + it('varias tarjetas y figuras abiertas mantienen solicitudes concurrentes independientes', () => { + load(); toggle(0); const a = request('f1'), b = request('f2'); toggle(1); const c = request('g'); + expect(a.cancelled).toBe(false); expect(b.cancelled).toBe(false); + b.flush({ data: [{ y: [2] }], layout: {} }); c.flush({ data: [{ y: [3] }], layout: {} }); + a.flush({ data: [{ y: [1] }], layout: {} }); + expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2], [3]]); + expect(cards().every(c => c.expanded)).toBe(true); + }); + it('contraer cancela solo sus figuras, descarta respuestas y destruye paneles', () => { + load(); toggle(); toggle(1); const a = request('f1'), b = request('f2'), c = request('g'); + toggle(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true); expect(c.cancelled).toBe(false); + expect(() => a.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); + expect(panels()).toHaveLength(1); c.flush({ data: [{ y: [3] }], layout: {} }); + expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]); + }); + it('404 y reintento afectan solo una figura y 200 sin puntos sigue siendo resultado', () => { + load([item]); const a = request('f1'), b = request('f2'); + a.flush('private', { status: 404, statusText: 'Not Found' }); + b.flush({ data: [{ y: [null] }], layout: {} }); fixture.detectChanges(); + expect(panels()[0].result().status).toBe('error'); expect(panels()[1].result().status).toBe('ready'); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); - expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación'); + panels()[0].requestFigure(); request('f1').flush({ data: [], layout: {} }); http.expectNone(() => true); }); - it.each([ - ['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']], - ['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']], - ['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']], - ['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']], - ['toString', ['No hay una explicación específica']], - ])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => { - http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]); - figure().flush({ data: [], layout: {} }); - fixture.detectChanges(); - const help = fixture.nativeElement.querySelector('.interpretation').textContent; - for (const text of expected) expect(help).toContain(text); - if (contract === 'C3r') { - expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados'); - expect(help).not.toMatch(/serving|corrección|fase independiente/i); + it('edición y aplicación son independientes por figura y tema utiliza aplicación', () => { + load([item]); flushAll(); const a = control(), b = control(1); + a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true); + panels()[0].applyFilters(); const applied = request('f1'); expect(applied.request.params.get('periodos')).toBe('2025-S1'); + applied.flush({ data: [], layout: {} }); a.unit = 'S2'; a.add(); + b.changeTipo('mes'); b.year = '2026'; b.unit = '01'; b.add(); + page.changeTema('oscuro'); fixture.detectChanges(); + const themedA = request('f1'), themedB = request('f2'); + expect(themedA.request.params.get('periodos')).toBe('2025-S1'); + expect(themedB.request.params.has('periodos')).toBe(false); + expect(themedA.request.params.get('tema')).toBe('oscuro'); + expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(b.selectedPeriods).toEqual(['2026-01']); + themedA.flush({ data: [], layout: {} }); themedB.flush({ data: [], layout: {} }); + }); + it('cerrar y reabrir restaura borrador y aplicado por figura sin confirmar borradores', () => { + load([item]); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); + panels()[0].applyFilters(); request('f1').flush({ data: [], layout: {} }); a.unit = 'S2'; a.add(); + control(1).changeTipo('mes'); control(1).year = '2026'; control(1).unit = '01'; control(1).add(); + toggle(); toggle(); + const restored = request('f1'); expect(restored.request.params.get('periodos')).toBe('2025-S1'); + const other = request('f2'); expect(other.request.params.has('periodos')).toBe(false); + expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(control(1).selectedPeriods).toEqual(['2026-01']); + restored.flush({ data: [], layout: {} }); other.flush({ data: [], layout: {} }); + }); + it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => { + load(); toggle(); const a = request('f1'), b = request('f2'); + page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true); + const darkA = request('f1'), darkB = request('f2'); + expect(darkA.request.params.get('tema')).toBe('oscuro'); http.expectNone(r => r.url.endsWith('/g')); + darkA.flush({ data: [], layout: {} }); darkB.flush({ data: [], layout: {} }); + page.changeTema('oscuro'); fixture.detectChanges(); http.expectNone(() => true); + toggle(1); const later = request('g'); expect(later.request.params.get('tema')).toBe('oscuro'); later.flush({ data: [], layout: {} }); + }); + it('salir del dominio cancela paneles y catálogos obsoletos', () => { + load(); toggle(); const a = request('f1'), b = request('f2'); + page.changeDominio('cacu'); fixture.detectChanges(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true); + const oldCatalog = http.expectOne('/cacu/indicadores'); page.changeDominio('cama'); fixture.detectChanges(); + expect(oldCatalog.cancelled).toBe(true); load(syntheticCatalogs.cama, 'cama'); flushAll(); + expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama'); + }); + it('restaura expansión y tema de dominio sin aplicar borrador pendiente', () => { + load(); toggle(); flushAll(); control().changeMode('manual'); + page.changeTema('oscuro'); fixture.detectChanges(); flushAll(); + page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); flushAll(); + toggle(); page.changeDominio('tea'); fixture.detectChanges(); load(); + expect(cards()[0].expanded).toBe(true); expect(cards()[1].expanded).toBe(false); + expect(page.tema).toBe('oscuro'); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false); + expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} }); + page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); + expect(cards()[0].expanded).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); + }); + it('identidades estables conservan componentes al reordenar el catálogo', () => { + load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0]; + page.catalog.set([second, item]); fixture.detectChanges(); + expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true); + }); + it('identidad eliminada no se monta aunque exista preferencia anterior', () => { + TestBed.inject(IndicadoresMemory).rememberExpansion('tea', 'removed', true); + load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll(); + }); + it('botones semánticos anuncian expansión, IDs únicos y devuelven foco al contraer contenido', () => { + load(); + const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf; + expect(buttons[0].tagName).toBe('BUTTON'); expect(buttons[0].getAttribute('aria-expanded')).toBe('false'); + buttons[0].click(); fixture.detectChanges(); flushAll(); + expect(buttons[0].getAttribute('aria-expanded')).toBe('true'); + expect(document.getElementById(buttons[0].getAttribute('aria-controls')!)).toBeTruthy(); + const input = fixture.nativeElement.querySelector('app-indicador-period-filters mat-select') as HTMLElement; + input.focus(); expect(document.activeElement).toBe(input); cards()[0].toggle(); fixture.detectChanges(); + expect(document.activeElement).toBe(buttons[0]); + const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf).map(e => e.id); + expect(new Set(ids).size).toBe(ids.length); + expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); + }); + it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => { + load([item]); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } }; + const before = JSON.stringify(raw); request('f1').flush(raw); request('f2').flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); + expect(JSON.stringify(raw)).toBe(before); expect(panels()[0].result().figure).toEqual(raw); + const charts = fixture.debugElement.queryAll(By.directive(ChartStub)); expect(charts).toHaveLength(2); + expect(charts[0].componentInstance.figure).not.toBe(charts[1].componentInstance.figure); + expect(panels()[0].result().presentationFigure).not.toBe(raw); + expect(fixture.nativeElement.textContent).not.toContain('reportes no están disponibles'); + }); + it.each(['cacu', 'cama'] as const)('preserva advertencias y filtros mensuales de %s', domain => { + load([]); page.changeDominio(domain); load(syntheticCatalogs[domain], domain); flushAll(); + const c = control(); c.changeTipo('mes'); c.year = '2025'; c.unit = '01'; c.add(); http.expectNone(() => true); + panels()[0].applyFilters(); const r = http.expectOne(r => r.url.includes('/figuras/')); + expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('no entregan intervalos Wilson efectivos'); + expect(fixture.nativeElement.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); + }); + it('catálogo error, reintento y vacío no dejan paneles', () => { + http.expectOne('/tea/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(page.catalogError()).toContain('error interno'); expect(fixture.nativeElement.textContent).not.toContain('private'); + page.retryCatalog(); load([]); expect(panels()).toHaveLength(0); + }); + it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => { + load(syntheticCatalogs.tea); + const index = cards().findIndex(c => c.indicador.id === id); + toggle(index); flushAll(); + const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable(); + expect(c.canApply).toBe(false); http.expectNone(() => true); + c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable(); + toggle(index); toggle(index); flushAll(); await fixture.whenStable(); + expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos'); + const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save'); + const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; + const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue'); + for (let i = 0; i < 3; i++) { + select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable(); + expect(select.componentInstance.panelOpen).toBe(true); + select.componentInstance.close(); fixture.detectChanges(); await fixture.whenStable(); } - expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.'); - expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables'); + expect(writes).not.toHaveBeenCalled(); expect(saves).not.toHaveBeenCalled(); + expect(panels()[0].result()).toBe(state); http.expectNone(() => true); }); - it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => { - load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson'); - page.selectIndicador('i2'); fixture.detectChanges(); - const help = fixture.nativeElement.querySelector('.interpretation').textContent; - expect(help).toContain('min/max'); expect(help).not.toContain('Wilson'); - figure().flush({ data: [], layout: {} }); + it('mantiene el aviso de investigación en el catálogo', () => { + load(); expect(fixture.nativeElement.querySelector('.notice').textContent).toBe('Uso exclusivo de investigación. No usar para decisiones clínicas.'); }); - it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => { - load(); - const received: PlotlyFigure = { - data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }], - layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true }, - config: { staticPlot: false }, frames: [], extra: { preserved: true }, - }; - const original = JSON.stringify(received); - figure().flush(received); fixture.detectChanges(); - expect(JSON.stringify(received)).toBe(original); - expect(page.result().figure).toEqual(received); - const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; - expect(chart.figure).toBe(page.result().presentationFigure); - expect(chart.figure).not.toBe(page.result().figure); - expect(chart.figure?.data).toEqual(received.data); - expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } }); - expect(JSON.stringify(page.result().figure)).toBe(original); - expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); - }); - it('muestra catálogo vacío y permite recargar', () => { - http.expectOne('/tea/indicadores').flush([]); - fixture.detectChanges(); - expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); - page.retryCatalog(); - load(); - figure().flush({ data: [], layout: {} }); - }); - it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => { - load(); - const old = figure(); - page.selectIndicador('i2'); - expect(old.cancelled).toBe(true); - expect(page.figuraId).toBe('box'); - expect(page.result().figure).toBeUndefined(); - figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} }); - expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); - expect(page.result().figure?.data[0]['median']).toEqual([2]); - }); - it('soporta varias figuras, volver al indicador y selección sin figuras', () => { - load(); figure().flush({ data: [], layout: {} }); - page.selectFigura('f2'); - expect(figure().request.url).toContain('/i1/figuras/f2'); - // Cancel the previous request and verify its cancellation explicitly below. - page.selectIndicador('empty'); - expect(page.figuraId).toBe(''); - expect(page.result().status).toBe('idle'); - page.selectIndicador('i1'); - expect(page.figuraId).toBe('f2'); - figure().flush({ data: [], layout: {} }); - }); - it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => { - load(); figure().flush({ data: [], layout: {} }); - const control = filters(); - control.changeMode('manual'); - expect(control.canApply).toBe(false); - page.applyFilters(); - http.expectNone(req => req.url.includes('/figuras/')); - control.year = '2025'; control.unit = 'S1'; control.add(); - control.unit = 'S2'; control.add(); - http.expectNone(req => req.url.includes('/figuras/')); - expect(page.filters?.applied?.selection.mode).toBe('todos'); - page.applyFilters(); - const manual = figure(); - expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2'); - control.select([]); - expect(manual.cancelled).toBe(false); - expect(control.canApply).toBe(false); - page.applyFilters(); - http.expectNone(req => req.url.includes('/figuras/')); - control.changeMode('todos'); - page.applyFilters(); - expect(manual.cancelled).toBe(true); - const all = figure(); - expect(all.request.params.has('periodos')).toBe(false); - all.flush({ data: [], layout: {} }); - }); - it('cancela figuras al cambiar tema rápidamente', () => { - load(); - const old = figure(); - page.changeTema('oscuro'); - const dark = figure(); - expect(old.cancelled).toBe(true); - expect(dark.request.params.get('tema')).toBe('oscuro'); - page.changeTema('claro'); - expect(dark.cancelled).toBe(true); - figure().flush({ data: [], layout: {} }); - }); - it.each([ - [400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'], - ])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => { - load(); - figure().flush('error privado', { status: status as number, statusText: 'Error' }); - expect(page.result().status).toBe('error'); - expect(page.result().message).toContain(message); - fixture.detectChanges(); - expect(fixture.nativeElement.textContent).not.toContain('error privado'); - fixture.nativeElement.querySelector('app-indicador-figure-card button').click(); - figure().flush({ data: [], layout: {} }); - expect(page.result().status).toBe('ready'); - }); - it('distingue conexión fallida y cancela HTTP al destruirse', () => { - load(); figure().error(new ProgressEvent('error')); - expect(page.result().message).toContain('conectar'); - page.requestFigure(); - const pending = figure(); - fixture.destroy(); - expect(pending.cancelled).toBe(true); - }); - it('controla errores de catálogo y puede recuperarse', () => { - http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' }); - expect(page.catalogError()).toContain('error interno'); - page.retryCatalog(); load(); figure().flush({ data: [], layout: {} }); - }); - it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => { - load(); figure().flush({ data: [{ y: [0, null] }], layout: {} }); - const control = filters(); control.changeMode('manual'); - control.year = '2025'; control.unit = 'S1'; control.add(); - fixture.detectChanges(); - expect(page.result().figure?.data[0]['y']).toEqual([0, null]); - expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar'); - expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres con reporte'); - http.expectNone(r => r.url.includes('/figuras/')); - }); - it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => { - load(); figure().flush({ data: [{ y: [42] }], layout: {} }); - const control = filters(); control.changeMode('manual'); control.year = '2025'; - for (const period of periodos) { control.unit = period.slice(-2); control.add(); } - page.applyFilters(); - const req = figure(); - expect(page.result().figure).toBeUndefined(); - req.flush('private', { status: 404, statusText: 'Not Found' }); - expect(page.result().status).toBe('error'); - expect(page.result().figure).toBeUndefined(); - expect(page.result().message).toContain('esta selección'); - expect(page.result().message).not.toContain('2025'); - if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos'); - expect(control.selectedPeriods).toEqual(periodos); - control.select([]); - page.requestFigure(); - const retry = figure(); - expect(retry.request.params.get('periodos')).toBe(periodos.join(',')); - retry.flush({ data: [{ y: [null] }], layout: {} }); - fixture.detectChanges(); - expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); - expect(control.entry.draft.mode).toBe('empty'); - }); - it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => { - load(); figure().flush({ data: [], layout: {} }); - const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); - page.applyFilters(); figure().flush({ data: [{ y: [20] }], layout: {} }); - control.unit = 'S2'; control.add(); - page.changeTema('oscuro'); - const themed = figure(); - expect(themed.request.params.get('periodos')).toBe('2025-S1'); - expect(themed.request.params.get('tema')).toBe('oscuro'); - themed.flush('error', { status: 500, statusText: 'Server Error' }); - page.requestFigure(); - const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1'); - retry.flush({ data: [], layout: {} }); - expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); - }); - it('descarta respuestas obsoletas de aplicaciones sucesivas', () => { - load(); figure().flush({ data: [], layout: {} }); - const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); - page.applyFilters(); const old = figure(); - control.unit = 'S2'; control.add(); - expect(old.cancelled).toBe(false); - page.applyFilters(); const current = figure(); - expect(old.cancelled).toBe(true); - expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2'); - current.flush({ data: [{ y: [12] }], layout: {} }); - expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); - expect(page.result().figure?.data[0]['y']).toEqual([12]); - }); - it('restaura borrador pendiente y consulta la aplicación al regresar a indicador y figura', () => { - load(); figure().flush({ data: [], layout: {} }); - let control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); - page.applyFilters(); figure().flush({ data: [], layout: {} }); - control.unit = 'S2'; control.add(); - page.selectFigura('f2'); figure().flush({ data: [], layout: {} }); - page.selectFigura('f1'); - const restored = figure(); expect(restored.request.params.get('periodos')).toBe('2025-S1'); - restored.flush({ data: [], layout: {} }); - control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); - page.selectIndicador('i2'); figure().flush({ data: [], layout: {} }); - page.selectIndicador('i1'); - const returned = figure(); expect(returned.request.params.get('periodos')).toBe('2025-S1'); - returned.flush({ data: [], layout: {} }); - control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']); - expect(control.hasPending).toBe(true); - }); - it('restaura dominio, indicador, figura y tema sin aplicar el borrador mensual pendiente', () => { - http.expectOne('/tea/indicadores').flush([]); - page.changeDominio('cacu'); - http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu); - http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); - const id = page.indicadorId; const fig = page.figuraId; - page.changeTema('oscuro'); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); - let control = filters(); control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add(); - page.changeDominio('cama'); - http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama); - http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); - page.changeDominio('cacu'); - http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu); - const restored = http.expectOne(r => r.url.includes('/figuras/')); - expect(restored.request.params.has('periodos')).toBe(false); - expect(restored.request.params.get('tema')).toBe('oscuro'); - restored.flush({ data: [], layout: {} }); - expect(page.indicadorId).toBe(id); expect(page.figuraId).toBe(fig); - control = filters(); expect(control.state.tipo).toBe('mes'); - expect(control.selectedPeriods).toEqual(['2025-01']); - expect(control.state.applied?.tipo).toBe('semestre'); - }); - it('conserva memoria al destruir y recrear la página dentro de la aplicación', () => { - load(); figure().flush({ data: [], layout: {} }); - page.selectIndicador('i2'); figure().flush({ data: [], layout: {} }); - const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S2'; control.add(); - fixture.destroy(); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; - load(); - const restored = figure(); - expect(restored.request.url).toContain('/i2/figuras/box'); - expect(restored.request.params.has('periodos')).toBe(false); - restored.flush({ data: [], layout: {} }); - expect(filters().selectedPeriods).toEqual(['2025-S2']); - expect(filters().hasPending).toBe(true); + it('IDs distintos con el mismo título y figura conservan paneles y etiquetas independientes', () => { + load([{ ...item, figuras: ['f1'] }, { ...second, titulo: item.titulo, figuras: ['f1'] }]); + toggle(0); toggle(1); + const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1')); + const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1')); + a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges(); + const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf; + expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); + expect(buttons[0].tabIndex).toBe(0); expect(buttons[1].tabIndex).toBe(0); + expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]); }); }); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 273ef58..d061597 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -1,5 +1,4 @@ -import { Component, DestroyRef, inject, signal } from '@angular/core'; -import { HttpErrorResponse } from '@angular/common/http'; +import { ChangeDetectorRef, Component, DestroyRef, inject, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, RouterLink } from '@angular/router'; import { FormsModule } from '@angular/forms'; @@ -8,29 +7,22 @@ import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; -import { Dominio, DOMINIOS, isDominio, FigureSelection, Indicador, Tema } from './indicadores.models'; +import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { presentationFigure } from './indicadores.presentation'; -import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; -import { FilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; -import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadoresMemory } from './indicadores-memory'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { indicatorIdentity } from './indicadores-identities'; +import { httpMessage } from './indicadores-http'; -export function httpMessage(error: unknown, catalog = false): string { - if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.'; - if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.'; - if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.'; - if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.'; - if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.'; - return 'No se pudo completar la solicitud. Intenta nuevamente.'; -} @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard, IndicadorPeriodFilters], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { + private readonly changeDetector = inject(ChangeDetectorRef); private readonly service = inject(IndicadoresService); private readonly memory = inject(IndicadoresMemory); private readonly destroyRef = inject(DestroyRef); @@ -39,107 +31,38 @@ export class IndicadoresPage { dominio: Dominio = 'tea'; readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; private readonly catalogRequests = new Subject(); - private readonly figureRequests = new Subject(); readonly catalog = signal([]); readonly catalogLoading = signal(true); readonly catalogError = signal(''); - readonly result = signal({ status: 'idle' }); - indicadorId = ''; - figuraId = ''; tema: Tema = 'claro'; - filters?: FilterState; - get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); } - + cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); } constructor() { const initialDomain: unknown = this.route?.snapshot.data['dominio']; if (isDominio(initialDomain)) this.dominio = initialDomain; - this.figureRequests.pipe(switchMap(selection => selection - ? defer(() => this.service.figura(selection)).pipe( - map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState), - catchError(error => of({ - status: 'error', - message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 - && (selection.periodos?.length ?? 0) > 1 - ? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''), - } as FigureState)), - startWith({ status: 'loading' } as FigureState)) - : of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef)) - .subscribe(state => this.result.set(state)); + this.tema = this.memory.theme(this.dominio); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { this.catalogLoading.set(true); this.catalogError.set(''); this.catalog.set([]); - this.indicadorId = this.figuraId = ''; - this.filters = undefined; - this.figureRequests.next(null); return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })), catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { this.catalogLoading.set(false); this.catalog.set(items); this.catalogError.set(error); - const navigation = this.memory.navigation(this.dominio); - this.tema = navigation?.tema ?? 'claro'; - if (items.length) this.selectIndicador(items.some(i => i.id === navigation?.indicador) ? navigation!.indicador : items[0].id); }); } - filtersEdited() { - if (!this.filters || !this.selected) return; - this.memory.save(this.dominio, this.indicadorId, this.figuraId, this.filters); - this.memory.remember(this.dominio, this.indicadorId, this.figuraId, this.tema); - } changeDominio(dominio: Dominio) { if (!isDominio(dominio) || dominio === this.dominio) return; - this.filtersEdited(); this.dominio = dominio; + this.tema = this.memory.theme(dominio); this.catalogRequests.next(); } - retryCatalog() { this.filtersEdited(); this.catalogRequests.next(); } - selectIndicador(id: string) { - if (!this.catalog().some(i => i.id === id)) return; - this.filtersEdited(); - this.indicadorId = id; - const remembered = this.memory.selectedFigure(this.dominio, id); - this.figuraId = this.selected!.figuras.includes(remembered ?? '') ? remembered! : this.selected!.figuras[0] ?? ''; - this.restoreFilters(); - } - selectFigura(id: string) { - if (!this.selected?.figuras.includes(id)) return; - this.filtersEdited(); - this.figuraId = id; - this.restoreFilters(); - } - private restoreFilters() { - this.filters = this.memory.restore(this.dominio, this.selected!, this.figuraId); - this.filtersEdited(); - this.requestFigure(); - } - applyFilters() { - if (!this.filters || !this.selected) return; - const draft = this.filters.editors[this.filters.tipo]!.draft; - if (!validDraft(draft, this.filters.tipo, this.selected.tipos_periodo)) return; - this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) }; - this.filtersEdited(); - this.requestFigure(); - } + retryCatalog() { this.catalogRequests.next(); } changeTema(tema: Tema) { - if (tema !== 'claro' && tema !== 'oscuro') return; + if ((tema !== 'claro' && tema !== 'oscuro') || tema === this.tema) return; this.tema = tema; - this.filtersEdited(); - this.requestFigure(); - } - // Navigation, retry and theme all use the last application, never the pending editor. - requestFigure() { - const applied = this.filters?.applied; - if (!this.selected?.figuras.includes(this.figuraId) || !applied - || !validDraft(applied.selection, applied.tipo, this.selected.tipos_periodo)) { - this.figureRequests.next(null); - return; - } - this.figureRequests.next({ - dominio: this.dominio, tipoPeriodo: applied.tipo, indicador: this.indicadorId, - figura: this.figuraId, tema: this.tema, - periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined, - }); + this.memory.rememberTheme(this.dominio, tema); + this.changeDetector.markForCheck(); } } diff --git a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts new file mode 100644 index 0000000..a1672c6 --- /dev/null +++ b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts @@ -0,0 +1,61 @@ +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 { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + const disconnects: ReturnType[] = []; + beforeEach(() => { + vi.resetAllMocks(); disconnects.length = 0; + runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); + vi.stubGlobal('ResizeObserver', class { + disconnect = vi.fn(); observe = vi.fn(); + constructor() { disconnects.push(this.disconnect); } + }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }]); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } + function respond() { + http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: { annotations: [{ text: 'Nota' }] } })); + fixture.detectChanges(); + } + it('dos gráficos poseen hosts y etiquetas independientes y purgan al contraer', async () => { + respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2); + const hosts = charts.map(c => c.componentInstance.host.nativeElement); + expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f'); + expect(hosts[1].getAttribute('aria-label')).toBe('tea · i · g'); + const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; + card.toggle(); fixture.detectChanges(); + for (const host of hosts) expect(runtime.purge).toHaveBeenCalledWith(host); + for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1); + expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(0); + }); + it('un error de renderizado y su reintento no afectan la otra instancia', async () => { + runtime.react.mockRejectedValueOnce(new Error('render')); + respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart)); + expect(charts[0].componentInstance.status()).toBe('error'); expect(charts[1].componentInstance.status()).toBe('ready'); + const otherHost = charts[1].componentInstance.host.nativeElement; + charts[0].componentInstance.retry(); await settle(); + expect(charts[0].componentInstance.status()).toBe('ready'); expect(charts[1].componentInstance.status()).toBe('ready'); + expect(runtime.react.mock.calls.filter(c => c[0] === otherHost)).toHaveLength(1); http.expectNone(() => true); + }); + it('destruir la página desconecta y purga todas las instancias salientes', async () => { + respond(); await settle(); fixture.destroy(); + expect(runtime.purge).toHaveBeenCalledTimes(2); expect(disconnects).toHaveLength(2); + for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index fe92a76..f52dd1a 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -16,6 +16,7 @@ export class IndicadoresService { && typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string' && typeof item['contrato'] === 'string' && Array.isArray(item['figuras']) && item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0) + && new Set(item['figuras']).size === item['figuras'].length && Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0 && item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes') && new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) { diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts index 48b9589..209c06e 100644 --- a/src/app/shared/plotly/plotly-chart.ts +++ b/src/app/shared/plotly/plotly-chart.ts @@ -14,7 +14,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';

No se pudo representar la figura. Puedes reintentar.

} - + @if (status() === 'ready' && notes.length) {

Notas de la figura

@@ -25,6 +25,7 @@ import { PLOTLY_LOADER } from './plotly-runtime'; styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`, }) export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { + @Input() label = 'Figura estadística'; @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); From 9c012e9bb4cb44c7170923150d5c57605e2b0371 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 13 Oct 2026 10:42:34 -0600 Subject: [PATCH 06/51] feat(indicadores): agregar busqueda priorizada UX-05C --- .../indicadores/indicadores-page.html | 23 ++- .../indicadores/indicadores-page.scss | 3 + .../features/indicadores/indicadores-page.ts | 41 ++++- .../indicadores/indicadores-search.spec.ts | 162 ++++++++++++++++++ 4 files changed, 226 insertions(+), 3 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-search.spec.ts diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 1b1c416..fa0260f 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -27,7 +27,28 @@

{{ catalog().length }} indicadores publicados

- @for (item of catalog(); track cardIdentity(item)) { + @if (searchVisible()) { + +

+ @if (searchResults().active) { + @if (searchResults().count) { + {{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles. + } @else { + No se encontraron coincidencias. El catálogo completo permanece disponible en su orden original. + } + } +

+ } + @for (item of searchResults().items; track cardIdentity(item)) { } diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index 2fa9f71..8fbe1e4 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -7,3 +7,6 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .state { padding: 1.25rem; margin: 0; } mat-form-field { width: 100%; max-width: 24rem; } @media (max-width: 550px) { h1 { font: var(--mat-sys-headline-medium); } } +.catalog-search { display: flex; align-items: flex-start; gap: .75rem; flex-wrap: wrap; } +.catalog-search button { margin-top: .5rem; } +.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); } diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index d061597..86d70db 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -1,10 +1,12 @@ -import { ChangeDetectorRef, Component, DestroyRef, inject, signal } from '@angular/core'; +import { DOCUMENT } from '@angular/common'; +import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, RouterLink } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; @@ -17,11 +19,28 @@ import { httpMessage } from './indicadores-http'; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { + private readonly document = inject(DOCUMENT); + private readonly element = inject>(ElementRef); + private readonly injector = inject(Injector); + changeSearchQuery(query: string) { + const focused = this.document.activeElement; + this.searchQuery.set(query); + if (focused instanceof HTMLElement && this.element.nativeElement.contains(focused) + && focused.closest('app-indicador-catalog-card')) { + // Moving a retained view can blur its control. Restore only that connected control, + // without overriding focus deliberately assigned elsewhere during the update. + afterNextRender(() => { + if (focused.isConnected && this.document.activeElement === this.document.body) { + focused.focus({ preventScroll: true }); + } + }, { injector: this.injector }); + } + } private readonly changeDetector = inject(ChangeDetectorRef); private readonly service = inject(IndicadoresService); private readonly memory = inject(IndicadoresMemory); @@ -32,6 +51,23 @@ export class IndicadoresPage { readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; private readonly catalogRequests = new Subject(); readonly catalog = signal([]); + readonly searchQuery = signal(''); + readonly searchVisible = computed(() => this.catalog().length >= 5); + readonly searchResults = computed(() => { + const items = this.catalog(); + const query = this.normalizeSearch(this.searchQuery()); + if (!query) return { items, active: false, count: 0 }; + const matches: Indicador[] = []; + const remaining: Indicador[] = []; + for (const item of items) { + const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query)); + (matchesQuery ? matches : remaining).push(item); + } + return { items: matches.length ? [...matches, ...remaining] : items, active: true, count: matches.length }; + }); + private normalizeSearch(value: string) { + return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim(); + } readonly catalogLoading = signal(true); readonly catalogError = signal(''); tema: Tema = 'claro'; @@ -54,6 +90,7 @@ export class IndicadoresPage { } changeDominio(dominio: Dominio) { if (!isDominio(dominio) || dominio === this.dominio) return; + this.searchQuery.set(''); this.dominio = dominio; this.tema = this.memory.theme(dominio); this.catalogRequests.next(); diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts new file mode 100644 index 0000000..80760bd --- /dev/null +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -0,0 +1,162 @@ +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 { NgModel } from '@angular/forms'; +import { MatSelect } from '@angular/material/select'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; + +const items: Indicador[] = [ + { id: 'A01', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'B02', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'M02_sexo', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'D04', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, + { id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, +]; + +describe('UX-05C búsqueda local y partición estable', () => { + let fixture: ReturnType>; + let page: IndicadoresPage; + let http: HttpTestingController; + const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; + const disconnect = vi.fn(); + beforeEach(() => { + vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); + vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); disconnect = disconnect; }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + function load(catalog = items, domain = 'tea') { + http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); + } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); } + function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); } + function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); } + async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } + async function search(value: string) { + input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle(); + } + function respond() { + http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); + } + function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } + + it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { + load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); + expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); + expect(cards().every(c => c.expanded === (count === 1))).toBe(true); + if (count === 1) respond(); else http.expectNone(() => true); + if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); + }); + it.each([ + ['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], + ['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2], + [' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2], + ['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], + ['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], + [' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], + ])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => { + load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards(); + await search(query as string); + expect(cards().map(c => c.indicador.id)).toEqual(ids); + expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim()); + expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); + for (const card of cards()) { + expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id)); + expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.expanded).toBe(false); + } + if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); + if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe(''); + http.expectNone(() => true); + }); + it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => { + load(); await settle(); const field = input(); field.focus(); await search('sexo'); + expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo'); + field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2); + expect(field.labels?.[0].textContent).toContain('Buscar indicadores'); + for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy(); + expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull(); + const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement; + expect(clear.getAttribute('aria-label')).toContain('Limpiar búsqueda'); clear.click(); fixture.detectChanges(); await settle(); + expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); + http.expectNone(() => true); + }); + it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => { + load(); cards().slice(0, 3).forEach(c => c.toggle()); fixture.detectChanges(); respond(); await settle(); + const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); + const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); + beforePanels[0].applyFilters(); request('A01').flush({ data: [{ y: [2, null] }], layout: {} }); + c.unit = 'S2'; c.add(); c.year = '2026'; + beforeFilters[1].changeMode('manual'); fixture.detectChanges(); await settle(); + const states = beforePanels.map(p => p.filters), results = beforePanels.map(p => p.result()); + const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement); + const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple); + const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue')); + const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'save'), restores = vi.spyOn(memory, 'restore'); + const reacts = runtime.react.mock.calls.length; + for (const query of ['sexo', 'evaluacion', '']) { + await search(query); + for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card); + for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel); + beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c)); + beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c)); + } + expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.expanded)).toBe(true); + expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts); + beforePanels.forEach((p, i) => { expect(p.filters).toBe(states[i]); expect(JSON.stringify(p.filters)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); }); + beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i])); + expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']); + for (const write of writes) expect(write).not.toHaveBeenCalled(); + expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled(); + expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); + http.expectNone(() => true); + }); + it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => { + load(); cards().slice(0, 3).forEach(c => c.toggle()); fixture.detectChanges(); + const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo'); + b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle(); + await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error'); + expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true); + a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]); + const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} }); + expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true); + }); + it('mover una tarjeta abierta mantiene el foco en su control existente', async () => { + load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); + filters()[0].changeMode('manual'); fixture.detectChanges(); await settle(); + const field = fixture.nativeElement.querySelector('app-indicador-period-filters input') as HTMLInputElement; + field.focus(); expect(document.activeElement).toBe(field); + page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle(); + expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true); + page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); + http.expectNone(() => true); + }); + it('cambiar de dominio limpia búsqueda y volver conserva expansión y borrador mediante memoria existente', async () => { + load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); + filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add(); + await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe(''); + load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].expanded).toBe(true); + page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe(''); + expect(cards().map(c => c.expanded)).toEqual([false, false, true, false, false]); + const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} }); + expect(filters()[0].selectedPeriods).toEqual(['2025-S1']); + await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; load(); respond(); + expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); + }); +}); From ecf2778f1a1f5d059e532cb9cb6b21f174337145 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 13 Oct 2026 11:38:17 -0600 Subject: [PATCH 07/51] feat(ui): incorporar base institucional UX-06B --- public/images/LogoISSSTELEON.png | Bin 0 -> 13023 bytes scripts/ux06b-resources.test.mjs | 59 ++++++++++ src/app/app.html | 13 ++- src/app/app.scss | 90 ++++++++++++++- src/app/app.spec.ts | 53 +++++++-- src/app/app.ts | 5 +- .../indicadores/indicadores-page.scss | 28 ++++- .../indicadores/indicadores-page.spec.ts | 29 +++++ src/index.html | 6 +- src/styles.scss | 106 +++++++++++++----- 10 files changed, 333 insertions(+), 56 deletions(-) create mode 100644 public/images/LogoISSSTELEON.png create mode 100644 scripts/ux06b-resources.test.mjs diff --git a/public/images/LogoISSSTELEON.png b/public/images/LogoISSSTELEON.png new file mode 100644 index 0000000000000000000000000000000000000000..df4c1f93561d6a8db96768ad9b46632b53ec6367 GIT binary patch literal 13023 zcmeHu`8(8K__tC@SrUn4NuN-bO4-*?lChNRTavx8WE~ljFeOw(V;}o2+1If~_Amy6 z31y7IU@#cNb9|qF;rZ?P{@^;-b>_U!xzBy>{eF3GsISd>=F%Ak1_oB0hgwe<7*04a zFdTC{%>-sT9*CNPf!Xt+xi=OdGgg)lQQ8V;VN2 zi)VgR@wf1=O6YSB=3^%58H=1|s-fnh&buc}QZpRX|BP{E&>xCRYAd!r6#Y~4EMM2U z^vgrX7Y`0#0vSWjxNEn=J|j8MAA{^Ysw_@|gBkkwZt5M4L&_)?FsL8X;042*205q%ts^IoESEa0$g91A~~l7$X=A-xwaZ{d9NDbUNIw*YD+J|Ap#(WtG9*S zHJ$+>RTt6V{n5~jOTOPBA*`y^f$z$~{9sJq6&suFJzzTA)y#e)Lg&B73bwW6?D?b@ z$hs)eTr9tSv0lc1xCaelc1Zxo+r)x(e`GXxZ-6b8KKk-d=A%OPxi})N zE$_X8*Z6aDs5$LCX6NwYAiY`8xCwOSj~iHA2Np*oVEbED=?3$^U1wV76%bn=68(8Y zmW_%{hpe=|2j}|)1jbYI)oFQ5rbrUizOk6x*aX&}{72gO6DM>x!gS)BxWOKdrpf zmV(CmzwYJo17zJgXVUY%oYc@nLG0}O3>honPn?mTp>^oFp ze~4}qoWC(9?vxM+Oqx2{?0UODl($=J)9ouHdphetZ2vZRjdVbe6OjgX$q;=f9W=rg z3duff_Lw|>mwuVU#^pEz!y*TY1z+)TVGFX%$?vp1hS#zPsA zk>E^xP4&aB&7mK$Ti#j{Wq{%>6JW(w&-bheR*yRn-KZ+=398lv{-HHO^)6Y6!u z+R@hdmHy{7>LQuxWl~l2@$IW~A;VN)*3`RBJ0K7Uz#<*3{nBfSME_P`9@VK}_GxnV zl9Z;LihHKRDb=iJU~z{1J88y5zx6uAR?#hEW!L_>U{m{}d8K#KDV^I&lD}>I9FA^t z8rAp4SYlaMX+^uE&JoE{VxqTMx+#~u}ly~2Ke{Hz*2a2H%c{WY@#lgP>d#f??1eh}4{os~}O0-LBw_T(f4U%{YoGJ?F7~Py4))iHGS<#LNz|Ly!HU`$)Xuu zCfVe3o{o!w4Tssw17UACQo%zi(196qaH`?hjBC~K8AeZdP0dFHJL`Vop`1X8!0S=> ziyZ6r1`VCYT2opbuaqsU<#oX=ldi?{z5zsyAa@HUtEhPq5wTGtwy(2ZP>->v+@I36K&nr8x`1Z zM_)c(tZ^EC6iah9{k{fMw&+(J^2_5`H)zVI;jb|;RQ_J~3FP63yb#>c|L^&F{x#aX zM^c8reimF@Mb!qsA_)u^%#u$M^M|9maV0xPu0{uw?p0?daW?oM3$Ym3pC-)sj)gH< zwiazAv3j<0`kvNh-^LYzn-`;!70X!R?&+7x?5$TVsfkgYuxM<`&*r!Ud{INtN^n(d zB{XOxkp{P(f2T2z25(f?hCjR_%mm{nilZR0*~Zd&lJtNhmFNGcT~xtcjgt@##)irM z2mvNfTA)PA!lyz7v4l&+kEw(P+&-3;eW>!$w~V4QB5DzcsOoojZ|==_AHGJn;&;3LJ^#H~TRr^E zJHOREo!Mb8C%Wi`%^u;%QzYAjaC9%f_~PCM{d^T-J|-{!E$7%6P1XOy6yv*5zrnDP zW^zPA!-@^tvgmKJqPd)mEnmGmayKYti*8YUFIjKWr@6-YOYr7gFm(V{WsK7s<~itM zt7;A2YgBvCLGBtM5)kr|mCv_#)BNk_w}{y-wbebf3q2(zA@8JBKA-u1Fc})VcN;zy zx9+@UR@*<2IXT>la>Z#meVKLoo5nSGgN3br@rFH4#b7`9@wfmApr~9yxOtH!yyWYC@wG-z5Y=ldWk*9 z;F79S%;eCa^F-L_jX>Y@W2Bz4lk*ATVMuhL4Vf>n|w7L-L}AHhYTcmB9-Lopbk>r+bP zS((>r!Uw*}sRw>_W+`J+hx$f`y|-s3)zb81FDc6v#aM<*tNa&F41KD*kZmvcKZ}9* zT;QlUGTw$tsSo5#xXSA;hy8s-zge;>&$oCYcbMUd%56oyXBlfR&Apz5aJQQqS9;+b zEPmgrrTplM>$Kur)hVDfNiqqH8>gMiyG4@NqpvLx=81QgPCL3bKIqS^t4}fRDxuyZ zpLWjg2y0W{Ih*gw;U1TJg%QV$X>j;lpwNcj2^iWHy3tSe#h&N^>b|A zI_2CKDgT!ZDF)26aq?)~#19Xm5ubH06K(QdJ-)x)4KH_Lk}MHH2_y~z?&%F!7rL@l zrnwE@wR`gKX5y4&{N8DYz*`D2+pD#e(Xr*Fa+F3=>wS#Q;gLMLCdZxo`PYwYC15Vm zey)ndKoT1(Yh|Uo?6+5oM-Tt;;kCIkRe#9p`3&v0cSRsw5^js;72+?E1KY26B~zTZ&~T4wA2D znCGg=d4%6BFzKUkr)uUO7@z{B8O?*OO!L<+FS<1NW^C2o$1zvf1kAgjzDo0@B=3zb zKoe|m1r>wUU);8Bo7=75ZlcocY2|D|q8Dg?V0S4(bGycyiq|)K<(M7n$(3DQ+n0y- zFL8LmYc7`SBLvYD{P6JmfG7`lOZG2DLiT)HHxn!?Q(Nh)P=B7Zr|8YGkv0^bb4KF9 zjZeE#H6PYYn(#jEe3sZ{S3Ju5C0w%fi54|Lu?ewYvfiJ0VCXm;w=RdICyFeV0&6?L z;1N%r*EOSTu(P`As35~w7*lbQAq0sN(n_r7SXRZWrth78(Oeyr(ai=e#%l+ z{|m2P+1|>|Kv5B+(h2jQETSkLnl8=d@&(IE+XCxmeOKk0!d0HaZjV^NZ_-mv!)~~) zs&<^X1B;=*hZ?G_272DPzdc4C|HOYKc7SF>%Z8Teao3>J^llt1mwX7kC{kIp#@~Fp zYJ9eS>g_hI+=uT4PsQ*(4J6y61{U7@k%jjGoP}&((q+vHK8gHf%2(P9->mGdTEZoG zR8Bw67ACx$AxoDyFV+{CPCAy-mha9AbQI~D1iaW~Tj|?@M)Do_6LN4jQ&0Kk2lCfp zqxW>hM)XX64TXp5q{{WRv&gL^vxdaJUuT22j#JAJ!)Z3$zvcAGI_%ba;!l zz#V!V^OHrRWV*{Q&bccrrCtMxveF(8l`L;?$z^t?v}7NPV^On@OUA*XyVkh)Z9fFo znN6WL$_(7n7;Jp^l`Wd3Z>hWw^#9rrjp$;lneG%nT+Ik=_Ts^q&X4Z$OYo&ED{HBx z%{2R}<=0#M*uw5r-q=i4ed5x0YtRR-8ik0GZQMv$)uuQ*cCIyE!~0sJAmp;E%lcv? zw;89IlDBK2?SA8*2`)Pu(V^Xs7v8T^)ZKO;eESV^`3f1h0B65B>3%xwOA6yio>^qn zMa}W5*;nQAu}P-RKtX#8?I@tfjaw5|jKnWtuM~4OFm8DlF6IiJM{sSn{mm#;tg7m;86q(|1Nr z;Q1Mpe}?3CN4jj33OrPW^1d;U-v3zRUR|dV9*K}|vXYQu@=NXE5Kz0{vHz-^r|-+& zUC&m|jg7r^;K&Oy#lN(f6~Eb6IYo=bkNk;fNHOGT^w)H%?zQ$6zj?tG1@< ztt13SxG{&tYxXns?EjMR$}g6BE4pc(1yn3YAxDo-_tvz{swmZ(svs-{60}af6~9mJ z33*pC3YLzd(=hJhgn~VlnP%C?dIpWJBy5|a5x*EjI~ABr4GLD=E2s4jZV$bGJROG> z@rUa2u)MKrEm3rH#%u1bEoyReF^she| zOOIj+$CfgVBR8L_YVRnFw!&jVi8qfU$MlDEA;T3AKc-9Fe`^VnxFApB6|I;+O;JX+ z7n#rb29!L5B7LJ9o=hhd+Lz)ghsCf>Wa~?VmH%eSSpxOMM))tOUn5VNap%lGTInku`OXZrE3LdKEED^07I5t6}x zs_!?u<+ZylrU^FHwmIHE7^_lVZ4!&Fj1~vZPfk;r{lD5b!tIsgv)I#eC@Z(;cMkqD zI_&o1uYQtCcqh#dqI7?58_Pi1-t{HO8K;=%O{1R|PI(&NUC&nRx^1&4I9aNWOKs4q z+S{XydU{Psl`a!U6ktkk>@RP~C~5Pl`eZ-z`)VIVy7Vf(j(uS%wj#kQ^1?1Z0}9fc zGo27TcAgY998lS#D1SNDgo4<)GA8ah-ggw7w@a}L$(e<(OSO}01)UGOZ`THn`YBQF zmWU8#VhhU_B)1CgrN;FhyPQSRZwkH7R|=23&~@K~-yU;n&^D60P6J6L*4qY71qyDa z8Rm9Av9s+Ra%=X=F-65_lpsYsZW%K%8QYR;1LyrA((tjc&~4T-^HnMBbcNB6B4tQ5 z$|u@rwmsgzfJ_yOD0!6s{c;QJdyqqMJY2>$aBVxDIBsC!87vVt!`V~$^v3dQ0a*3d zl_*+$u;&dX<@Z}L`lBIXQVMHsOAE3idX?6p2k=Z<?HIU;RXSE6+a^yThP?r?Zt{sceAh4V__^ft z1#9ginF>vAz9duUi9Rsp)HIeIa`wmreNc?|a(B%*_!f)>Tl;J>(<2FF zk&}GdQ;d|%xDRi2c}k%t|X`&$uWb3 zJNLJ#Be0eBJ`K(b(9s5~gYU6%nRnj=EUhbSx@qkjM3>b}ZPu;?#~?y-s*|xpesKPv zCS7WE2=FMe#0%frWBA*%v+(3|X+Ip(Jqh0={G5H~&WXU~BpapjMU4(?rLdZB=+>_7 z*|*zh3ES2d55z{KyurJX;9ifVEt`a}i_Bmc0_J2Ti<_!rS)8O>OL0|Dj*;EoaOx&4PLcktv5&Ia5Xtbaeqq z`P=61)Ut*O5*w_&P*U#CD+kPA)FunX0j3S*)Cl^_~8l3@N%eaB9pC{h&iH21^<)QZZn3MHAXGDr7^t zAqGlOke1;dv>K$A4~_S66qfl!(znJ(21;XM%9jT5+4|3Zm6UsbJiFR|5OGgzMBt9z zkSoY*t!m0`c<&gLSvK7`DI3?#*>{&)*fGF@v%C|SCHeaV z#u!!U%JR_+W{1i4gt~sKKYm~QcwKRw>)u+B<|^rhXnWYlpjJq_=zS+fW%RbaH8sn% z_Lkt{)^+V#PuZbr+W6cvkuG@N_z8*dK6aHAIbX~_9t(bis;z$lcw3g{GzjDU;Pii1 zyNxSW{R6r$Az~xPT}Tc}QdPFeB1!4M-@S~(+{S-7n31?q%5+o!b6pJ3g?tzYRQ^2i zpVfF>zfou}N_BSE?Aquf#w|S4lpjHI-wK|8_7>SC{ntz>uZg;{&&t=ZG+X~kv%mfm z+Yf*p=(FR*LoG_;NLT*8?A^wBxZrcbfo6H;Gha$gA^%sB;L^VIWw1aMf|;-Tb<5DB z@S)RuT&B;}bk-fKhJ3SkzTEAvPcBc88PM{YeEVF#A2LvM zqfUGfI-tG~euI-RDXOpFS5+W=9mGZppF@<^OLxp1v~xFo4)Q{)r)eL`ZmV4UC-D4M zh2RSF<}0g^4|*-Y-iK{I8Yjb-#e5;P_RoBUo(R^xN2I?Vzwd4tV9gVxg3KMP=(Ds> zzdICcXCtqyf!vmVzv^zR%u~Rv`~K`dqtVT!v4G0LCntWqPm)#$*3Jo~fp{@$w)7j) z^koCZ?9?4imW%r0)zhECkRu7j3B;Ew$kE_lGY^#+?HZZN3A?9L#IoFs{8H6dTpZNL zP2asNFokAQ?+t!$IqPDB5e;Z_&xVFT*I**swsq(OuhhuG0{Yg`4n&6Az0 z@n({DCaUs1I628zARmT5AkkfGuJDu>&JC2snHXDz#xgU@1%+=4m;W@`sZExP+hJ(^ zMy=NtFRG-y#LCn`H@L6+av9Th@h#!G=hb70l zb7$NBJ@?`w8Q;;YZ~nK4js*oUonp<_E0Qkmnqnir@=}iqAA9DSxvSNwKI^oZ->}UP z!k_~yVJsV(Uf@7z71?@GSUoFM_D06sR788xN08-%VQ%;^=|9cn9q4@i8g=9^>(-GW zi?yDB>~Xz-`H#);n@c9Pz)$xp>2092TclpP6SC%~YC$>u z0FIWM=Ho^|baRaFP(T6YlSuGVf6(s;MMk|KL4)7R34H{W)Od{aL;cx4m__T_;gjyQ z>tk08@g{E}uFmKvkbL}oRX(nJMbj3ynjcYZX(Pp50VaingC9bv+U#Ubn(-OEnrwU` zk6HTtLyXMq!B8vNQqX0);oD|i$f&h}$OzmE>(^Ih;dmHr8doHcu7GC%rQ=FGu;OS? zF9x;UkxN^USAIhsvI|Ef;-9HC0L#-5?S~N(v-#`auCrlZKVchW@9916`C2d2-avhX z6ZOv&>OZtr7aV_(qBV1kPLrvb)(g5C&{x@GZxmUu;wW>OY!`3&bGl9#O?*8FJHY3X zCiOI_P0y)+3b)cTn={0yUIUqXXGRkb9@4X*p_EifAA4Soz7=yGt6soVo$#YozlK<5gp6HMs=_M^2NPTWl5VxPG!c!Z zPd!$F1bsk+WMk(e{8l8k9^H?F|NXC>XGvB#xE5F>%`-2gKXzi`etD-EmvDX~UC8yv z!$wLH#P{@*0bxu$qGDCsF3 z^Bd*w)DrTOp*5+`;LWq6}tMsc%pL82R(N? zjeRFUk+&rvyXUsMg=W#y&v*jq)j&x(9(~!#!D1FJ$npgcKjZTD&~vEWelOle@CH!$ zDhFa9=Gdoe8N05JSxfovtYjF%7$)o@d4nJPQYUF9s=ki-)pCyH;jmn0Ek79fq`Nkn zYP9tt(^x6x-(^DD3juFd_>`iV25*Gw#LK86?#AlPVZr2m?fKt@3CY@l8=taxW`|-t zpX4zxoDV<30{knClJ2YY)sKl^rQ<%Tk*<$~E9VW%oh*|w7JSw(JZLgjqxt%6 zTG|40rJq{^L9!Dk>*>C?=RHz2m@<1IO{yqx**d>M`ufxZYbr_;8+M*h+q!1l$mAO&KdgIW#JKJBph9i*CHiX2vfvZYTNYA?7E@2JR(GKt*h zJrx72yY$9MX@lFJ3>N|vRY1}+2%1UVoZTI7CRc@6A9)DdK2yCJ@X%P4js0X>?PY4a ztx-nr_6!KB3A|B7HJJOk&vP~JxKJW>sm(X+_Hyksa=!kDB%N5;H%B{Ol1ouAjv#?n z4X1*#{Z_q_T_U1B(Rn3|m& zl8CIQug9o9==cQ^8x9A5Lxr;SuOpx@nhq?A_nt~`Xi$wY*;^2#c4Jl8D6F2E$%;4M zerX{#f6DjxO<_D^v6Vd&rRf-Fk53D5s*TOKk#qPo$k%2ae3v^h0LO?V@R`h`AQ4cd znp7@hR_xx=^_gJTJH5BQk&1Tt4iEktGr;aVz+GTrtT!{rjq#kduNR&WY^^^4j|0-*Cg|@S z4*`}W!w4y*8!&HOy9sc>>FT{p_K zXS6HY(C7`B*7KWV6Mus}J&N;VSu#TYZsWMidh{;I$KuxRGz8$YP6A^(8!_|*^hv#d z7-)5<&C#y>1Z|;9u_o3<#RpA%CaGP&|B@I*e&X3KII_YG;658;XR^4Qn?|07tm~dV z9$i?Z_ek%<$$Jeu)xgqAt29N6pa!?$vN#L*cB*o^D~linudA4;B+jy$gXFGm+lQ4<`}^=0)Z1azv~4rHta6hZ8O^pv=+%w= zrPyJr$|Q)JV)-N`LGRBU9IH%MAUX3;Ce{Cwu+OkX8vN&u&Y!n?=RA^p(?3~!^VL7I*P*`qjYV3NF z1`U9|zX zlwA3}m71vRHN74@)Y4SK%wAUV3ewsZE>#Zth}fqb@tAWpiTFzWd_c!}zmzZ+5)?=cja!Fg=mK5MwDY9RIfnPTZi)=(C_P&|>_pjB+8 zZ~%rwmZDnL56fUmK-lC{#jO+`@kRhmWOiRa30(Q{N1EKptq zU-}esZ08bO^V4ML2l;O5d;_NoY+_Ng|}oGKQS9qjEibSgp>OPP5iM^efJtIk1%C>hT$Lz+Ut8tTp99{vSW?No* zA4~cbq(bEGTUJFT`+Lnb>9wSp>@Yi4FJE=hP~jWr*-ZQpK8~~cOZ``8g!SK3UPxko z5fE*dYd@TACWPwtc>lhqkufean#t^_HkE-V5V*vivie8zI9qoH`u4eWhGNdqW}wBk zaY`=h8I>E)$qW{9T;zCi1sX;lL{ehB7L0#EK zI}?vHT%U17CmeHo5Sp0fu9Ilhxo4b{C3}(^zka2?y!w$VrG0UgB(D$?f<@!1o;lXd zd!^;jX3v@SPpw`$pN9#Cv#F$;zFVkuH|6zEF>WHeUm@^NuZ+nMMq};lLq<-d`f!sp zpqexEjz>txla$dA1M zpX%#yE2&`Tl{i^vFx(pW1=uCIzUMrxe~fdhl>&eJK?S_0pUMx=5Z`j5}I0g@x&^uhKQdMzaSUKYn7h_Qw6#ZL6l6s&R!Y?lzUy7a1wQ z;hW&&hPR#xa8T}kPRUl&{yq4~5m~;n0A82U{@omaSCF&vHihHIBj^#`TRnbkFZ)fzlZn;cRJo~_=2ZXQ`UzXs zUR*!aeTGUjxY)G6EXUzx`%K6a^BV-6H)p5yw3KD{E&A_8;#U7DY)_r?2z*-meTh1Z zYz?Tlnd*o#McJO1kMpofW>?yQ+q`hEDAO#7<1)F-bw<*CWNX<${u3o2@g}*zk?Ipu7O zG{`TUb08~lHvv)$`N;4$frSj+gR8py32)zzgz|5PtLNHWUj`U7gW~|)`37{Q6{VVf zQo7!-!B#EHreRuBvD)HL0D?2Tih`*1J-4Pekc+4Ck2G6i?BtT81pv)t*tqs=I!VL1 zNH_k$OKy5A36#VHjYMyvjKYsVp-TW$V*rRuUi60}ksfubpmTCI^axRO2Y?^Gh>WOh ztqle1pg3h7hW5dV{Wlab!T=T1zqa>8O?09HvC||P=`ABrBGQbR-0Pv7L7ujZ2B+Tb zd4v>L`uzc!w>J3%`XrzRa_BGo37qGgV3?a1c)qW1x%z1=2>&X~%5oj|V1Rbp{zNNQ8jSM?NjIa|0>Dk|J0?K$zdNx5(z8-{n`WJnzDP^t-|b6K%2EM~I&wO>;EKJZM6Ietqmd{AT45 zcVH$xEI^MGqY!BAhNZr#2k+XNdEr+-Ay2;m>;azkjv;_X@p43RcwyegQX1dR|CWpE zG7as6YF&m&f*mrf8=JMPfXG~(!@d=~7aiA#CrC7(kPdm*au)ph^_{e`!QWWnIbq=$ znf;;=zE~3*%O0vqnpOvT_>g|BsSwbrewNuGKmnzOK!ArBA1Z6)k2TS@P{mQHjlIM6 z#im^nRRF!L{<`3LJK$weS0(MYTIPXpi$VEJW-`n08KlFW_kaKMDr({mJ2U?s3JHTW zy6aN#K1E+$Ei#%-?`cLjh$n?AUd4` z$Vxx6!?-Mu{KM9kLCXV75olkyv=Tz<95&t3+L1?v3)|WzgD1)8D1_ScCdCCC4*ELdrcLrj9TDsd?k5kJ}ro(tSXkd%MayF*~*5I)?v&h?nxH#L+JxpQF3_#rt zu>&lqPN(DG9POUA<#A+~*(qtV`2M#@AeFxA-f_DW{-1$SYdXd4-w4}WKf%p6;|(Kv zY+yOW8^ZdNhSa}D>}f7m{55-J?8>0Da00GbKi*{Ja;M@ug%9Y6`)xenK4}2P+8u>H9!@uCFeIwr11yYwsRk1tR$-8U}xF=|3sAs9XiFP4O4Dx zV5Yu readFileSync(new URL(path, root), 'utf8'); + +test('UX-06B: idioma, título, base y favicon', () => { + const index = read('src/index.html'); + for (const value of [ + 'lang="es"', + 'Plataforma de Indicadores | ISSSTELEON', + ' { + const index = read('src/index.html'); + assert.equal(index.match(/family=Rajdhani/g)?.length, 1); + assert.equal(index.match(/family=Roboto/g)?.length, 1); + for (const value of [ + 'https://fonts.googleapis.com/css2?family=Rajdhani:wght@600;700', + 'family=Roboto:wght@300;400;500', + 'display=swap', + 'https://fonts.googleapis.com/icon?family=Material+Icons', + ]) assert.ok(index.includes(value), value); + const styles = read('src/styles.scss'); + assert.ok(styles.includes("--issste-font-heading: 'Rajdhani', 'Roboto', sans-serif;")); + assert.ok(styles.includes("--issste-font-body: 'Roboto', sans-serif;")); +}); + +test('UX-06B: PNG original y mecanismo de publicación del asset', () => { + const png = readFileSync(new URL('public/images/LogoISSSTELEON.png', root)); + assert.deepEqual(Array.from(png.subarray(0, 8)), [137, 80, 78, 71, 13, 10, 26, 10]); + assert.equal(png.readUInt32BE(16), 1125); + assert.equal(png.readUInt32BE(20), 358); + const config = JSON.parse(read('angular.json')); + assert.ok(config.projects.WebApp.architect.build.options.assets.some( + asset => asset.glob === '**/*' && asset.input === 'public', + )); + assert.ok(read('src/app/app.html').includes('src="images/LogoISSSTELEON.png"')); +}); + +test('UX-06B: tokens globales, tema único y uso en shell/navegación', () => { + const styles = read('src/styles.scss'); + for (const value of [ + '--issste-text: #081839;', + '--issste-background: #F7F7F7;', + '@include mat.theme-overrides(', + 'primary: var(--issste-text)', + 'outline: var(--issste-text-secondary)', + ]) assert.ok(styles.includes(value), value); + assert.equal(styles.match(/@include mat.theme\(/g)?.length, 1); + assert.ok(read('src/app/app.scss').includes('background: var(--issste-surface)')); + assert.ok(read('src/app/app.scss').includes('font-family: var(--issste-font-heading)')); + assert.ok(read('src/app/features/indicadores/indicadores-page.scss') + .includes('background: var(--issste-accent)')); +}); diff --git a/src/app/app.html b/src/app/app.html index ff298c4..2cd6ad0 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,7 +1,12 @@ - - {{ title }} - + +
+
+ + {{ title }} +
+
-
+
diff --git a/src/app/app.scss b/src/app/app.scss index 8e69d4f..45363e3 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -1,3 +1,89 @@ -main { - padding: 1.5rem; +:host { + display: block; + min-height: 100%; +} + +.institutional-header { + position: sticky; + top: 0; + z-index: 100; + background: var(--issste-surface); + border-bottom: 3px solid var(--issste-logo-lime); +} + +.header-content { + display: flex; + align-items: center; + gap: var(--issste-space-4); + box-sizing: border-box; + min-height: 69px; + max-width: 1488px; + margin-inline: auto; + padding-inline: var(--issste-page-gutter); +} + +.institutional-logo { + display: block; + flex: 0 0 auto; + width: 200px; + height: auto; +} + +.platform-title { + color: var(--issste-text); + font-family: var(--issste-font-heading); + font-size: 1.5rem; + font-weight: 600; + line-height: 1.15; + overflow-wrap: anywhere; +} + +main { + padding: var(--issste-space-4) var(--issste-page-gutter); + scroll-margin-top: var(--issste-header-clearance); +} + +.skip-link { + position: fixed; + top: var(--issste-space-2); + left: var(--issste-page-gutter); + z-index: 101; + transform: translateY(-200%); + padding: var(--issste-space-2) var(--issste-space-3); + color: var(--issste-surface); + background: var(--issste-text); + border-radius: var(--issste-radius); +} + +.skip-link:focus { + transform: translateY(0); +} + +@media (max-width: 550px) { + .header-content { + gap: var(--issste-space-2); + min-height: 64px; + } + + .institutional-logo { + width: 145px; + } + + .platform-title { + font-size: 1.125rem; + } +} + +@media (max-width: 359px) { + .header-content { + flex-wrap: wrap; + justify-content: center; + padding-block: var(--issste-space-2); + gap: var(--issste-space-1); + } + + .platform-title { + flex-basis: 100%; + text-align: center; + } } diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index f1bdf4a..6f80b93 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -1,25 +1,56 @@ import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { App } from './app'; -describe('App', () => { +describe('App — UX-06B', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [App], - }) - .compileComponents(); + providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()], + }).compileComponents(); }); + function render() { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + return fixture; + } + it('should create the app', () => { - const fixture = TestBed.createComponent(App); - const app = fixture.componentInstance; - expect(app).toBeTruthy(); + expect(render().componentInstance).toBeTruthy(); }); - it('should render the toolbar title', async () => { - const fixture = TestBed.createComponent(App); - await fixture.whenStable(); + it('renders one institutional header and the platform identification', () => { + const element = render().nativeElement as HTMLElement; + expect(element.querySelectorAll('header')).toHaveLength(1); + expect(element.querySelector('header')?.textContent).toContain('Plataforma de Indicadores'); + }); + + it('uses the authorized static logo with alternative text and intrinsic proportions', () => { + const logo = (render().nativeElement as HTMLElement).querySelector('header img'); + expect(logo?.getAttribute('src')).toBe('images/LogoISSSTELEON.png'); + expect(logo?.getAttribute('alt')).toBe('ISSSTELEON'); + expect(logo?.getAttribute('width')).toBe('1125'); + expect(logo?.getAttribute('height')).toBe('358'); + }); + + it('keeps the routed content inside a main landmark and a keyboard skip target', () => { + const element = render().nativeElement as HTMLElement; + const main = element.querySelector('main#contenido-principal'); + expect(main?.querySelector('router-outlet')).toBeTruthy(); + expect(main?.getAttribute('tabindex')).toBe('-1'); + expect(element.querySelector('a.skip-link')?.getAttribute('href')).toBe('#contenido-principal'); + }); + + it('does not duplicate domain navigation or introduce shell HTTP requests', () => { + const fixture = render(); fixture.detectChanges(); - const compiled = fixture.nativeElement as HTMLElement; - expect(compiled.querySelector('mat-toolbar')?.textContent).toContain('ISSSTELEON'); + const element = fixture.nativeElement as HTMLElement; + expect(element.querySelector('nav')).toBeNull(); + expect(element.querySelectorAll('[routerLink]')).toHaveLength(0); + TestBed.inject(HttpTestingController).expectNone(() => true); + TestBed.inject(HttpTestingController).verify(); }); }); diff --git a/src/app/app.ts b/src/app/app.ts index 71ff325..7af688e 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,13 +1,12 @@ import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; -import { MatToolbarModule } from '@angular/material/toolbar'; @Component({ - imports: [RouterOutlet, MatToolbarModule], + imports: [RouterOutlet], selector: 'app-root', styleUrl: './app.scss', templateUrl: './app.html', }) export class App { - protected readonly title = 'ISSSTELEON'; + protected readonly title = 'Plataforma de Indicadores'; } diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index 8fbe1e4..dde4746 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -1,12 +1,36 @@ :host { display: block; } .dashboard { max-width: 1440px; margin: 0 auto; } -h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; } +h1 { font: var(--mat-sys-headline-large); font-family: var(--issste-font-heading); font-weight: 700; margin: .65rem 0; } header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); } .notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; } .state { padding: 1.25rem; margin: 0; } mat-form-field { width: 100%; max-width: 24rem; } -@media (max-width: 550px) { h1 { font: var(--mat-sys-headline-medium); } } +@media (max-width: 550px) { h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); } } .catalog-search { display: flex; align-items: flex-start; gap: .75rem; flex-wrap: wrap; } .catalog-search button { margin-top: .5rem; } .search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); } + +nav { + display: flex; + flex-wrap: wrap; + gap: var(--issste-space-2); + padding: var(--issste-space-2); + background: var(--issste-surface); + border: 1px solid var(--issste-border); + border-radius: var(--issste-radius); +} + +nav a { + flex: 1 1 4rem; + max-width: 10rem; + color: var(--issste-text); + border-radius: var(--issste-radius); +} + +nav a[aria-current='page'] { + background: var(--issste-accent); + font-weight: 700; + text-decoration: underline; + text-underline-offset: .25em; +} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index e552372..d0ff1b6 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -41,6 +41,35 @@ describe('UX-05B catálogo expandible', () => { function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } + it('UX-06B conserva una navegación con rutas y estado activo en los tres dominios', () => { + const domains = ['tea', 'cacu', 'cama'] as const; + for (const domain of domains) { + if (domain !== 'tea') page.changeDominio(domain); + load([], domain); + const navs = fixture.nativeElement.querySelectorAll('nav') as NodeListOf; + expect(navs).toHaveLength(1); + expect(navs[0].getAttribute('aria-label')).toBe('Dominios de indicadores'); + const links = Array.from(navs[0].querySelectorAll('a')); + expect(links.map(link => link.textContent?.trim())).toEqual(['TEA', 'CaCu', 'CaMa']); + expect(links.map(link => link.getAttribute('href'))).toEqual(domains.map(d => '/indicadores/' + d)); + expect(links.filter(link => link.getAttribute('aria-current') === 'page')).toHaveLength(1); + expect(links[domains.indexOf(domain)].getAttribute('aria-current')).toBe('page'); + expect(cards()).toHaveLength(0); + http.expectNone(() => true); + } + }); + + it('UX-06B conserva el selector técnico claro/oscuro y no vuelve a cargar el catálogo', async () => { + load(); + await fixture.whenStable(); fixture.detectChanges(); + const select = fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; + expect(select.options.map(option => option.value)).toEqual(['claro', 'oscuro']); + expect(select.value).toBe('claro'); + page.changeTema('oscuro'); fixture.detectChanges(); + expect(page.tema).toBe('oscuro'); + expect(cards().every(card => !card.expanded)).toBe(true); + http.expectNone(() => true); + }); it.each([0, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i })); load(items); diff --git a/src/index.html b/src/index.html index 5ac61ae..04446b4 100644 --- a/src/index.html +++ b/src/index.html @@ -1,15 +1,15 @@ - + - WebApp + Plataforma de Indicadores | ISSSTELEON diff --git a/src/styles.scss b/src/styles.scss index 8ba3af6..7afccdf 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -1,39 +1,83 @@ -// Include theming for Angular Material with `mat.theme()`. -// This Sass mixin will define CSS variables that are used for styling Angular Material -// components according to the Material 3 design spec. -// Learn more about theming and how to use it for your application's -// custom components at https://material.angular.dev/guide/theming @use '@angular/material' as mat; html { - height: 100%; - @include mat.theme( - ( - color: ( - primary: mat.$azure-palette, - tertiary: mat.$blue-palette, - ), - typography: Roboto, - density: 0, - ) - ); + // Presentation candidates approved for UX-06B, not a certified brand guide. + --issste-text: #081839; + --issste-accent: #A8C243; + --issste-logo-lime: #C3D600; + --issste-text-secondary: #4B4949; + --issste-background: #F7F7F7; + --issste-surface: #FFFFFF; + --issste-border: #E4E7E9; + --issste-font-heading: 'Rajdhani', 'Roboto', sans-serif; + --issste-font-body: 'Roboto', sans-serif; + --issste-space-1: .25rem; + --issste-space-2: .5rem; + --issste-space-3: .75rem; + --issste-space-4: 1rem; + --issste-space-6: 1.5rem; + --issste-radius: .5rem; + --issste-page-gutter: clamp(.75rem, 2vw, 1.5rem); + --issste-header-clearance: 7rem; + + min-height: 100%; + color-scheme: light; + scroll-padding-top: var(--issste-header-clearance); + + @include mat.theme(( + color: ( + primary: mat.$azure-palette, + tertiary: mat.$blue-palette, + ), + typography: Roboto, + density: 0, + )); + + // Public Material system tokens also reach CDK overlays under body. + // Keep the figure's claro/oscuro setting independent from the application theme. + @include mat.theme-overrides(( + primary: var(--issste-text), + on-primary: var(--issste-surface), + primary-container: var(--issste-accent), + on-primary-container: var(--issste-text), + secondary: var(--issste-text-secondary), + on-secondary: var(--issste-surface), + secondary-container: var(--issste-border), + on-secondary-container: var(--issste-text), + tertiary: var(--issste-text), + on-tertiary: var(--issste-surface), + tertiary-container: var(--issste-logo-lime), + on-tertiary-container: var(--issste-text), + surface: var(--issste-surface), + surface-dim: var(--issste-background), + surface-bright: var(--issste-surface), + surface-container-lowest: var(--issste-surface), + surface-container-low: var(--issste-background), + surface-container: var(--issste-background), + surface-container-high: var(--issste-border), + surface-container-highest: var(--issste-border), + on-surface: var(--issste-text), + on-surface-variant: var(--issste-text-secondary), + outline: var(--issste-text-secondary), + outline-variant: var(--issste-border), + )); } body { - // Default the application to a light color theme. This can be changed to - // `dark` to enable the dark color theme, or to `light dark` to defer to the - // user's system settings. - color-scheme: light; - - // Set a default background, font and text colors for the application using - // Angular Material's system-level CSS variables. Learn more about these - // variables at https://material.angular.dev/guide/system-variables - background-color: var(--mat-sys-surface); - color: var(--mat-sys-on-surface); - font: var(--mat-sys-body-medium); - - // Reset the user agent margin. margin: 0; - height: 100%; + min-height: 100vh; + background: var(--issste-background); + color: var(--issste-text); + font: var(--mat-sys-body-medium); + font-family: var(--issste-font-body); +} + +h1, h2, h3, h4, h5, h6 { + font-family: var(--issste-font-heading); + font-weight: 700; +} + +:focus-visible { + outline: 2px solid var(--issste-text); + outline-offset: 3px; } -/* You can add global styles to this file, and also import other style files */ From 41be0c343fe96eebebc4213f12ed850b277dfd00 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 13 Oct 2026 12:34:03 -0600 Subject: [PATCH 08/51] feat(ui): redisenar catalogo y filtros UX-06C --- scripts/ux06c-presentation.test.mjs | 39 +++++++++++++++ .../indicadores/indicador-catalog-card.ts | 30 ++++++++--- .../indicadores/indicador-figure-panel.ts | 7 ++- .../indicadores/indicador-period-filters.html | 28 ++++++----- .../indicadores/indicador-period-filters.scss | 22 ++++++-- .../indicador-period-filters.spec.ts | 22 ++++++++ .../indicadores/indicadores-page.html | 4 +- .../indicadores/indicadores-page.scss | 19 +++++-- .../indicadores/indicadores-page.spec.ts | 50 +++++++++++++++++++ .../indicadores-plotly-lifecycle.spec.ts | 5 +- .../indicadores/indicadores-search.spec.ts | 2 +- 11 files changed, 195 insertions(+), 33 deletions(-) create mode 100644 scripts/ux06c-presentation.test.mjs diff --git a/scripts/ux06c-presentation.test.mjs b/scripts/ux06c-presentation.test.mjs new file mode 100644 index 0000000..f2dc306 --- /dev/null +++ b/scripts/ux06c-presentation.test.mjs @@ -0,0 +1,39 @@ +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +const root = new URL('../src/app/features/indicadores/', import.meta.url); +const read = path => readFileSync(new URL(path, root), 'utf8'); + +test('UX-06C: geometría prevista conserva título flexible, flecha lateral y foco visible', () => { + const card = read('indicador-catalog-card.ts'); + const styles = card.slice(card.indexOf(' styles:'), card.indexOf('export class')); + assert.match(styles, /grid-template-columns:\s*minmax\(0, 1fr\) auto/); + assert.match(styles, /header button\s*\{[^}]*justify-self:\s*end/); + assert.match(styles, /header button\s*\{[^}]*min-width:\s*48px;\s*min-height:\s*48px/); + assert.match(styles, /button:focus-visible\s*\{[^}]*outline:/); + assert.match(styles, /overflow-wrap:\s*anywhere/); +}); + +test('UX-06C: navegación centrada sin banda blanca ni sticky añadido', () => { + const styles = read('indicadores-page.scss'); + const nav = styles.match(/(?:^|\n)nav\s*\{([^}]*)\}/)?.[1]; + assert.ok(nav); + assert.match(nav, /justify-content:\s*center/); + assert.match(nav, /flex-wrap:\s*wrap/); + assert.doesNotMatch(nav, /background|border:/); + assert.doesNotMatch(styles, /position:\s*(sticky|fixed)/); + assert.match(styles, /nav a\[aria-current='page'\]\s*\{[^}]*text-decoration:\s*underline/); +}); + +test('UX-06C: filtros preparados para valores largos y apilamiento móvil con ayudas dinámicas', () => { + const styles = read('indicador-period-filters.scss'); + const template = read('indicador-period-filters.html'); + assert.match(styles, /\.select-value\s*\{[^}]*white-space:\s*normal;[^}]*overflow-wrap:\s*anywhere/); + assert.match(styles, /@media\s*\(max-width:\s*550px\)[\s\S]*flex:\s*1 1 100%/); + assert.match(styles, /mat-form-field\s*\{[^}]*min-width:\s*0/); + const fields = template.match(/]*>/g); + assert.equal(fields.length, 5); + assert.ok(fields.every(field => field.includes('subscriptSizing="dynamic"'))); + assert.doesNotMatch(styles, /overflow:\s*hidden|z-index|\.mat-mdc-|::ng-deep/); +}); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 5e8af4b..993dfac 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -2,6 +2,7 @@ import { DOCUMENT } from '@angular/common'; import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, ViewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; import { Dominio, Indicador, Tema } from './indicadores.models'; import { IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; @@ -9,18 +10,21 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; @Component({ selector: 'app-indicador-catalog-card', - imports: [MatButtonModule, MatCardModule, IndicadorFigurePanel], + imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel], template: `
-

{{ indicador.titulo }}

-

{{ indicador.id }} · Contrato {{ indicador.contrato }} · {{ indicador.figuras.length }} figuras publicadas

- + (click)="toggle()">
@if (expanded) { + @for (figure of indicador.figuras; track panelIdentity(figure)) { } @empty {

El indicador no tiene figuras disponibles.

} @@ -28,7 +32,21 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
`, - styles: ':host { display: block; margin: 1rem 0; } mat-card { padding: 1.25rem; } h2, p { overflow-wrap: anywhere; } h2 { margin-top: 0; }', + styles: ` + :host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } + mat-card { padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); + color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } + header { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: start; gap: var(--issste-space-3); } + .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; } + .indicator-id { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } + header button { justify-self: end; flex-shrink: 0; min-width: 48px; min-height: 48px; color: var(--issste-text); } + button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + .catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4); + border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } + @media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } } + `, }) export class IndicadorCatalogCard implements OnChanges { @Input({ required: true }) dominio!: Dominio; diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 8dd0b7b..2d4427b 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -25,7 +25,12 @@ import { figureIdentity, identityElementId } from './indicadores-identities'; [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (retry)="requestFigure()" />
`, - styles: ':host { display: block; min-width: 0; } section { margin-top: 1.5rem; } h3 { overflow-wrap: anywhere; }', + styles: ` + :host { display: block; min-width: 0; } + section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); } + h3 { margin: 0 0 var(--issste-space-4); overflow-wrap: anywhere; color: var(--issste-text); + font-family: var(--issste-font-heading); font-weight: 600; font-size: 1.25rem; line-height: 1.4; } + `, }) export class IndicadorFigurePanel implements OnChanges, OnDestroy { @Input({ required: true }) dominio!: Dominio; diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html index 7ae2e89..9fe759a 100644 --- a/src/app/features/indicadores/indicador-period-filters.html +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -1,23 +1,25 @@
@if (types.length > 1) { - Granularidad + Granularidad @for (tipo of types; track tipo) { {{ tipo === 'mes' ? 'Mes' : 'Semestre' }} } } @if (state.tipo === types[0]) { - Modalidad + Modalidad + {{ entry.draft.mode === 'todos' ? (state.tipo === 'mes' ? 'Todos los meses con reporte' : 'Todos los semestres con reporte') : 'Elegir periodos' }} Todos los {{ state.tipo === 'mes' ? 'meses' : 'semestres' }} con reporte Elegir periodos } @if (entry.draft.mode !== 'todos') { - Periodos seleccionados + Periodos seleccionados + {{ selectedPeriods.join(', ') }} @for (period of entry.added; track period) { {{ period }} } Disponibilidad desconocida hasta consultar. @@ -25,26 +27,26 @@ }
@if (entry.draft.mode !== 'todos') { -

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

-
- Año - {{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }} +

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

+
+ Año + {{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }} @for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { {{ value }} } - +
@for (period of entry.added; track period) { - + }
} @if (error) { } -

Selección en edición: {{ summary }}

+

Selección en edición: {{ summary }}

@if (!canApply) {

Selecciona al menos un periodo válido para aplicar.

} -@if (hasPending) {

Hay cambios sin aplicar.

} - -

Filtros de la consulta aplicada: {{ appliedSummary }}

+@if (hasPending) {

Hay cambios sin aplicar.

} + +

Filtros de la consulta aplicada: {{ appliedSummary }}

diff --git a/src/app/features/indicadores/indicador-period-filters.scss b/src/app/features/indicadores/indicador-period-filters.scss index b45eef7..ed8f559 100644 --- a/src/app/features/indicadores/indicador-period-filters.scss +++ b/src/app/features/indicadores/indicador-period-filters.scss @@ -1,5 +1,19 @@ -:host { display: block; margin: 1rem 0; } -.fields { display: flex; flex-wrap: wrap; align-items: start; gap: 1rem; } -mat-form-field { flex: 1; min-width: 160px; } +:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } +section { min-width: 0; } +.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); } +mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; } +.period-builder mat-form-field { flex: 0 1 10rem; } +.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; } +p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; } +.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; } +.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } +.draft-summary { font-weight: 500; } +.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); } .error { color: var(--mat-sys-error); } -.remove { display: flex; flex-wrap: wrap; gap: .5rem; } +.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); } +.remove button { min-height: 44px; } +.apply-button { min-height: 44px; margin-top: var(--issste-space-2); } +@media (max-width: 550px) { + mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; } + .period-builder button { margin-top: 0; } +} diff --git a/src/app/features/indicadores/indicador-period-filters.spec.ts b/src/app/features/indicadores/indicador-period-filters.spec.ts index 89ccc2a..6b3e711 100644 --- a/src/app/features/indicadores/indicador-period-filters.spec.ts +++ b/src/app/features/indicadores/indicador-period-filters.spec.ts @@ -18,6 +18,28 @@ 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 los semestres con reporte'); + fixture.componentRef.setInput('state', { + ...control.state, editors: { ...control.state.editors, semestre: { + added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, + } }, + }); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf); + expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2'); + expect(values.map(e => e.textContent)).toContain('Elegir periodos'); + fixture.componentRef.setInput('state', { + ...control.state, editors: { ...control.state.editors, semestre: { + added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' }, + } }, + }); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + expect(control.canApply).toBe(false); + expect(control.state.applied?.selection.mode).toBe('todos'); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); + }); 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(); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index fa0260f..7bed319 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -21,7 +21,7 @@

No hay indicadores disponibles en el catálogo.

} @else { - Tema del dominio + Tema del dominio ClaroOscuro @@ -29,7 +29,7 @@

{{ catalog().length }} indicadores publicados

@if (searchVisible()) { -
+
+ +@if (showBackToTop()) { + +} diff --git a/src/app/app.scss b/src/app/app.scss index 45363e3..f52f0dc 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -39,7 +39,7 @@ } main { - padding: var(--issste-space-4) var(--issste-page-gutter); + padding: var(--issste-space-4) var(--issste-page-gutter) 5.5rem; scroll-margin-top: var(--issste-header-clearance); } @@ -87,3 +87,23 @@ main { text-align: center; } } + +.back-to-top { + position: fixed; + right: max(var(--issste-page-gutter), env(safe-area-inset-right)); + bottom: max(var(--issste-space-4), env(safe-area-inset-bottom)); + z-index: 90; + display: grid; + place-items: center; + width: 48px; + height: 48px; + padding: 0; + border: 1px solid var(--issste-text); + border-radius: 50%; + background: var(--issste-text); + color: var(--issste-surface); + cursor: pointer; +} + +.back-to-top:hover { background: var(--issste-text-secondary); } +.back-to-top:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 4px; } diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index 6f80b93..c6ea793 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -54,3 +54,68 @@ describe('App — UX-06B', () => { TestBed.inject(HttpTestingController).verify(); }); }); + +describe('App — UX-06D volver al inicio', () => { + let scrollY: number; + beforeEach(() => { + scrollY = 0; + vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => scrollY); + TestBed.configureTestingModule({ imports: [App], providers: [provideRouter([])] }); + }); + afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function render() { + const fixture = TestBed.createComponent(App); + fixture.detectChanges(); + return fixture; + } + function scroll(fixture: ReturnType, position: number) { + scrollY = position; + window.dispatchEvent(new Event('scroll')); + fixture.detectChanges(); + } + it('oculta al inicio y en el umbral, muestra después y vuelve a ocultar al subir', () => { + const fixture = render(); + expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull(); + scroll(fixture, 400); + expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull(); + scroll(fixture, 401); + expect(fixture.nativeElement.querySelector('.back-to-top')).not.toBeNull(); + scroll(fixture, 0); + expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull(); + }); + it('reconoce una posición restaurada al montar el shell', () => { + scrollY = 900; + expect(render().nativeElement.querySelector('.back-to-top')).not.toBeNull(); + }); + it.each([false, true])('activa un botón nativo y respeta movimiento reducido=%s', reduced => { + const matchMedia = vi.fn().mockReturnValue({ matches: reduced } as MediaQueryList); + vi.stubGlobal('matchMedia', matchMedia); + const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {}); + const fixture = render(); + scroll(fixture, 900); + const button = fixture.nativeElement.querySelector('.back-to-top') as HTMLButtonElement; + const main = fixture.nativeElement.querySelector('main') as HTMLElement; + const focus = vi.spyOn(main, 'focus'); + expect(button.type).toBe('button'); + expect(button.tabIndex).toBe(0); + expect(button.getAttribute('aria-label')).toBe('Volver al inicio'); + expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true'); + button.click(); + expect(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)'); + expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: reduced ? 'instant' : 'smooth' }); + expect(focus).toHaveBeenCalledWith({ preventScroll: true }); + // Native Enter/Space activation is checked in Chrome, not emulated by jsdom. + }); + it('registra un listener pasivo y elimina exactamente el mismo al destruir', () => { + const add = vi.spyOn(window, 'addEventListener'); + const remove = vi.spyOn(window, 'removeEventListener'); + const fixture = render(); + const registration = add.mock.calls.find(call => call[0] === 'scroll')!; + expect(registration[2]).toEqual({ passive: true }); + fixture.destroy(); + expect(remove).toHaveBeenCalledWith('scroll', registration[1]); + scrollY = 900; + window.dispatchEvent(new Event('scroll')); + expect(fixture.componentInstance.showBackToTop()).toBe(false); + }); +}); diff --git a/src/app/app.ts b/src/app/app.ts index 7af688e..ff7f2d1 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,4 +1,5 @@ -import { Component } from '@angular/core'; +import { DOCUMENT } from '@angular/common'; +import { Component, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ @@ -7,6 +8,26 @@ import { RouterOutlet } from '@angular/router'; styleUrl: './app.scss', templateUrl: './app.html', }) -export class App { +export class App implements OnInit, OnDestroy { protected readonly title = 'Plataforma de Indicadores'; + readonly showBackToTop = signal(false); + @ViewChild('mainContent') private mainContent?: ElementRef; + private readonly browserWindow = inject(DOCUMENT).defaultView; + private readonly updateScroll = () => this.showBackToTop.set((this.browserWindow?.scrollY ?? 0) > 400); + + ngOnInit() { + this.updateScroll(); + this.browserWindow?.addEventListener('scroll', this.updateScroll, { passive: true }); + } + + backToTop() { + const reducedMotion = this.browserWindow?.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + // Keep keyboard focus near the destination when the floating button disappears. + this.mainContent?.nativeElement.focus({ preventScroll: true }); + this.browserWindow?.scrollTo({ top: 0, behavior: reducedMotion ? 'instant' : 'smooth' }); + } + + ngOnDestroy() { + this.browserWindow?.removeEventListener('scroll', this.updateScroll); + } } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index d0971ec..d4f4a4d 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -2,8 +2,18 @@

Cómo leer esta figura · {{ selected?.contrato }}

    - @for (line of interpretation; track $index) {
  • {{ line }}
  • } + @for (line of visibleInterpretation; track $index) {
  • {{ line }}
  • }
+ @if (methodologyDetail.length) { + +
+ @for (line of methodologyDetail; track $index) {

{{ line }}

} +
+ }

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

} diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index 576c8a6..7be5486 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -1,12 +1,22 @@ :host { display: block; min-width: 0; } -.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; } -.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); } +.interpretation { + padding: var(--issste-space-4); + margin-bottom: var(--issste-space-4); + border-left: 3px solid var(--issste-accent); + color: var(--issste-text); + font-family: var(--issste-font-body); + line-height: 1.5; + overflow-wrap: anywhere; +} +.interpretation h2 { margin: 0 0 .5rem; font-family: var(--issste-font-heading); font-size: 1.125rem; } .interpretation ul { margin: 0; padding-left: 1.25rem; } .interpretation li + li { margin-top: .25rem; } -.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); } -.figure-card { overflow: hidden; min-width: 0; } -.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; } -.state { padding: 1.25rem; margin: 0; } +.period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); } +.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; } +.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.figure-card { overflow: visible; min-width: 0; border: 1px solid var(--issste-border); } +.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; } +.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; } .dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } .figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; } -@media (max-width: 550px) { .interpretation { padding: 1rem; } } +@media (max-width: 550px) { .interpretation { padding: var(--issste-space-3); } } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index d2e4d6d..0f99470 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -128,4 +128,67 @@ describe('IndicadorFigureCard', () => { expect(purge).toHaveBeenCalledWith(secondHost); expect(disconnect).toHaveBeenCalledTimes(2); }); + it('UX-06D pliega solo el detalle complementario local C2 y mantiene advertencias visibles', () => { + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; + expect(section.querySelector('ul')?.textContent).toContain('Las barras muestran la composición porcentual'); + expect(section.querySelector('ul')?.textContent).toContain('SIN_DATO'); + expect(section.querySelector('ul')?.textContent).toContain('suprimidos no representan tasas'); + expect(section.querySelector('.period-note')?.textContent).toContain('no permite determinar la disponibilidad'); + const button = section.querySelector('button')!; + const detail = section.querySelector('[id]') as HTMLElement; + expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(button.getAttribute('aria-controls')).toBe(detail.id); + expect(detail.hidden).toBe(true); + expect(detail.textContent?.trim()).toBe('Las categorías corresponden a la distribución de cada grupo y periodo.'); + expect([...section.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.visibleInterpretation); + button.click(); fixture.detectChanges(); + expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true'); + state({ status: 'loading' }); + expect(detail.hidden).toBe(false); + button.click(); fixture.detectChanges(); + expect(detail.hidden).toBe(true); + }); + it.each(['fig_c1_puntos', 'fig_c3r_cajas', 'desconocida'])('UX-06D mantiene íntegra la interpretación %s sin separación insegura', figura => { + fixture.componentRef.setInput('figuraId', figura); + if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' }); + state({ status: 'idle' }); + expect(fixture.nativeElement.querySelector('.methodology-toggle')).toBeNull(); + expect([...fixture.nativeElement.querySelectorAll('.interpretation li')].map((li: any) => li.textContent)) + .toEqual(fixture.componentInstance.interpretation); + }); + it.each(['cacu', 'cama'])('UX-06D mantiene toda la interpretación C2 de %s visible', dominio => { + fixture.componentRef.setInput('dominio', dominio); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.methodology-toggle')).toBeNull(); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); + }); + it('UX-06D conserva completas todas las anotaciones, sin clasificar ni plegar notas del backend', async () => { + const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [ + { text: 'Denominador pequeño
Intervalos no disponibles' }, + { text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' }, + { text: 'Supresión: consulta las notas completas' }, + ] }, frames: [] }; + const snapshot = JSON.stringify(figure); + ready(figure); await settle(); + const notes = fixture.nativeElement.querySelector('.notes') as HTMLElement; + expect(notes.closest('[hidden]')).toBeNull(); + expect([...notes.querySelectorAll('p')].map(p => p.innerHTML)).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); + expect(JSON.stringify(figure)).toBe(snapshot); + expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0'); + }); + it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'); + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' }); + fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas'); + fixture.detectChanges(); + const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'); + expect(first).not.toBe(second); + expect(fixture.nativeElement.querySelector('[id]').id).toBe(second); + }); }); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 625fd70..fbf67b0 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -1,9 +1,10 @@ -import { Component, Input, output } from '@angular/core'; +import { Component, Input, output, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; import { figureTitle } from './indicadores.presentation'; +import { figureIdentity, identityElementId } from './indicadores-identities'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; // The panel owns requests; the card receives the original and its presentation copy. @@ -49,6 +50,19 @@ export class IndicadorFigureCard { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) tema!: Tema; readonly retry = output(); + readonly methodologyExpanded = signal(false); + get methodologyId(): string { + return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology'; + } + + // Only this exact local C2 sentence is complementary. Backend notes and + // uncertainty/suppression warnings are never classified or collapsed. + get methodologyDetail(): readonly string[] { + return this.interpretation.filter(line => line === CONTRACT_INTERPRETATIONS['C2'][1]); + } + get visibleInterpretation(): readonly string[] { + return this.interpretation.filter(line => line !== CONTRACT_INTERPRETATIONS['C2'][1]); + } readonly hasNoVisibleValues = hasNoVisibleValues; readonly figureTitle = figureTitle; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 7bed319..90cc577 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -9,7 +9,6 @@ {{ domainLabels[domain] }} } -

Uso exclusivo de investigación. No usar para decisiones clínicas.

@if (catalogLoading()) { @@ -21,11 +20,6 @@

No hay indicadores disponibles en el catálogo.

} @else { - Tema del dominio - - ClaroOscuro - -

{{ catalog().length }} indicadores publicados

@if (searchVisible()) { }
- @if (status() === 'ready' && notes.length) { + @if (showNotes && status() === 'ready' && notes.length) {

Notas de la figura

@for (note of notes; track $index) {

} @@ -25,6 +25,7 @@ import { PLOTLY_LOADER } from './plotly-runtime'; styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, }) export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { + @Input() showNotes = true; @Input() label = 'Figura estadística'; @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; From 69afcc7fdbc35028cfa73e707ee7392bd1095ca5 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 14 Oct 2026 11:46:17 -0600 Subject: [PATCH 17/51] feat(ui): mejorar periodos KPI y presentacion del dashboard --- .../indicador-catalog-card.spec.ts | 24 +- .../indicadores/indicador-catalog-card.ts | 66 +--- .../indicadores/indicador-figure-card.html | 42 +-- .../indicadores/indicador-figure-card.scss | 14 +- .../indicadores/indicador-figure-card.spec.ts | 95 +++-- .../indicadores/indicador-figure-card.ts | 9 +- .../indicadores/indicador-figure-panel.ts | 28 +- .../indicadores/indicador-kpi-panel.spec.ts | 1 + .../indicadores/indicador-kpi-panel.ts | 27 +- .../indicadores/indicador-period-filters.html | 17 +- .../indicadores/indicador-period-filters.ts | 13 +- .../indicadores-global-filters.spec.ts | 33 +- .../indicadores/indicadores-memory.spec.ts | 14 +- .../indicadores/indicadores-memory.ts | 8 - .../indicadores-navigation.spec.ts | 12 +- .../indicadores/indicadores-page.html | 9 +- .../indicadores/indicadores-page.spec.ts | 138 +++---- .../features/indicadores/indicadores-page.ts | 95 ++--- .../indicadores-periodos-integration.spec.ts | 121 ++++++ .../indicadores/indicadores-periodos.spec.ts | 83 ++++ .../indicadores-periodos.testing.ts | 18 + .../indicadores/indicadores-periodos.ts | 77 ++++ .../indicadores/indicadores-pinning.spec.ts | 27 +- .../indicadores-plotly-lifecycle.spec.ts | 11 +- .../indicadores/indicadores-search.spec.ts | 46 +-- .../indicadores-visibility.spec.ts | 354 ++++++------------ 26 files changed, 778 insertions(+), 604 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-periodos-integration.spec.ts create mode 100644 src/app/features/indicadores/indicadores-periodos.spec.ts create mode 100644 src/app/features/indicadores/indicadores-periodos.testing.ts create mode 100644 src/app/features/indicadores/indicadores-periodos.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index 6ac8bd9..0327366 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -16,11 +16,12 @@ describe('UX-06E.D.2.1 selector de representación', () => { let http: HttpTestingController; const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 }; beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); create(['f', 'g']); }); - afterEach(() => { fixture.destroy(); http.verify(); }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function create(figuras: string[], domain = 'cacu') { fixture = TestBed.createComponent(IndicadorCatalogCard); fixture.componentRef.setInput('dominio', domain); @@ -28,9 +29,9 @@ describe('UX-06E.D.2.1 selector de representación', () => { 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)); } + 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.toggle(); fixture.detectChanges(); } + function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } 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); @@ -45,20 +46,21 @@ describe('UX-06E.D.2.1 selector de representación', () => { request('f').flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges(); expect(panels()[0].componentInstance.result().figure.data[0].y).toEqual([7]); http.expectNone(() => true); }); - it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva apertura diferida', () => { + it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva carga diferida', () => { open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g']); - expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.awaitingFigures).toBe(true); http.expectNone(() => true); - fixture.componentInstance.activateVisible(); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); + expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.visible).toBe(false); http.expectNone(() => true); + fixture.componentInstance.setVisible(true); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g'], 'cama'); expect(fixture.componentInstance.selectedFigure).toBe('f'); fixture.destroy(); create(['f']); expect(fixture.componentInstance.selectedFigure).toBe('f'); }); - it('cambio de aplicado conserva elección y consulta sólo su representación; cierre manual prevalece', () => { + it('cambio de aplicado conserva elección y consulta sólo su representación; fuera de vista cancela revisión obsoleta', () => { open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); fixture.detectChanges(); const current = request('g'); expect(current.request.params.get('periodos')).toBe('2025-S2'); http.expectNone(r => r.url.endsWith('/figuras/f')); - fixture.componentInstance.toggle(); fixture.detectChanges(); expect(current.cancelled).toBe(true); - fixture.componentInstance.activateVisible(); fixture.detectChanges(); expect(panels()).toHaveLength(0); http.expectNone(() => true); + fixture.componentInstance.setVisible(false); fixture.detectChanges(); + fixture.componentRef.setInput('applied', { ...applied, revision: 3 }); fixture.detectChanges(); expect(current.cancelled).toBe(true); + expect(panels()).toHaveLength(0); http.expectNone(() => true); }); it('opciones ajenas al catálogo y selección repetida no consultan', () => { open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('bad'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); @@ -66,7 +68,7 @@ describe('UX-06E.D.2.1 selector de representación', () => { }); }); -it('C2 sin magnitudes mantiene nota de supresión del servicio fuera del host Plotly y no cambia trazas', () => { +it('C2 sin magnitudes elimina la copia HTML de la nota y no cambia trazas Plotly', () => { TestBed.configureTestingModule({ imports: [IndicadorFigureCard] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); const fixture = TestBed.createComponent(IndicadorFigureCard); @@ -74,7 +76,7 @@ it('C2 sin magnitudes mantiene nota de supresión del servicio fuera del host Pl fixture.componentRef.setInput('state', { status: 'ready', figure, presentationFigure: structuredClone(figure) }); fixture.componentRef.setInput('selected', { id: 'i', titulo: 'I', contrato: 'C2', figuras: ['fig_c2_donas'], tipos_periodo: ['semestre'] }); fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]').textContent).toContain('Valores ocultos por supresión.'); + expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]')).toBeNull(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(fixture.nativeElement.textContent).toContain('Los sectores'); expect(figure.data[0].values).toEqual([null, null]); fixture.destroy(); }); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 7da0e6f..4fc63e5 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -1,4 +1,3 @@ -import { DOCUMENT } from '@angular/common'; import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, output, ViewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; @@ -6,7 +5,7 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; import { MatIconModule } from '@angular/material/icon'; import { Dominio, Indicador, Tema } from './indicadores.models'; -import { CardActivation, GlobalApplied, IndicadoresMemory } from './indicadores-memory'; +import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; import { IndicadorFigurePanel } from './indicador-figure-panel'; @@ -15,26 +14,20 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel], template: ` -
+

{{ indicador.titulo }}

{{ indicador.id }}

-
-
- @if (awaitingFigures) { - - } @else if (expanded && figuresActivated) { - - @if (selectedFigure) { +
+ + @if (selectedFigure) { Representación gráfica {{ figure }} } +
@for (figure of [selectedFigure]; track panelIdentity(figure)) { - + } - } @else {

El indicador no tiene figuras disponibles.

} - } +
+ } @else {

El indicador no tiene figuras disponibles.

}
`, @@ -54,12 +48,12 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; :host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } mat-card { padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } - header { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: start; gap: var(--issste-space-3); } + header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); } + .graphic-region { min-height: 620px; } .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; } .indicator-id { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } - header button { justify-self: end; flex-shrink: 0; min-width: 48px; min-height: 48px; color: var(--issste-text); } .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; } @@ -77,20 +71,12 @@ export class IndicadorCatalogCard implements OnChanges { @Input({ required: true }) applied!: GlobalApplied; @Input() pinned = false; readonly pinChanged = output(); - @ViewChild('visibilityHeader', { static: true }) visibilityHeader!: ElementRef; + @ViewChild('visibilityRegion') visibilityRegion?: ElementRef; readonly host = inject>(ElementRef); - readonly activationChanged = output(); - @ViewChild('toggleButton', { read: ElementRef }) toggleButton!: ElementRef; - @ViewChild('content') content!: ElementRef; private readonly changeDetector = inject(ChangeDetectorRef); private readonly memory = inject(IndicadoresMemory); - private readonly document = inject(DOCUMENT); private identity = ''; - private state: CardActivation = 'pending'; - figuresActivated = false; - get expanded() { return this.state === 'auto-open' || this.state === 'manual-open'; } - get awaitingFigures() { return this.expanded && !this.figuresActivated; } - get awaitingVisibility() { return this.state === 'pending' || this.awaitingFigures; } + visible = false; titleId = ''; contentId = ''; panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); } @@ -110,29 +96,11 @@ export class IndicadorCatalogCard implements OnChanges { const id = identityElementId(identity); this.titleId = id + '-title'; this.contentId = id + '-content'; - this.state = this.memory.activation(this.dominio, this.indicador.id); - this.figuresActivated = false; + this.visible = false; } - activateVisible() { - // Recheck the decision at commit time, including manual changes after observation. - if (!this.awaitingVisibility) return; - if (this.state === 'pending') { - this.state = 'auto-open'; - this.memory.rememberActivation(this.dominio, this.indicador.id, this.state); - } - this.figuresActivated = true; - this.changeDetector.markForCheck(); - } - toggle() { - if (this.expanded && !this.awaitingFigures && this.content.nativeElement.contains(this.document.activeElement)) { - this.toggleButton.nativeElement.focus(); - } - // A restored open preference first shows its figures; the next click closes. - const opening = !this.expanded || this.awaitingFigures; - this.state = opening ? 'manual-open' : 'manual-closed'; - this.figuresActivated = opening; - this.memory.rememberActivation(this.dominio, this.indicador.id, this.state); - this.activationChanged.emit(); + setVisible(visible: boolean) { + if (this.visible === visible) return; + this.visible = visible; this.changeDetector.markForCheck(); } } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index 51d2a46..e295488 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -1,28 +1,26 @@ @if (selected) { -
-

Cómo leer esta figura · {{ selected?.contrato }}

-
    - @for (line of visibleInterpretation; track $index) {
  • {{ line }}
  • } -
- @if (methodologyDetail.length) { - -
- @for (line of methodologyDetail; track $index) {

{{ line }}

} -
- } -

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
+ +
+
    + @for (line of interpretation; track $index) {
  • {{ line }}
  • } +
+

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
} @if (state.status === 'loading') { -

Cargando figura…

+

Cargando figura…

+ } @else if (state.status === 'deferred') { +

{{ state.message }}

} @else if (state.status === 'incompatible') {

Filtro general incompatible con esta figura.

{{ state.message }}

} @else if (state.status === 'error') { @@ -32,12 +30,6 @@ @if (hasNoVisibleValues(figure)) {

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

} - @if (serviceNotes.length) { -
-

Notas de la figura

- @for (note of serviceNotes; track $index) {

} -
- }

Figura: {{ figuraId }}

} @else { diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index 0faff13..ac364c4 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -1,19 +1,20 @@ :host { display: block; min-width: 0; } .interpretation { - padding: var(--issste-space-4); margin-bottom: var(--issste-space-4); - border-left: 3px solid var(--issste-accent); color: var(--issste-text); font-family: var(--issste-font-body); line-height: 1.5; overflow-wrap: anywhere; } -.interpretation h2 { margin: 0 0 .5rem; font-family: var(--issste-font-heading); font-size: 1.125rem; } +.methodology-detail { + margin-top: var(--issste-space-3); + padding: var(--issste-space-4); + border-left: 3px solid var(--issste-accent); +} .interpretation ul { margin: 0; padding-left: 1.25rem; } .interpretation li + li { margin-top: .25rem; } .period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); } .methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; } -.methodology-detail { margin-top: var(--issste-space-3); } .methodology-detail p { margin: 0; } .methodology-detail p + p { margin-top: var(--issste-space-2); } .methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } @@ -22,8 +23,11 @@ .state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; } .dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } .figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; } -@media (max-width: 550px) { .interpretation { padding: var(--issste-space-3); } } +@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } + +.figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } +.skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 5a80856..80640b2 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -130,53 +130,70 @@ describe('IndicadorFigureCard', () => { expect(purge).toHaveBeenCalledWith(firstHost); expect(purge).toHaveBeenCalledTimes(1); expect(disconnect).toHaveBeenCalledTimes(1); }); - it('UX-06E.B1 integra composición y detalle complementario local C2 y mantiene advertencias visibles', () => { + it('UX-06E.P0.2 inicia cerrado y despliega toda la explicación con estado accesible', () => { fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); state({ status: 'idle' }); const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; - expect(section.querySelector('ul')?.textContent).not.toContain('Las barras muestran la composición porcentual'); + expect(section.textContent).toContain('Cómo leer'); + expect(section.querySelector('h2')).toBeNull(); + expect(section.classList.contains('expanded')).toBe(false); + expect(section.querySelector('.methodology-detail ul')).not.toBeNull(); + expect(section.querySelector('ul')?.closest('[hidden]')).not.toBeNull(); expect(section.querySelectorAll('button')).toHaveLength(1); expect(section.querySelectorAll('[hidden]')).toHaveLength(1); - expect(section.querySelector('ul')?.textContent).toContain('SIN_DATO'); - expect(section.querySelector('ul')?.textContent).toContain('suprimidos no representan tasas'); - expect(section.querySelector('.period-note')?.textContent).toContain('no permite determinar la disponibilidad'); const button = section.querySelector('button')!; const detail = section.querySelector('[id]') as HTMLElement; expect(button.getAttribute('aria-expanded')).toBe('false'); expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); - expect([...detail.querySelectorAll('p')].map(p => p.textContent)).toEqual([ - 'Las barras muestran la composición porcentual de cada grupo y periodo.', - 'Las categorías corresponden a la distribución de cada grupo y periodo.', - ]); - expect([...section.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.visibleInterpretation); + expect(button.tagName).toBe('BUTTON'); + expect(button.nextElementSibling?.classList.contains('methodology-detail')).toBe(true); + button.focus(); + expect(document.activeElement).toBe(button); + expect(detail.textContent).toContain('SIN_DATO'); + expect(detail.textContent).toContain('suprimidos no representan tasas'); + expect(detail.textContent).toContain('no permite determinar la disponibilidad'); + expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation); button.click(); fixture.detectChanges(); expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true'); state({ status: 'loading' }); expect(detail.hidden).toBe(false); button.click(); fixture.detectChanges(); expect(detail.hidden).toBe(true); + expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail); }); - it.each(['fig_c3r_cajas', 'desconocida'])('UX-06D mantiene íntegra la interpretación %s sin separación insegura', figura => { + it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => { + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; + button.click(); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('composición porcentual'); + fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1'); + expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls')) + .toBe(fixture.nativeElement.querySelector('.methodology-detail').id); + }); + it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => { fixture.componentRef.setInput('figuraId', figura); if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' }); state({ status: 'idle' }); - expect(fixture.nativeElement.querySelector('.methodology-toggle')).toBeNull(); - expect([...fixture.nativeElement.querySelectorAll('.interpretation li')].map((li: any) => li.textContent)) + expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); + expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((li: any) => li.textContent)) .toEqual(fixture.componentInstance.interpretation); }); - it.each(['cacu', 'cama'])('UX-06E.B1 conserva advertencias C2 de %s y pliega solo composición', dominio => { + it.each(['cacu', 'cama'])('UX-06E.P0.2 conserva advertencias C2 de %s en ayuda cerrada', dominio => { fixture.componentRef.setInput('dominio', dominio); fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement; expect(detail.hidden).toBe(true); - expect([...detail.querySelectorAll('p')].map(p => p.textContent)).toEqual(['Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.']); - expect(fixture.nativeElement.querySelector('.interpretation > ul').textContent).toContain('SIN_DATO'); - expect(fixture.nativeElement.querySelector('.interpretation > ul').textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); + expect(detail.textContent).toContain('Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.'); + expect(detail.textContent).toContain('SIN_DATO'); + expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); }); - it('UX-06D conserva completas todas las anotaciones, sin clasificar ni plegar notas del backend', async () => { + it('UX-06E.P0.2 quita el panel redundante y preserva todas las anotaciones en Plotly', async () => { const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [ { text: 'Denominador pequeño
Intervalos no disponibles' }, { text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' }, @@ -184,12 +201,26 @@ describe('IndicadorFigureCard', () => { ] }, frames: [] }; const snapshot = JSON.stringify(figure); ready(figure); await settle(); - const notes = fixture.nativeElement.querySelector('.notes') as HTMLElement; - expect(notes.closest('[hidden]')).toBeNull(); - expect([...notes.querySelectorAll('p')].map(p => p.innerHTML)).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']); + expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); expect(JSON.stringify(figure)).toBe(snapshot); expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0'); }); + it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => { + fixture.componentRef.setInput('tema', tema); + const annotation = 'Advertencia metodológica única de la figura.'; + const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } }; + ready(original); await settle(); + const card = fixture.nativeElement.querySelector('.figure-card'); + expect(card.classList.contains('dark')).toBe(tema === 'oscuro'); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain(annotation); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.notes).toEqual([annotation]); + expect(JSON.stringify(original)).toContain(annotation); + }); it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => { fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' }); fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); @@ -219,8 +250,8 @@ describe('IndicadorFigureCard', () => { 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 = section.querySelector('ul')!; - expect(warnings.closest('[hidden]')).toBeNull(); + const warnings = detail.querySelector('ul')!; + expect(warnings.closest('[hidden]')).not.toBeNull(); expect(warnings.textContent).toContain('100 % no implica certeza poblacional'); expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); if (dominio === 'tea') { @@ -228,8 +259,7 @@ describe('IndicadorFigureCard', () => { expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan'); expect(warnings.textContent).toContain('denominadores pequeños'); } else expect(warnings.textContent).toContain('no entregan intervalos Wilson efectivos'); - expect([...detail.querySelectorAll('p')].map(p => p.textContent)).toEqual([fixture.componentInstance.interpretation[0]]); - expect([...detail.querySelectorAll('p'), ...warnings.querySelectorAll('li')].map(p => p.textContent)) + expect([...warnings.querySelectorAll('li')].map(p => p.textContent)) .toEqual(fixture.componentInstance.interpretation); button.focus(); button.click(); fixture.detectChanges(); expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false); @@ -237,31 +267,30 @@ describe('IndicadorFigureCard', () => { button.click(); fixture.detectChanges(); expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true); }); - it('UX-06E.B1 mantiene la oración mixta C3r y todos sus límites visibles', () => { + it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => { fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' }); const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; - expect(section.querySelector('[hidden]')).toBeNull(); - expect(section.querySelector('button')).toBeNull(); - expect([...section.querySelectorAll('li')].map(p => p.textContent)).toEqual([ + expect(section.querySelector('[hidden]')).not.toBeNull(); + expect(section.querySelector('button')).not.toBeNull(); + expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([ 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', 'Los límites de dibujo no representan necesariamente extremos observados.', 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', 'Los puntos suprimidos no representan tasas observadas de 0 %.', ]); }); - it('UX-06E.B1 al alternar ayuda conserva Plotly, JSON, notas y observadores sin react ni purge', async () => { + it('UX-06E.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => { const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } }; const copy = ready(original); await settle(); const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy); const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance; - const host = fixture.nativeElement.querySelector('.plot'), notes = fixture.nativeElement.querySelector('.notes'); + const host = fixture.nativeElement.querySelector('.plot'); const button = fixture.nativeElement.querySelector('.methodology-toggle'); const calls = react.mock.calls.length, observers = observe.mock.calls.length; for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); } expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); expect(fixture.nativeElement.querySelector('.plot')).toBe(host); - expect(fixture.nativeElement.querySelector('.notes')).toBe(notes); - expect(notes.closest('[hidden]')).toBeNull(); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers); expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 3f71dfc..b5eb099 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -10,7 +10,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; // The panel owns requests; the card receives the original and its presentation copy. export interface FigureState { - status: 'idle' | 'loading' | 'ready' | 'error' | 'incompatible'; + status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; message?: string; @@ -35,7 +35,7 @@ const CONTRACT_INTERPRETATIONS: Readonly> = { 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', ], }; -const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.']; +const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.']; @Component({ selector: 'app-indicador-figure-card', @@ -81,11 +81,6 @@ export class IndicadorFigureCard { get visibleInterpretation(): readonly string[] { return this.interpretation.slice(this.complementaryLineCount); } - get serviceNotes(): string[] { - const annotations = this.state.figure?.layout['annotations']; - return Array.isArray(annotations) ? annotations.flatMap(note => - note && typeof note.text === 'string' ? [note.text] : []) : []; - } readonly hasNoVisibleValues = hasNoVisibleValues; readonly figureTitle = figureTitle; diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 338482c..b605e7b 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -1,4 +1,4 @@ -import { Component, DestroyRef, inject, Input, OnChanges, signal, SimpleChanges } from '@angular/core'; +import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; @@ -37,6 +37,7 @@ export class IndicadorFigurePanel implements OnChanges { @Input({ required: true }) figuraId!: string; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>(); @@ -62,16 +63,31 @@ export class IndicadorFigurePanel implements OnChanges { if (generation === this.generation && revision === this.applied?.revision) this.result.set(state); }); } - ngOnChanges(changes: SimpleChanges) { + ngOnChanges() { const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); this.titleId = identityElementId(identity) + '-title'; - const key = JSON.stringify([identity, this.tema, this.applied?.revision, this.applied && selectionKey(this.applied)]); - if (key !== this.currentKey || changes['indicador']) { - this.currentKey = key; - this.requestFigure(); + const key = this.requestKey(); + if (key === this.currentKey) return; + if (this.visible) this.requestFigure(); + else { + // Cancel stale work immediately but retain the panel and its Plotly host. + const message = this.generation === 0 + ? 'Figura pendiente: se cargará al acercarse a esta región.' + : 'Actualización pendiente: se consultará al volver a esta región.'; + this.generation++; + this.figureRequests.next(null); + this.currentKey = ''; + this.result.set({ status: 'deferred', message }); } } + private requestKey() { + return JSON.stringify([figureIdentity(this.dominio, this.indicador.id, this.figuraId), + this.tema, this.applied?.revision, this.applied && selectionKey(this.applied), + this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId)]); + } requestFigure() { + if (!this.visible) return; + this.currentKey = this.requestKey(); const applied = this.applied; const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo); this.generation++; diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 0bad38d..8cb546a 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -20,6 +20,7 @@ describe('KPI integración con autoridad global', () => { function load(domain: Dominio, missing = false) { 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: [{ tipo: 'semestre', periodo: '2025-S1' }] }); fixture.detectChanges(); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); } diff --git a/src/app/features/indicadores/indicador-kpi-panel.ts b/src/app/features/indicadores/indicador-kpi-panel.ts index 6c7cc5b..ac78114 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.ts @@ -7,6 +7,7 @@ import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } fro import { IndicadoresService } from './indicadores.service'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi'; +import { PeriodAvailability, sortedPeriods } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; @Component({ @@ -22,32 +23,48 @@ export class IndicadorKpiPanel implements OnChanges { @Input({ required: true }) definition!: KpiDefinition; @Input() indicador?: Indicador; @Input() applied?: GlobalApplied; + @Input() availability?: PeriodAvailability; @Input() catalogPending = false; private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); private readonly requests = new Subject(); private key = ''; + readonly usedPeriod = signal(undefined); readonly result = signal({ state: 'Esperando catálogo' }); - get temporalReference() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'; } + get temporalReference() { return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'); } constructor() { this.requests.pipe(switchMap(() => { const applied = this.applied, definition = this.definition, domain = this.dominio; + this.usedPeriod.set(undefined); if (this.catalogPending) return of({ state: 'Esperando catálogo' }); if (!this.indicador) return of({ state: 'Indicador no publicado', info: 'No está disponible en el catálogo: ' + definition.id }); if (this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' }); const compatible = filterCompatibility(applied, this.indicador.tipos_periodo); if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' }); if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' }); - return defer(() => this.service.datos(domain, definition.id, applied.tipo, - applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined)).pipe( - map(data => ({ ...kpiResult(data, definition, domain, applied), notes: data.notas })), + let resolved = applied; + if (applied.selection.mode === 'todos') { + const availability = this.availability; + if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true }); + if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' }); + const periods = availability.byIndicator[definition.id]; + if (!periods) return of({ state: 'Error de disponibilidad' }); + const latest = sortedPeriods(periods.filter(p => p.tipo === applied.tipo).map(p => p.periodo))[0]; + if (!latest) return of({ state: 'Sin reportes disponibles' }); + resolved = { ...applied, selection: { mode: 'explicit', periodos: [latest] } }; + } + const periodos = resolved.selection.mode === 'explicit' ? resolved.selection.periodos : undefined; + this.usedPeriod.set(periodos?.[0]); + return defer(() => this.service.datos(domain, definition.id, applied.tipo, periodos)).pipe( + map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas })), catchError(error => of({ state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta', info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })), startWith({ state: 'Cargando…', loading: true })); }), takeUntilDestroyed(this.destroyRef)).subscribe(result => this.result.set(result)); } ngOnChanges() { - const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.catalogPending, this.applied && selectionKey(this.applied)]); + const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.catalogPending, this.applied && selectionKey(this.applied), + this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]); if (key === this.key) return; this.key = key; this.requests.next(); diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html index 2341c9f..5aa1025 100644 --- a/src/app/features/indicadores/indicador-period-filters.html +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -22,13 +22,24 @@ Periodos seleccionados {{ selectedPeriods.join(', ') }} - @for (period of entry.added; track period) { {{ period }} } + @for (period of options; track period) { {{ period }} } + @if (availability) { + @for (period of unavailableSelection; track period) { {{ period }} — disponibilidad no confirmada } + } - Disponibilidad desconocida hasta consultar. + {{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }} }
-@if (entry.draft.mode !== 'todos') { +@if (availability) { + @if (availability.status === 'loading') {

Consultando periodos disponibles…

} + @else if (availability.status === 'error') { +

No se pudo completar la consulta de periodos disponibles.

+ + } @else if (!options.length) {

Sin reportes disponibles para esta granularidad.

} + @if (entry.draft.mode === 'explicit' && unavailableSelection.length) {

La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.

} +} +@if (!availability && entry.draft.mode !== 'todos') {

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

Año diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts index e05d478..1dd7369 100644 --- a/src/app/features/indicadores/indicador-period-filters.ts +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -5,6 +5,7 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { parsePeriodos, TipoPeriodo } from './indicadores.models'; +import { PeriodAvailability } from './indicadores-periodos'; import { describePeriods, newEditor, FilterState, pending, validDraft } from './indicadores-memory'; @Component({ @@ -16,6 +17,8 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './ export class IndicadorPeriodFilters implements OnChanges { @Input({ required: true }) state!: FilterState; @Input({ required: true }) types!: TipoPeriodo[]; + @Input() availability?: PeriodAvailability; + @Output() retryAvailability = new EventEmitter(); @Output() edited = new EventEmitter(); @Output() apply = new EventEmitter(); year = ''; @@ -28,7 +31,13 @@ export class IndicadorPeriodFilters implements OnChanges { // Keep the empty multiple-select value 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 canApply() { return validDraft(this.entry.draft, this.state.tipo, this.types); } + get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; } + get unavailableSelection() { return this.selectedPeriods.filter(p => !this.options.includes(p)); } + get canApply() { + return validDraft(this.entry.draft, this.state.tipo, this.types) + && (!this.availability || this.entry.draft.mode === 'todos' + || (this.availability.status === 'ready' && !this.unavailableSelection.length)); + } 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'; } @@ -47,7 +56,7 @@ export class IndicadorPeriodFilters implements OnChanges { } select(values: string[]) { const unique = [...new Set(values)]; - if (unique.some(p => !this.entry.added.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) 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(); } diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts index 18b18ff..b73cbf3 100644 --- a/src/app/features/indicadores/indicadores-global-filters.spec.ts +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -21,18 +22,19 @@ describe('D.2 integración de autoridad global y consumidores', () => { let page: IndicadoresPage; let http: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); }); - afterEach(() => { fixture.destroy(); http.verify(); }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function load(items = [item('a'), item('b')], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } - function open(index = 0) { cards()[index].toggle(); fixture.detectChanges(); } + function open(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); } function draft(tipo: TipoPeriodo, periods: string[]) { @@ -62,7 +64,7 @@ describe('D.2 integración de autoridad global y consumidores', () => { it('aplicar actualiza todas las activadas sin abrir pendientes ni KPI', () => { load([item('a'), item('b'), item('c')]); open(0); open(1); respond(); const before = cards(); draft('semestre', ['2025-S1']); apply(); - expect(cards()).toEqual(before); expect(cards()[2].expanded).toBe(false); + expect(cards()).toEqual(before); expect(cards()[2].visible).toBe(false); const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2); for (const r of requests) { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); } expect(page.filters!.applied.revision).toBe(1); expect(panels().every(p => p.applied === page.filters!.applied)).toBe(true); @@ -77,20 +79,21 @@ describe('D.2 integración de autoridad global y consumidores', () => { }); it('tarjeta activada después recibe el último aplicado y solo su primera consulta', () => { load(); draft('semestre', ['2025-S2']); apply(); http.expectNone(() => true); - cards()[1].activateVisible(); fixture.detectChanges(); + cards()[1].setVisible(true); fixture.detectChanges(); const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} }); - cards()[1].activateVisible(); fixture.detectChanges(); http.expectNone(() => true); + cards()[1].setVisible(true); fixture.detectChanges(); http.expectNone(() => true); }); - it('cierre manual queda protegido al aplicar y reabrir usa aplicado vigente', () => { - load(); open(); respond(); open(); draft('semestre', ['2025-S1']); apply(); - cards()[0].activateVisible(); fixture.detectChanges(); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + it('fuera del viewport difiere aplicado y al volver usa revisión vigente', () => { + load(); open(); respond(); const panel = panels()[0]; + cards()[0].setVisible(false); fixture.detectChanges(); draft('semestre', ['2025-S1']); apply(); + expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); expect(panel.result().status).toBe('deferred'); http.expectNone(() => true); open(); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); }); it('restaurada abierta espera visibilidad y usa revisión vigente al activarse', () => { load(); open(); respond(); page.changeDominio('cacu'); load(undefined, 'cacu'); page.changeDominio('tea'); load(); - expect(cards()[0].awaitingFigures).toBe(true); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true); - cards()[0].activateVisible(); fixture.detectChanges(); + expect(cards()[0].visible).toBe(false); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true); + cards()[0].setVisible(true); fixture.detectChanges(); expect(panels()[0].applied.revision).toBe(1); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); }); it('mensual compartido consulta compatibles y retira resultado anterior del incompatible', () => { @@ -132,13 +135,13 @@ describe('D.2 integración de autoridad global y consumidores', () => { expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos'); draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load(); expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); - expect(cards()[0].awaitingFigures).toBe(true); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); http.expectNone(() => true); }); it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => { load(); draft('mes', ['2025-01']); apply(); open(); respond(); page.retryCatalog(); fixture.detectChanges(); load([item('a', ['semestre'])]); expect(page.filters!.applied.tipo).toBe('mes'); expect(page.filters!.applied.revision).toBe(1); - cards()[0].activateVisible(); fixture.detectChanges(); + cards()[0].setVisible(true); fixture.detectChanges(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); editor().changeTipo('semestre'); apply(); request('a').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2); diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts index b1b0826..8ef623b 100644 --- a/src/app/features/indicadores/indicadores-memory.spec.ts +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -25,22 +25,20 @@ describe('D.2 memoria global por dominio', () => { applyGlobal(state, ['semestre']); memory.saveGlobal('tea', state); for (const domain of ['cacu', 'cama'] as const) expect(memory.restoreGlobal(domain, ['semestre']).applied.selection.mode).toBe('todos'); }); - it('mantiene activación por dominio e indicador y tema independiente', () => { - expect(memory.activation('tea', 'i')).toBe('pending'); - memory.rememberActivation('tea', 'i', 'manual-closed'); memory.rememberActivation('cacu', 'i', 'auto-open'); - expect(memory.activation('tea', 'i')).toBe('manual-closed'); expect(memory.activation('cacu', 'i')).toBe('auto-open'); - expect(memory.activation('tea', 'otro')).toBe('pending'); - memory.rememberActivation('cama', 'i', 'manual-open'); expect(memory.activation('cama', 'i')).toBe('manual-open'); + it('mantiene figura por dominio e indicador y tema independiente', () => { + memory.rememberFigure('tea', 'i', 'f'); memory.rememberFigure('cacu', 'i', 'g'); + expect(memory.figure('tea', 'i')).toBe('f'); expect(memory.figure('cacu', 'i')).toBe('g'); + expect(memory.figure('cama', 'i')).toBeUndefined(); memory.rememberTheme('cacu', 'oscuro'); expect(memory.theme('cacu')).toBe('oscuro'); expect(memory.theme('tea')).toBe('claro'); }); it('nueva instancia reinicia memoria sin almacenamiento persistente', () => { const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem'); - memory.rememberTheme('tea', 'oscuro'); memory.rememberActivation('tea', 'i', 'manual-closed'); + memory.rememberTheme('tea', 'oscuro'); const saved = memory.restoreGlobal('tea', ['semestre', 'mes']); saved.tipo = 'mes'; saved.editors.mes!.draft = { mode: 'explicit', periodos: ['2025-01'] }; applyGlobal(saved, ['semestre', 'mes']); memory.saveGlobal('tea', saved); const fresh = new IndicadoresMemory(); - expect(fresh.theme('tea')).toBe('claro'); expect(fresh.activation('tea', 'i')).toBe('pending'); + expect(fresh.theme('tea')).toBe('claro'); expect(fresh.restoreGlobal('tea', ['semestre']).applied.revision).toBe(0); expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); read.mockRestore(); write.mockRestore(); }); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index 97c58ae..a63dc8c 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -59,7 +59,6 @@ export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boo state.applied = { tipo: state.tipo, selection: structuredClone(draft), revision: state.applied.revision + 1 }; return true; } -export type CardActivation = 'pending' | 'auto-open' | 'manual-open' | 'manual-closed'; @Injectable({ providedIn: 'root' }) export class IndicadoresMemory { @@ -81,16 +80,9 @@ export class IndicadoresMemory { rememberFigure(domain: Dominio, indicador: string, figure: string) { this.figures.set(JSON.stringify([domain, indicador]), figure); } - private readonly expansions = new Map(); private readonly filters = new Map(); theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; } rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); } - activation(domain: Dominio, indicador: string): CardActivation { - return this.expansions.get(JSON.stringify([domain, indicador])) ?? 'pending'; - } - rememberActivation(domain: Dominio, indicador: string, state: CardActivation) { - this.expansions.set(JSON.stringify([domain, indicador]), state); - } saveGlobal(domain: Dominio, state: GlobalFilterState) { this.filters.set(domain, structuredClone(state)); } diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index b158b38..82670bc 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -21,7 +22,8 @@ class ChartStub { figure?: PlotlyFigure; } describe('UX-04 navegación Angular', () => { let http: HttpTestingController; async function setup() { - TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); return RouterTestingHarness.create(); @@ -29,13 +31,15 @@ describe('UX-04 navegación Angular', () => { function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) { http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]); harness.detectChanges(); + const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; + vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; - if (!card.expanded || card.awaitingFigures) { card.toggle(); harness.detectChanges(); } + if (!card.visible) { card.setVisible(true); harness.detectChanges(); } const req = http.expectOne(r => r.url.includes('/figuras/')); req.flush({ data: [{ y: [0, null] }], layout: {} }); return req; } - afterEach(() => http.verify()); + afterEach(() => { http.verify(); vi.unstubAllGlobals(); }); it.each(['tea', 'cacu', 'cama'] as const)('navegación %s mantiene tres enlaces, estado, decoración y foco independiente', async domain => { const harness = await setup(); await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); @@ -97,7 +101,7 @@ describe('UX-04 navegación Angular', () => { const restarted = await harness.navigateByUrl(url, IndicadoresPage); const req = load('cacu', harness); expect(TestBed.inject(Router).url).toBe('/indicadores/cacu'); - expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).expanded).toBe(true); + expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).visible).toBe(true); expect(restarted.tema).toBe('claro'); expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.tipo).toBe('semestre'); expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.mes?.draft.mode).toBe('empty'); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 7e1728d..5a68abb 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -14,20 +14,21 @@

Filtros generales de {{ domainLabels[dominio] }}

La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.

-
}

Indicadores destacados{{ dominio === 'tea' ? ' — Vista preliminar' : '' }}

-

{{ dominio === 'tea' ? 'Muestra visual de TEA. Las definiciones y fuentes de estos indicadores están pendientes.' : 'Valores del filtro general aplicado. Selecciona un único periodo para evitar consolidaciones sin una regla aprobada.' }}

+

{{ dominio === 'tea' ? 'Muestra visual de TEA. Las definiciones y fuentes de estos indicadores están pendientes.' : 'Todos con reporte muestra el último periodo disponible de cada indicador. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.' }}

@if (dominio === 'tea') { @for (preview of kpiPreviewsByDomain.tea; track preview.id) { } } @else { @for (definition of kpisByDomain[dominio]; track dominio + ':' + definition.id) { + [applied]="filters?.applied" [availability]="availability()" [catalogPending]="catalogLoading() || !!catalogError()" /> } }
@@ -74,7 +75,7 @@
@for (item of searchResults().items; track cardIdentity(item)) { + [pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> }
} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 7d053f0..4b0f265 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -20,23 +21,24 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; class ChartStub { figure?: PlotlyFigure; } const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] }; const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] }; -describe('UX-05B catálogo expandible', () => { +describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); }); - afterEach(() => { fixture.destroy(); http.verify(); }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function load(items: Indicador[] = [item, second], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } - function toggle(index = 0) { cards()[index].toggle(); fixture.detectChanges(); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } + function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } @@ -83,48 +85,23 @@ describe('UX-05B catálogo expandible', () => { toggle(0); toggle(1); flushAll(); expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]); expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']); - expect(cards()).toEqual(before); expect(cards().every(card => card.expanded)).toBe(true); + expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true); http.expectNone(() => true); }); - it('UX-06C: tarjeta contraída contiene solo identidad y flecha decorativa en un botón nativo', () => { - load(); - const host = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement; - const header = host.querySelector('header')!; - expect(header.querySelector('h2')?.textContent).toBe('Uno'); - expect(header.querySelector('.indicator-id')?.textContent).toBe('i1'); - expect(host.textContent).not.toContain('Contrato'); - expect(host.textContent).not.toContain('figuras publicadas'); - expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0); - const button = header.querySelector('button')!; - expect(button.type).toBe('button'); - expect(button.tabIndex).toBe(0); - expect(button.getAttribute('aria-expanded')).toBe('false'); - expect(button.getAttribute('aria-label')).toContain('Expandir tea · i1 · Uno'); - expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_more'); - expect(button.querySelector('mat-icon')?.getAttribute('aria-hidden')).toBe('true'); - http.expectNone(() => true); + it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => { + load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); + expect(host.querySelector('h2').textContent).toBe('Uno'); + expect(host.querySelector('header button')).toBeNull(); + expect(host.querySelector('mat-select')).toBeTruthy(); + expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); + expect(host.textContent).toContain('Contrato C1'); http.expectNone(() => true); }); - it('UX-06C: conserva encabezado, botón y relación accesible al abrir varias figuras y contraer', () => { - load(); - const host = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement; - const header = host.querySelector('header')!; - const button = header.querySelector('button')!; - const contentId = button.getAttribute('aria-controls')!; - button.click(); fixture.detectChanges(); flushAll(); - expect(host.querySelector('header')).toBe(header); - expect(header.querySelector('button')).toBe(button); - expect(button.getAttribute('aria-controls')).toBe(contentId); - expect(button.getAttribute('aria-expanded')).toBe('true'); - expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_less'); - expect(button.getAttribute('aria-label')).toContain('Contraer tea · i1 · Uno'); - expect(header.textContent).not.toContain('Contrato'); - expect(host.querySelector('.catalog-metadata')?.textContent).toContain('Contrato C1 · 2 figuras publicadas'); - expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(1); - button.click(); fixture.detectChanges(); - expect(host.querySelector('.catalog-metadata')).toBeNull(); - expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0); - expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_more'); - http.expectNone(() => true); + it('D.3.A conserva encabezado y contenido al salir del viewport', () => { + load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); + const header = host.querySelector('header'); toggle(); flushAll(); + const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges(); + expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel); + expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true); }); it('UX-06C: conserva título largo completo y el control separado de la identidad', () => { const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive'; @@ -132,8 +109,8 @@ describe('UX-05B catálogo expandible', () => { const header = fixture.nativeElement.querySelector('app-indicador-catalog-card header') as HTMLElement; expect(header.querySelector('h2')?.textContent).toBe(title); expect(header.querySelector('.card-identity button')).toBeNull(); - expect(header.lastElementChild?.tagName).toBe('BUTTON'); - expect(header.querySelector('button')?.getAttribute('aria-label')).toContain(title); + expect(header.querySelector('button')).toBeNull(); + expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title); http.expectNone(() => true); }); it('UX-06B conserva una navegación con rutas y estado activo en los tres dominios', () => { @@ -162,29 +139,29 @@ describe('UX-05B catálogo expandible', () => { expect(page.tema).toBe('claro'); page.changeTema('oscuro'); fixture.detectChanges(); expect(page.tema).toBe('oscuro'); - expect(cards().every(card => !card.expanded)).toBe(true); + expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true); }); it.each([0, 1, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i })); load(items); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); - expect(cards().every(c => !c.expanded)).toBe(true); + expect(cards().every(c => !c.visible)).toBe(true); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/')); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); - it('abrir manualmente consulta exactamente una vez la primera figura publicada', () => { - load([item]); toggle(); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(1); + it('activar visibilidad consulta exactamente una vez la primera figura publicada', () => { + load([item]); toggle(); expect(cards()[0].visible).toBe(true); expect(panels()).toHaveLength(1); request('f1').flush({ data: [], layout: {} }); fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true); }); - it('el cierre manual se conserva al volver sin consultar figuras', () => { - load([item]); toggle(); flushAll(); toggle(); - fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; - load([item]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + it('volver al dominio espera nueva visibilidad sin memoria de cierre', () => { + load([item]); toggle(); flushAll(); + fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + load([item]); expect(cards()[0].visible).toBe(false); http.expectNone(() => true); }); it('indicador sin figuras informa y no consulta HTTP', () => { - load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].expanded).toBe(true); + load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].visible).toBe(true); expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles'); expect(panels()).toHaveLength(0); http.expectNone(() => true); }); @@ -194,11 +171,12 @@ describe('UX-05B catálogo expandible', () => { c.flush({ data: [{ y: [3] }], layout: {} }); a.flush({ data: [{ y: [1] }], layout: {} }); expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [3]]); - expect(cards().every(c => c.expanded)).toBe(true); + expect(cards().every(c => c.visible)).toBe(true); }); - it('contraer cancela solo sus figuras, descarta respuestas y destruye paneles', () => { + it('retirar una tarjeta cancela solo su solicitud y destruye su panel', () => { load(); toggle(); toggle(1); const a = request('f1'), c = request('g'); - toggle(); expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false); + page.catalog.set([second]); fixture.detectChanges(); + expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false); expect(() => a.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); expect(panels()).toHaveLength(1); c.flush({ data: [{ y: [3] }], layout: {} }); expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]); @@ -242,16 +220,14 @@ describe('UX-05B catálogo expandible', () => { http.expectNone(() => true); } }); - it('cerrar y reabrir conserva borrador general y consulta aplicado en la figura seleccionada', () => { + it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => { load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); page.applyFilters(); fixture.detectChanges(); flushAll(); a.unit = 'S2'; a.add(); - toggle(); toggle(); - const restored = request('f1'); - expect(restored.request.params.get('periodos')).toBe('2025-S1'); + cards()[0].setVisible(false); fixture.detectChanges(); toggle(); expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); - restored.flush({ data: [], layout: {} }); + http.expectNone(() => true); }); - it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => { + it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => { load(); toggle(); const a = request('f1'); page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true); const darkA = request('f1'); @@ -267,17 +243,17 @@ describe('UX-05B catálogo expandible', () => { expect(oldCatalog.cancelled).toBe(true); load(syntheticCatalogs.cama, 'cama'); flushAll(); expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama'); }); - it('restaura expansión y tema de dominio sin aplicar borrador pendiente', () => { + it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => { load(); toggle(); flushAll(); control().changeMode('manual'); page.changeTema('oscuro'); fixture.detectChanges(); flushAll(); page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll(); toggle(); page.changeDominio('tea'); fixture.detectChanges(); load(); - expect(cards()[0].expanded).toBe(true); expect(cards()[1].expanded).toBe(false); - expect(page.tema).toBe('oscuro'); expect(cards()[0].awaitingFigures).toBe(true); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); expect(cards()[1].visible).toBe(false); + expect(page.tema).toBe('oscuro'); expect(cards()[0].visible).toBe(false); http.expectNone(() => true); toggle(); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false); expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); - expect(cards()[0].expanded).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); }); it('identidades estables conservan componentes al reordenar el catálogo', () => { load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0]; @@ -285,22 +261,16 @@ describe('UX-05B catálogo expandible', () => { expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true); }); it('identidad eliminada no se monta aunque exista preferencia anterior', () => { - TestBed.inject(IndicadoresMemory).rememberActivation('tea', 'removed', 'manual-open'); + TestBed.inject(IndicadoresMemory).rememberFigure('tea', 'removed', 'f1'); load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll(); }); - it('botones semánticos anuncian expansión, IDs únicos y devuelven foco al contraer contenido', () => { - load(); - const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf; - expect(buttons[0].tagName).toBe('BUTTON'); expect(buttons[0].getAttribute('aria-expanded')).toBe('false'); - buttons[0].click(); fixture.detectChanges(); flushAll(); - expect(buttons[0].getAttribute('aria-expanded')).toBe('true'); - expect(document.getElementById(buttons[0].getAttribute('aria-controls')!)).toBeTruthy(); - const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle') as HTMLElement; - input.focus(); expect(document.activeElement).toBe(input); cards()[0].toggle(); fixture.detectChanges(); - expect(document.activeElement).toBe(buttons[0]); + it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => { + load(); toggle(); flushAll(); + const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle'); + input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input); const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf).map(e => e.id); expect(new Set(ids).size).toBe(ids.length); - expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); + expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); }); it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => { load(); toggle(0); toggle(1); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } }; @@ -354,9 +324,9 @@ describe('UX-05B catálogo expandible', () => { const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1')); const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1')); a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges(); - const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf; - expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); - expect(buttons[0].tabIndex).toBe(0); expect(buttons[1].tabIndex).toBe(0); + const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf; + expect(panels()[0].titleId).not.toBe(panels()[1].titleId); + expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1); expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]); }); }); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index b83eb0c..3375ef2 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -20,6 +20,7 @@ import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { indicatorIdentity } from './indicadores-identities'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; @Component({ @@ -34,7 +35,7 @@ export class IndicadoresPage { private readonly injector = inject(Injector); private readonly searchInput = viewChild>('searchInput'); private readonly graphicCards = viewChildren(IndicadorCatalogCard); - private readonly observedHeaders = new Map(); + private readonly observedRegions = new Map(); private renderedCards: readonly IndicadorCatalogCard[] = []; private visibilityObserver?: IntersectionObserver; private sizeObserver?: ResizeObserver; @@ -42,11 +43,9 @@ export class IndicadoresPage { private frame?: number; private stickyHeight = -1; private visibilityDestroyed = false; - private confirmation?: { cards: IndicadorCatalogCard[]; trigger: IndicadorCatalogCard; top: number; left: number; width: number; height: number; viewportWidth: number; viewportHeight: number }; private readonly viewportChanged = () => this.visibilityChanged(); visibilityChanged() { - this.confirmation = undefined; this.queueVisibility(); } private queueVisibility() { @@ -60,31 +59,34 @@ export class IndicadoresPage { private clearVisibility() { this.visibilityObserver?.disconnect(); this.visibilityObserver = undefined; - this.observedHeaders.clear(); + this.observedRegions.clear(); this.renderedCards = []; - this.confirmation = undefined; if (this.frame !== undefined) this.document.defaultView?.cancelAnimationFrame(this.frame); this.frame = undefined; } private syncVisibility() { - if (this.visibilityDestroyed || typeof IntersectionObserver === 'undefined' || !this.document.defaultView) return; + if (this.visibilityDestroyed || !this.document.defaultView) return; const cards = this.graphicCards(); + if (typeof IntersectionObserver === 'undefined') { + for (const card of cards) card.setVisible(true); + return; + } const orderChanged = cards.length !== this.renderedCards.length || cards.some((card, i) => card !== this.renderedCards[i]); this.renderedCards = [...cards]; this.refreshVisibilityObserver(); let changed = orderChanged; - for (const [header, card] of this.observedHeaders) { - if (!cards.includes(card) || !card.awaitingVisibility) { - this.visibilityObserver?.unobserve(header); - this.observedHeaders.delete(header); + for (const [region, card] of this.observedRegions) { + if (!cards.includes(card) || card.visibilityRegion?.nativeElement !== region) { + this.visibilityObserver?.unobserve(region); + this.observedRegions.delete(region); changed = true; } } for (const card of cards) { - const header = card.visibilityHeader.nativeElement; - if (card.awaitingVisibility && !this.observedHeaders.has(header)) { - this.observedHeaders.set(header, card); - this.visibilityObserver?.observe(header); + const region = card.visibilityRegion?.nativeElement; + if (region && !this.observedRegions.has(region)) { + this.observedRegions.set(region, card); + this.visibilityObserver?.observe(region); changed = true; } } @@ -106,58 +108,29 @@ export class IndicadoresPage { if (this.visibilityObserver && Math.abs(height - this.stickyHeight) < 1) return; this.stickyHeight = height; this.visibilityObserver?.disconnect(); - this.confirmation = undefined; const observer = new IntersectionObserver(entries => { // Callbacks from a replaced observer or retired target cannot authorize activation. if (this.visibilityDestroyed || this.visibilityObserver !== observer) return; - if (entries.some(entry => this.observedHeaders.has(entry.target))) this.queueVisibility(); - }, { root: null, rootMargin: `-${height}px 0px 0px 0px`, threshold: 0.25 }); + if (entries.some(entry => this.observedRegions.has(entry.target))) this.queueVisibility(); + }, { root: null, rootMargin: `-${height}px 0px 200px 0px`, threshold: 0 }); this.visibilityObserver = observer; - for (const header of this.observedHeaders.keys()) observer.observe(header); + for (const region of this.observedRegions.keys()) observer.observe(region); } private evaluateVisibility() { const browser = this.document.defaultView; if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; this.refreshVisibilityObserver(); const width = browser.innerWidth, height = browser.innerHeight; - const rows: { top: number; cards: IndicadorCatalogCard[] }[] = []; - // Read the current DOM geometry; never retain index pairs or observer entry rectangles. + // Reread connected graphic regions after scroll/reorder; old observer rectangles + // cannot activate a card that has since moved outside the current viewport. for (const card of this.renderedCards) { - if (card.dominio !== this.dominio || !card.host.nativeElement.isConnected) continue; - const top = card.host.nativeElement.getBoundingClientRect().top; - const row = rows.find(row => row.cards.length < 2 && Math.abs(row.top - top) <= 1); - if (row) row.cards.push(card); else rows.push({ top, cards: [card] }); + const region = card.visibilityRegion?.nativeElement; + if (!region || card.dominio !== this.dominio || !region.isConnected) continue; + const rect = region.getBoundingClientRect(); + card.setVisible(rect.width > 0 && rect.height > 0 && rect.right > 0 + && rect.left < width && rect.bottom > this.stickyHeight && rect.top < height + 200); } - rows.sort((a, b) => a.top - b.top); - for (const row of rows) { - const trigger = row.cards.find(card => { - if (!card.awaitingVisibility || !this.observedHeaders.has(card.visibilityHeader.nativeElement)) return false; - const rect = card.visibilityHeader.nativeElement.getBoundingClientRect(); - const visibleWidth = Math.max(0, Math.min(rect.right, width) - Math.max(rect.left, 0)); - const visibleHeight = Math.max(0, Math.min(rect.bottom, height) - Math.max(rect.top, this.stickyHeight)); - return rect.width > 0 && rect.height > 0 && visibleWidth * visibleHeight / (rect.width * rect.height) >= 0.25; - }); - if (!trigger) continue; - const rect = trigger.visibilityHeader.nativeElement.getBoundingClientRect(); - const previous = this.confirmation; - const stable = previous && previous.trigger === trigger && previous.cards.length === row.cards.length - && row.cards.every((card, i) => card === previous.cards[i]) - && Math.abs(previous.top - rect.top) <= 1 && Math.abs(previous.left - rect.left) <= 1 - && Math.abs(previous.width - rect.width) <= 1 && Math.abs(previous.height - rect.height) <= 1 - && previous.viewportWidth === width && previous.viewportHeight === height; - if (!stable) { - this.confirmation = { cards: row.cards, trigger, top: rect.top, left: rect.left, width: rect.width, height: rect.height, viewportWidth: width, viewportHeight: height }; - this.queueVisibility(); - return; - } - this.confirmation = undefined; - for (const card of row.cards) card.activateVisible(); - this.changeDetector.markForCheck(); - // Wait for Angular's height change before considering any lower row. - afterNextRender(() => this.queueVisibility(), { injector: this.injector }); - return; - } - this.confirmation = undefined; + this.changeDetector.markForCheck(); } clearSearch() { this.changeSearchQuery(''); @@ -166,13 +139,11 @@ export class IndicadoresPage { changeSearchQuery(query: string) { this.preserveCardFocus(); this.searchQuery.set(query); - this.confirmation = undefined; } isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); } togglePinned(item: Indicador) { this.preserveCardFocus(); this.memory.togglePinned(this.dominio, item.id); - this.confirmation = undefined; } private preserveCardFocus() { const focused = this.document.activeElement; @@ -189,6 +160,9 @@ export class IndicadoresPage { } private readonly changeDetector = inject(ChangeDetectorRef); private readonly service = inject(IndicadoresService); + private readonly periodService = inject(IndicadoresPeriodos); + private readonly availabilityRequests = new Subject(); + readonly availability = signal(emptyAvailability()); private readonly memory = inject(IndicadoresMemory); private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute, { optional: true }); @@ -229,8 +203,10 @@ export class IndicadoresPage { tema: Tema = 'claro'; filters?: GlobalFilterState; readonly filterTypes = computed(() => domainTypes(this.catalog())); + retryAvailability() { this.availabilityRequests.next(); } filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); } applyFilters() { + this.evaluateVisibility(); if (!this.filters || !applyGlobal(this.filters, this.filterTypes())) return; this.filtersEdited(); this.changeDetector.markForCheck(); @@ -255,11 +231,16 @@ export class IndicadoresPage { const initialDomain: unknown = this.route?.snapshot.data['dominio']; if (isDominio(initialDomain)) this.dominio = initialDomain; this.tema = this.memory.theme(this.dominio); + this.availabilityRequests.pipe(switchMap(() => { + this.availability.set(emptyAvailability()); + return this.periodService.dominio(this.dominio, this.catalog()); + }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { this.clearVisibility(); this.catalogLoading.set(true); this.catalogError.set(''); this.catalog.set([]); + this.availabilityRequests.next(); return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })), catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { @@ -268,6 +249,7 @@ export class IndicadoresPage { this.catalog.set(items); this.filtersEdited(); this.catalogError.set(error); + this.availabilityRequests.next(); }); } changeDominio(dominio: Dominio) { @@ -282,6 +264,7 @@ export class IndicadoresPage { retryCatalog() { this.catalogRequests.next(); } changeTema(tema: Tema) { if ((tema !== 'claro' && tema !== 'oscuro') || tema === this.tema) return; + this.evaluateVisibility(); this.tema = tema; this.memory.rememberTheme(this.dominio, tema); this.changeDetector.markForCheck(); diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts new file mode 100644 index 0000000..6256449 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -0,0 +1,121 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { Dominio, IndicadorDatos } from './indicadores.models'; + +describe('P0.1 selección publicada y último periodo por KPI', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) }); + function catalog(domain: Dominio) { + fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); + http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }))); + fixture.detectChanges(); + return http.match(r => r.url.endsWith('/periodos')); + } + function load(domain: Dominio, periods: string[][]) { + catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i]))); + fixture.detectChanges(); + } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } + function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } + function data(index: number, domain: Dominio, period: string, suppressed = false): 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: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A', + n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0, + }] }; + } + function flushDatos(domain: Dominio, suppressed = false) { + const requests = http.match(r => r.url.endsWith('/datos')); + requests.forEach(r => { + const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); + r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed)); + }); + fixture.detectChanges(); return requests; + } + it.each(['cacu', 'cama'] as const)('%s usa últimos periodos propios, conserva ceros y no altera Todos aplicado', domain => { + load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); + const requests = flushDatos(domain); + expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S2', '2025-S2']); + expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S2', '2025-S2']); + expect(panels().map(p => p.result().value)).toEqual([0, '0.0', 0]); + expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'todos' }); + expect(fixture.componentInstance.filters!.applied.revision).toBe(0); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); + }); + it('supresión del último no busca periodos anteriores ni sustituye cifras', () => { + load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2'])); + const requests = flushDatos('cacu', true); + expect(requests.every(r => r.request.params.get('periodos') === '2026-S2')).toBe(true); + expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.result().value === undefined)).toBe(true); + expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true); + }); + it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => { + load('cama', [[], ['2025-S2'], ['2025-S1']]); const requests = flushDatos('cama'); + expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); + expect(panels()[0].result().value).toBeUndefined(); + }); + it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => { + load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu'); + const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges(); + expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']); + expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador'); + expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + const single = flushDatos('cacu'); expect(single).toHaveLength(3); + expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true); + control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true); + http.expectNone(() => true); + control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges(); + http.expectNone(() => true); + await fixture.whenStable(); + }); + it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => { + const requests = catalog('cacu'); + requests[0].flush('private', { status: 503, statusText: 'Unavailable' }); + requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2']))); + fixture.detectChanges(); flushDatos('cacu'); + expect(panels()[0].result().state).toBe('Error de disponibilidad'); + expect(fixture.nativeElement.textContent).toContain('No se pudo completar la consulta'); + expect(fixture.nativeElement.textContent).not.toContain('private'); + const control = editor(); control.changeMode('manual'); control.select(['2025-S2']); + expect(control.canApply).toBe(false); + fixture.componentInstance.retryAvailability(); fixture.detectChanges(); + const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos'); + http.expectNone(r => r.url.endsWith('/periodos')); + retry.flush(payload('cacu_eu7', ['2025-S2'])); fixture.detectChanges(); flushDatos('cacu'); + expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); + }); + it('cambio de dominio cancela inventarios y evita opciones o valores obsoletos', () => { + const outgoing = catalog('cacu'); const incoming = catalog('cama'); + expect(outgoing.every(r => r.cancelled)).toBe(true); + expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow(); + incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1']))); + fixture.detectChanges(); const requests = flushDatos('cama'); + expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true); + expect(editor().options).toEqual(['2025-S1']); + }); + it('error y catálogo vacío no inventan opciones ni consultas KPI', () => { + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(fixture.componentInstance.catalogError()).toBeTruthy(); http.expectNone(() => true); + fixture.componentInstance.retryCatalog(); http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges(); + expect(fixture.componentInstance.availability().options.semestre).toEqual([]); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-periodos.spec.ts b/src/app/features/indicadores/indicadores-periodos.spec.ts new file mode 100644 index 0000000..7dc3808 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.spec.ts @@ -0,0 +1,83 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Indicador, TipoPeriodo } from './indicadores.models'; +import { IndicadoresPeriodos, parseAvailability, PeriodAvailability, sortedPeriods } from './indicadores-periodos'; + +const item = (id: string, tipos_periodo: TipoPeriodo[] = ['semestre', 'mes']): Indicador => ({ id, titulo: id, contrato: 'C1', figuras: [], tipos_periodo }); +const payload = (id: string, periods: string[]) => ({ id, version: 'test', periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes', report_id: 1 })) }); +describe('P0.1 inventarios publicados de periodos', () => { + let service: IndicadoresPeriodos, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresPeriodos); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + it('une coberturas diferentes, deduplica y separa mes/semestre con orden numérico', () => { + let result!: PeriodAvailability; + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectOne('/cacu/indicadores/a/periodos').flush(payload('a', ['2025-S1', '2026-S2', '2025-S1', '2025-02', '2025-10'])); + http.expectOne('/cacu/indicadores/b/periodos').flush(payload('b', ['2024-S2', '2025-10', '2026-01'])); + expect(result.status).toBe('ready'); + expect(result.options).toEqual({ semestre: ['2026-S2', '2025-S1', '2024-S2'], mes: ['2026-01', '2025-10', '2025-02'] }); + expect(result.byIndicator['b'].some(p => p.periodo === '2026-S2')).toBe(false); + }); + it('respeta capacidades individuales y no mezcla dominios en caché', () => { + let result!: PeriodAvailability; + service.dominio('tea', [item('a', ['semestre'])]).subscribe(value => result = value); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', ['2025-S1', '2025-01'])); + expect(result.options.mes).toEqual([]); + service.dominio('cama', [item('a')]).subscribe(); + http.expectOne('/cama/indicadores/a/periodos').flush(payload('a', [])); + }); + it('limita a cuatro consultas simultáneas y cancela también la cola', () => { + const sub = service.dominio('tea', Array.from({ length: 9 }, (_, i) => item('i' + i))).subscribe(); + const first = http.match(r => r.url.endsWith('/periodos')); expect(first).toHaveLength(4); + first[0].flush(payload('i0', [])); + const next = http.expectOne('/tea/indicadores/i4/periodos'); + sub.unsubscribe(); + expect(first.slice(1).every(r => r.cancelled)).toBe(true); expect(next.cancelled).toBe(true); + http.expectNone(r => r.url.includes('/i5/')); + }); + it('reutiliza inventarios exitosos sin HTTP y reintenta únicamente errores sin publicar unión parcial', () => { + let result!: PeriodAvailability; + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectOne('/cacu/indicadores/a/periodos').flush(payload('a', ['2025-S1'])); + http.expectOne('/cacu/indicadores/b/periodos').flush('private', { status: 503, statusText: 'Unavailable' }); + expect(result.status).toBe('error'); expect(result.options.semestre).toEqual([]); + expect(result.errors['b']).not.toContain('private'); expect(result.byIndicator['a']).toHaveLength(1); + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectNone('/cacu/indicadores/a/periodos'); + http.expectOne('/cacu/indicadores/b/periodos').flush(payload('b', ['2025-S2'])); + expect(result.options.semestre).toEqual(['2025-S2', '2025-S1']); + service.dominio('cacu', [item('a'), item('b')]).subscribe(); http.expectNone(() => true); + }); + it('un inventario cancelado no entrega respuestas obsoletas ni se conserva como éxito', () => { + const delivered = vi.fn(); + const sub = service.dominio('tea', [item('a')]).subscribe(delivered); + const old = http.expectOne('/tea/indicadores/a/periodos'); sub.unsubscribe(); + expect(old.cancelled).toBe(true); expect(delivered).not.toHaveBeenCalled(); + expect(() => old.flush(payload('a', ['2025-S1']))).toThrow(); + service.dominio('tea', [item('a')]).subscribe(delivered); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', [])); + expect(delivered).toHaveBeenCalledOnce(); + }); + it('catálogo vacío y lista vacía son éxito sin periodos inventados', () => { + let result!: PeriodAvailability; + service.dominio('tea', []).subscribe(value => result = value); + expect(result.status).toBe('ready'); expect(result.options.semestre).toEqual([]); http.expectNone(() => true); + service.dominio('tea', [item('a')]).subscribe(value => result = value); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', [])); + expect(result.byIndicator['a']).toEqual([]); + }); + it.each([ + null, { id: 'wrong', periodos: [] }, { id: 'a' }, payload('a', ['2025-13']), + { id: 'a', periodos: [{ periodo: '2025-S1', tipo: 'mes' }] }, + ])('rechaza respuestas inválidas sin inventar disponibilidad: %j', value => { + expect(() => parseAvailability(value, 'a')).toThrow(); + }); + it('ordena cambios de año y unidades sin usar el orden accidental', () => { + expect(sortedPeriods(['2026-S1', '2025-S2', '2026-S2'])).toEqual(['2026-S2', '2026-S1', '2025-S2']); + expect(sortedPeriods(['2025-02', '2024-12', '2025-10', '2026-01'])).toEqual(['2026-01', '2025-10', '2025-02', '2024-12']); + }); +}); diff --git a/src/app/features/indicadores/indicadores-periodos.testing.ts b/src/app/features/indicadores/indicadores-periodos.testing.ts new file mode 100644 index 0000000..adabe64 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.testing.ts @@ -0,0 +1,18 @@ +import { of } from 'rxjs'; +import { Indicador } from './indicadores.models'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; + +// Existing figure/search/visibility suites isolate their HTTP from availability. +// The new P0.1 suites exercise the real availability HTTP separately. +export const periodAvailabilityProvider = { + provide: IndicadoresPeriodos, + useValue: { dominio: (_domain: unknown, catalog: Indicador[]) => { + const state = emptyAvailability('ready'); + for (const tipo of ['semestre', 'mes'] as const) { + state.options[tipo] = [2024, 2025, 2026].flatMap(year => + (tipo === 'semestre' ? ['S1', 'S2'] : Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0'))).map(unit => year + '-' + unit)); + } + for (const item of catalog) state.byIndicator[item.id] = item.tipos_periodo.flatMap(tipo => state.options[tipo].map(periodo => ({ tipo, periodo }))); + return of(state); + } }, +}; diff --git a/src/app/features/indicadores/indicadores-periodos.ts b/src/app/features/indicadores/indicadores-periodos.ts new file mode 100644 index 0000000..fc4031b --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.ts @@ -0,0 +1,77 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { catchError, from, map, mergeMap, Observable, of, shareReplay, toArray } from 'rxjs'; +import { Dominio, Indicador, parsePeriodos, requireDominio, TipoPeriodo } from './indicadores.models'; +import { httpMessage } from './indicadores-http'; + +export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; } +export interface PeriodAvailability { + status: 'loading' | 'ready' | 'error'; + byIndicator: Record; + options: Record; + errors: Record; +} +export function emptyAvailability(status: PeriodAvailability['status'] = 'loading'): PeriodAvailability { + return { status, byIndicator: {}, options: { semestre: [], mes: [] }, errors: {} }; +} +// Numeric year/unit comparison, independent of server order and report generation date. +export function periodOrder(period: string): number { + return Number(period.slice(0, 4)) * 12 + (period.includes('-S') ? Number(period.slice(6)) * 6 : Number(period.slice(5))); +} +export function sortedPeriods(periods: readonly string[]): string[] { + return [...new Set(periods)].sort((a, b) => periodOrder(b) - periodOrder(a)); +} +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +export function parseAvailability(value: unknown, id: string): AvailablePeriod[] { + if (!record(value) || value['id'] !== id || !Array.isArray(value['periodos'])) throw new Error('Respuesta de periodos inválida'); + const unique = new Map(); + for (const row of value['periodos']) { + if (!record(row) || (row['tipo'] !== 'semestre' && row['tipo'] !== 'mes') + || typeof row['periodo'] !== 'string' || parsePeriodos(row['periodo'], row['tipo'])?.[0] !== row['periodo']) { + throw new Error('Respuesta de periodos inválida'); + } + unique.set(row['periodo'], { periodo: row['periodo'], tipo: row['tipo'] }); + } + return [...unique.values()].sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo)); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresPeriodos { + private readonly http = inject(HttpClient); + // Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached. + private readonly cache = new Map>(); + periodos(domain: Dominio, id: string) { + const dominio = requireDominio(domain); + const key = JSON.stringify([dominio, id]); + let request = this.cache.get(key); + if (!request) { + request = this.http.get(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`).pipe( + map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true })); + this.cache.set(key, request); + } + return request; + } + dominio(domain: Dominio, catalog: readonly Indicador[]): Observable { + return from(catalog).pipe( + mergeMap(item => this.periodos(domain, item.id).pipe( + map(periods => ({ id: item.id, periods: periods.filter(p => item.tipos_periodo.includes(p.tipo)), error: '' })), + catchError(error => of({ id: item.id, periods: [] as AvailablePeriod[], error: httpMessage(error) }))), 4), + toArray(), + map(results => { + const state = emptyAvailability('ready'); + for (const result of results) { + if (result.error) state.errors[result.id] = result.error; + else state.byIndicator[result.id] = result.periods; + } + state.status = Object.keys(state.errors).length ? 'error' : 'ready'; + // Do not publish an incomplete union as a successful inventory. + if (state.status === 'ready') { + for (const tipo of ['semestre', 'mes'] as const) { + state.options[tipo] = sortedPeriods(Object.values(state.byIndicator).flat().filter(p => p.tipo === tipo).map(p => p.periodo)); + } + } + return state; + })); + } +} diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index 969f630..8906a5e 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -21,15 +22,15 @@ describe('UX-06E.D.3.B fijación temporal', () => { let http: HttpTestingController; const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); - vi.stubGlobal('IntersectionObserver', undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); load(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); - function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); } + function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); } function load(domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function card(id: string) { return cards().find(c => c.indicador.id === id)!; } @@ -100,20 +101,20 @@ describe('UX-06E.D.3.B fijación temporal', () => { expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control); await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true); }); - it('preserva figura seleccionada, apertura, cierre manual, panel y host Plotly', async () => { - card('i3').toggle(); fixture.detectChanges(); respond(); await settle(); + it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => { + card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle(); card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle(); - card('i1').toggle(); fixture.detectChanges(); respond(); card('i1').toggle(); fixture.detectChanges(); await settle(); - const before = cards(), panel = fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance; + + const before = cards(), panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied; const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length; for (const id of ['i3', 'i1', 'i3']) { await pin(id); for (const c of before) expect(card(c.indicador.id)).toBe(c); - expect(card('i3').expanded).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').figuresActivated).toBe(true); - expect(card('i1').expanded).toBe(false); expect(TestBed.inject(IndicadoresMemory).activation('tea', 'i1')).toBe('manual-closed'); - expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); + expect(card('i3').visible).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').visible).toBe(true); + expect(card('i1').visible).toBe(false); + expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied); http.expectNone(() => true); @@ -121,10 +122,10 @@ describe('UX-06E.D.3.B fijación temporal', () => { expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges); }); it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => { - card('i4').toggle(); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f')); - const panel = fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance; + card('i4').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f')); + const panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; await pin('i4'); expect(request.cancelled).toBe(false); - expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); http.expectNone(() => true); + expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); http.expectNone(() => true); request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]); }); }); diff --git a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts index 42174a3..f02e6a9 100644 --- a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts +++ b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -14,6 +15,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; const disconnects: ReturnType[] = []; beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.resetAllMocks(); disconnects.length = 0; runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { @@ -21,12 +23,13 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => // Material outline labels also observe size; track only Plotly hosts here. observe = vi.fn((target: Element) => { if (target.classList.contains('plot')) disconnects.push(this.disconnect); }); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + fixture = TestBed.createComponent(IndicadoresPage); + vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'j', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]); fixture.detectChanges(); - for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).toggle(); + for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).setVisible(true); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); @@ -42,7 +45,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f'); expect(hosts[1].getAttribute('aria-label')).toBe('tea · j · g'); const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; - card.toggle(); fixture.detectChanges(); + fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges(); expect(runtime.purge).toHaveBeenCalledWith(hosts[0]); expect(runtime.purge).not.toHaveBeenCalledWith(hosts[1]); expect(disconnects[0]).toHaveBeenCalledTimes(1); expect(disconnects[1]).not.toHaveBeenCalled(); diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts index 540d2e5..660a706 100644 --- a/src/app/features/indicadores/indicadores-search.spec.ts +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -29,11 +30,12 @@ describe('UX-05C búsqueda local y partición estable', () => { const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; const disconnect = vi.fn(); beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); }); afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); @@ -41,7 +43,7 @@ describe('UX-05C búsqueda local y partición estable', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); } function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); } function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); } @@ -57,7 +59,7 @@ describe('UX-05C búsqueda local y partición estable', () => { it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); - expect(cards().every(c => !c.expanded)).toBe(true); + expect(cards().every(c => !c.visible)).toBe(true); http.expectNone(() => true); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); @@ -79,7 +81,7 @@ describe('UX-05C búsqueda local y partición estable', () => { expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); for (const card of cards()) { expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id)); - expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.expanded).toBe(false); + expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false); } if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe(''); @@ -137,7 +139,7 @@ describe('UX-05C búsqueda local y partición estable', () => { http.expectNone(() => true); }); it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => { - load(); cards().slice(0, 3).forEach(c => c.toggle()); fixture.detectChanges(); respond(); await settle(); + load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle(); const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); page.applyFilters(); fixture.detectChanges(); respond(); await settle(); @@ -152,13 +154,13 @@ describe('UX-05C búsqueda local y partición estable', () => { const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal'); const reacts = runtime.react.mock.calls.length; const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[]; - expect(helps).toHaveLength(3); + expect(helps).toHaveLength(5); const helpIds = helps.map(button => button.getAttribute('aria-controls')!); - expect(new Set(helpIds).size).toBe(3); + expect(new Set(helpIds).size).toBe(5); for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true); helps[0].click(); fixture.detectChanges(); await settle(); - expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false']); - expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true]); + expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); + expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]); for (const query of ['sexo', 'evaluacion', '']) { if (query) await search(query); else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); } @@ -167,9 +169,9 @@ describe('UX-05C búsqueda local y partición estable', () => { beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c)); beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c)); } - expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.expanded)).toBe(true); + expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true); for (const button of helps) expect(button.isConnected).toBe(true); - expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false']); + expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); helps[0].click(); fixture.detectChanges(); await settle(); expect(document.getElementById(helpIds[0])?.hidden).toBe(true); expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts); @@ -187,7 +189,7 @@ describe('UX-05C búsqueda local y partición estable', () => { http.expectNone(() => true); }); it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => { - load(); cards().slice(0, 3).forEach(c => c.toggle()); fixture.detectChanges(); + load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo'); b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle(); await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error'); @@ -196,27 +198,27 @@ describe('UX-05C búsqueda local y partición estable', () => { const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} }); expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true); }); - it('mover una tarjeta abierta mantiene el foco en su control existente', async () => { - load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); + it('reordenar el catálogo conserva foco en el selector global existente', async () => { + load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); fixture.detectChanges(); await settle(); - const field = fixture.nativeElement.querySelector('app-indicador-period-filters input') as HTMLInputElement; + const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf).at(-1)!; field.focus(); expect(document.activeElement).toBe(field); page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true); page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); http.expectNone(() => true); }); - it('cambiar de dominio limpia búsqueda y volver conserva expansión y borrador mediante memoria existente', async () => { - load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); + it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => { + load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add(); await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe(''); - load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].expanded).toBe(false); + load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false); page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe(''); - expect(cards().map(c => c.expanded)).toEqual([false, false, true, false, false]); - http.expectNone(() => true); cards()[2].toggle(); fixture.detectChanges(); + expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]); + http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges(); const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} }); expect(filters()[0].selectedPeriods).toEqual(['2025-S1']); - await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; load(); respond(); + await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond(); expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); }); }); diff --git a/src/app/features/indicadores/indicadores-visibility.spec.ts b/src/app/features/indicadores/indicadores-visibility.spec.ts index a4ac0c2..eae5fea 100644 --- a/src/app/features/indicadores/indicadores-visibility.spec.ts +++ b/src/app/features/indicadores/indicadores-visibility.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -44,7 +45,7 @@ class ResizeControl { emit() { this.callback([], this as unknown as ResizeObserver); } } -describe('UX-06E.D.1.1 visibilidad controlada', () => { +describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; @@ -68,7 +69,7 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => { sticky = document.createElement('header'); sticky.className = 'institutional-header'; document.body.append(sticky); geometry.set(sticky, rect(0, 0, 1440, 100)); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); create(); @@ -88,7 +89,7 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => { function positions(values: number[][]) { cards().forEach((card, i) => { geometry.set(card.host.nativeElement, rect(values[i][0], values[i][1])); - geometry.set(card.visibilityHeader.nativeElement, rect(values[i][0] + 16, values[i][1])); + geometry.set(card.visibilityRegion!.nativeElement, rect(values[i][0], values[i][1], 600, 620)); }); } function observer() { return IntersectionControl.instances.at(-1)!; } @@ -96,252 +97,125 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => { const callbacks = [...frames.values()]; frames.clear(); callbacks.forEach(callback => callback(0)); await render(); } async function confirm() { await frame(); await frame(); } - function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityHeader.nativeElement, intersects); } + function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityRegion!.nativeElement, intersects); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); } async function idle() { for (let i = 0; i < 6 && frames.size; i++) await frame(); expect(frames.size).toBe(0); } - it('D.3.B fijar invalida la fila pendiente y aplica visibilidad actual sin anticipar carga', async () => { - await load(); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - const original = cards(); - original[4].host.nativeElement.querySelector('.pin-toggle')!.click(); await render(); - expect(cards()[0]).toBe(original[4]); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - http.expectNone(() => true); await frame(); http.expectNone(() => true); - await frame(); expect(cards()[0].expanded).toBe(true); expect(original[0].expanded).toBe(false); - http.expectOne(r => r.url.endsWith('/i4/figuras/f')).flush({ data: [], layout: {} }); await idle(); - cards()[0].toggle(); await render(); - original[0].host.nativeElement.querySelector('.pin-toggle')!.click(); await render(); - positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); await confirm(); respond(); await idle(); - expect(original[4].expanded).toBe(false); expect(memory.activation('tea', 'i4')).toBe('manual-closed'); - http.expectNone(() => true); - }); - - it('observa sólo cabeceras gráficas con viewport, umbral y margen sticky medido', async () => { - await load(); - expect(observer().options).toEqual({ root: null, threshold: 0.25, rootMargin: '-100px 0px 0px 0px' }); - expect([...observer().targets]).toEqual(cards().map(card => card.visibilityHeader.nativeElement)); - expect([...observer().targets].every(target => target.tagName === 'HEADER')).toBe(true); - expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); - await idle(); http.expectNone(() => true); - }); - it('exige dos frames y activa una sola vez sin autocierre ni nuevas consultas', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); - await frame(); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - await frame(); expect(memory.activation('tea', 'i0')).toBe('auto-open'); expect(panels()).toHaveLength(1); respond(); - const panel = panels()[0], result = panel.result(); - positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); - observer().emit(cards()[0].visibilityHeader.nativeElement, false); await idle(); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(true); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); http.expectNone(() => true); - }); - it('abre juntas dos tarjetas de la fila real sin abrir filas inferiores', async () => { - await load(); positions([[200, 0], [200.5, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); - expect(panels()).toHaveLength(2); respond(); await idle(); http.expectNone(() => true); - }); - it('en una columna no asocia dos indicadores por índice', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); - }); - it('una intersección fugaz y una entrada antigua no abren una tarjeta ya fuera', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - positions([[900, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); await frame(); - notify(); await idle(); expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); - }); - it('un desplazamiento rápido invalida la confirmación geométrica previa', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - positions([[400, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); await frame(); - expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); await idle(); - }); - it('procesa primero la fila superior y descarta inferiores desplazadas por reflow', async () => { - await load(); positions([[200, 0], [200, 650], [400, 0], [400, 650], [1000, 0]]); notify(2); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); respond(); - positions([[200, 0], [200, 650], [1100, 0], [1100, 650], [1300, 0]]); await idle(); - expect(cards()[2].expanded).toBe(false); http.expectNone(() => true); - }); - it('las filas todavía visibles se activan en nuevas evaluaciones después de render', async () => { - await load(); positions([[200, 0], [200, 650], [450, 0], [450, 650], [1000, 0]]); notify(); await confirm(); respond(); - await confirm(); expect(cards().map(card => card.expanded)).toEqual([true, true, true, true, false]); respond(); await idle(); - }); - it('recalcula asociaciones responsive entre los dos frames', async () => { - await load(); positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await frame(); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); window.dispatchEvent(new Event('resize')); - await frame(); expect(cards().every(card => !card.expanded)).toBe(true); - await frame(); expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); - }); - it('excluye cabeceras detrás de sticky y mide sus cambios de altura', async () => { - await load(); positions([[0, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); http.expectNone(() => true); - const old = observer(); geometry.set(sticky, rect(0, 0, 1440, 50)); ResizeControl.instances.find(instance => instance.targets.has(sticky))!.emit(); - await frame(); expect(old.disconnect).toHaveBeenCalled(); expect(observer().options.rootMargin).toBe('-50px 0px 0px 0px'); - await frame(); expect(cards()[0].expanded).toBe(true); respond(); await idle(); - }); - it('una cabecera parcialmente visible por debajo del umbral no se activa', async () => { - await load(); positions([[770, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - }); - it('cierre manual prevalece sobre una confirmación pendiente y permite reapertura', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - cards()[0].toggle(); await render(); const request = http.expectOne(r => r.url.includes('/figuras/')); - cards()[0].toggle(); await render(); expect(request.cancelled).toBe(true); - notify(); await idle(); expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); - cards()[0].toggle(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-open'); respond(); - }); - it('una compañera cerrada manualmente permanece cerrada', async () => { - memory.rememberActivation('tea', 'i1', 'manual-closed'); await load(); - positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); - }); - it.each(['tea', 'cacu', 'cama'] as const)('singleton %s espera visibilidad antes de consultar', async domain => { + it.each([{ domain: 'tea', count: 18 }, { domain: 'cacu', count: 8 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => { if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } - await load([items[0]], domain); await idle(); http.expectNone(() => true); expect(cards()[0].expanded).toBe(false); - positions([[200, 0]]); notify(); await confirm(); expect(memory.activation(domain, 'i0')).toBe('auto-open'); respond(); await idle(); + await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'i' + i })), domain); + await idle(); expect(cards()).toHaveLength(count); expect(panels()).toHaveLength(count); + expect(panels().every(p => p.result().status === 'deferred')).toBe(true); http.expectNone(() => true); + expect(fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button')).toHaveLength(0); + expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(count); + positions(cards().map((_, i) => [i < 2 ? 200 : 1200 + i * 1000, i === 1 ? 650 : 0])); notify(); await confirm(); + const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2); + requests.forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); await render(); await idle(); http.expectNone(() => true); }); - it('regresar conserva abierto sin montar fuera del viewport, y carga al entrar', async () => { - await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); - page.changeDominio('cacu'); await load([items[0]], 'cacu'); await idle(); - expect(cards()[0].expanded).toBe(false); - page.changeDominio('tea'); await load([items[0]]); await idle(); - expect(cards()[0].expanded).toBe(true); expect(cards()[0].awaitingFigures).toBe(true); expect(panels()).toHaveLength(0); http.expectNone(() => true); - expect(fixture.nativeElement.textContent).toContain('Apertura recordada'); - positions([[200, 0]]); notify(); await confirm(); expect(panels()).toHaveLength(1); respond(); await idle(); - expect(memory.activation('tea', 'i0')).toBe('auto-open'); - }); - it('fallback manual permite mostrar figuras restauradas al primer clic y cerrar al siguiente', async () => { - http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create(); memory.rememberActivation('tea', 'i0', 'auto-open'); - await load([items[0]]); expect(IntersectionControl.instances).toHaveLength(0); http.expectNone(() => true); - const button = fixture.nativeElement.querySelector('app-indicador-catalog-card header button') as HTMLButtonElement; - expect(button.getAttribute('aria-expanded')).toBe('true'); expect(button.getAttribute('aria-label')).toContain('Mostrar figuras'); - button.focus(); button.click(); await render(); expect(document.activeElement).toBe(button); expect(panels()).toHaveLength(1); respond(); - button.click(); await render(); expect(button.getAttribute('aria-expanded')).toBe('false'); expect(panels()).toHaveLength(0); http.expectNone(() => true); - button.click(); await render(); expect(panels()).toHaveLength(1); respond(); - }); - it('búsqueda activa indirectamente una pendiente visible y conserva cierre manual al limpiar', async () => { - memory.rememberActivation('tea', 'i0', 'manual-closed'); await load(); await idle(); - const original = cards(); page.changeSearchQuery('Indicador 4'); await render(); - expect(cards()[0]).toBe(original[4]); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - http.expectNone(() => true); notify(); await confirm(); respond(); - page.changeSearchQuery(''); await render(); expect(cards()).toEqual(original); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(false); expect(cards()[4].expanded).toBe(true); http.expectNone(() => true); - }); - it('reordenar una pendiente fuera de vista no autoriza carga con callback antiguo', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); const target = cards()[0].visibilityHeader.nativeElement; - notify(); await frame(); page.changeSearchQuery('Indicador 4'); await render(); - positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); observer().emit(target); await idle(); - expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); - }); - it('retirar tarjetas desobserva sus cabeceras y descarta callbacks tardíos', async () => { - await load(); const retired = cards()[0].visibilityHeader.nativeElement, active = observer(); - page.catalog.set(items.slice(1)); await render(); - expect(active.unobserve).toHaveBeenCalledWith(retired); active.emit(retired); await idle(); http.expectNone(() => true); - }); - it('cambiar de dominio cancela HTTP e ignora el observer saliente', async () => { - await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); - const request = http.expectOne(r => r.url.includes('/figuras/')), old = observer(), target = cards()[0].visibilityHeader.nativeElement; - page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true); - expect(old.disconnect).toHaveBeenCalled(); old.emit(target); await idle(); http.expectNone(() => true); - }); - it('destruir desconecta observers, cancela frames y hace inocuos callbacks tardíos', async () => { - await load(); const active = observer(), target = cards()[0].visibilityHeader.nativeElement; - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - const sizeObserver = ResizeControl.instances.find(instance => instance.targets.has(sticky))!; - const scheduled = new Set(frames.keys()); - const cancellations = vi.mocked(window.cancelAnimationFrame).mock.calls.length; - fixture.destroy(); expect(active.disconnect).toHaveBeenCalled(); expect(sizeObserver.disconnect).toHaveBeenCalled(); - const cancelled = vi.mocked(window.cancelAnimationFrame).mock.calls.slice(cancellations).map(([id]) => id); - expect(cancelled.some(id => scheduled.has(id))).toBe(true); - for (const id of cancelled) expect(frames.has(id)).toBe(false); - // Angular/Material can own another global frame; late page callbacks must add none. - const remaining = frames.size; - active.emit(target); sizeObserver.emit(); window.dispatchEvent(new Event('scroll')); - expect(frames.size).toBe(remaining); http.expectNone(() => true); - }); - it('apertura automática monta sólo la primera figura y el cierre cancela la seleccionada', async () => { - await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm(); - const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(1); - requests[0].flush('private', { status: 500, statusText: 'Error' }); await render(); - expect(panels().map(panel => panel.result().status)).toEqual(['error']); - cards()[0].selectFigure('g'); await render(); - const current = http.expectOne(r => r.url.endsWith('/figuras/g')); - cards()[0].toggle(); await render(); expect(current.cancelled).toBe(true); - notify(); await idle(); http.expectNone(() => true); cards()[0].toggle(); await render(); - expect(panels()[0].figuraId).toBe('g'); respond(); - }); - it('fallback sin observers permite la apertura y cierre de una tarjeta pendiente', async () => { - http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); vi.stubGlobal('ResizeObserver', undefined); create(); - await load([items[0]]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - const button = fixture.nativeElement.querySelector('app-indicador-catalog-card header button') as HTMLButtonElement; - for (const key of ['Tab', 'Enter', ' ']) { - const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); - button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); - } - button.click(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-open'); respond(); - button.click(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); - }); - it('la activación protegida nunca sobrescribe una decisión manual', async () => { - memory.rememberActivation('tea', 'i0', 'manual-closed'); memory.rememberActivation('tea', 'i1', 'manual-open'); await load(); - cards()[0].activateVisible(); cards()[1].activateVisible(); await render(); - expect(memory.activation('tea', 'i0')).toBe('manual-closed'); expect(cards()[0].expanded).toBe(false); - expect(memory.activation('tea', 'i1')).toBe('manual-open'); expect(cards()[1].figuresActivated).toBe(true); respond(); - cards()[1].activateVisible(); await render(); http.expectNone(() => true); - }); - it('scroll progresivo reactiva evaluación sin mantener un bucle cuando todo está fuera', async () => { - await load(); await idle(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); respond(); await idle(); - positions([[-1000, 0], [200, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); respond(); await idle(); - expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); http.expectNone(() => true); - }); - it('búsqueda reconstruye la fila visual usando las mismas instancias', async () => { - await load(); await idle(); const before = cards(); page.changeSearchQuery('Indicador 4'); await render(); - positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); respond(); await idle(); - expect(memory.activation('tea', 'i4')).toBe('auto-open'); expect(memory.activation('tea', 'i0')).toBe('auto-open'); - expect(memory.activation('tea', 'i1')).toBe('pending'); - expect(cards().every(card => before.includes(card))).toBe(true); http.expectNone(() => true); - }); - it('una cabecera fuera horizontalmente no se considera visible', async () => { - await load([items[0]]); positions([[200, 1500]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - }); - it('visibilidad y búsqueda conservan hosts Plotly, resultados y foco sin react ni purge repetidos', async () => { - http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), - { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - const input = fixture.nativeElement.querySelector('.catalog-search input') as HTMLInputElement; input.focus(); notify(); await confirm(); respond(); await render(); - for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); - const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; - const host = chart.host.nativeElement, panel = panels()[0], result = panel.result(), reacts = runtime.react.mock.calls.length; - expect(reacts).toBe(1); expect(document.activeElement).toBe(input); - page.changeSearchQuery('Indicador 0'); await render(); notify(); await idle(); - expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.host.nativeElement).toBe(host); - expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); expect(document.activeElement).toBe(input); - expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true); - }); - it('D.2 aplicar fuera de pantalla no activa tarjetas y scroll consulta la revisión vigente una sola vez', async () => { + it('observa regiones gráficas permanentemente con margen de anticipación y sticky', async () => { await load(); await idle(); + expect(observer().options).toEqual({ root: null, threshold: 0, rootMargin: '-100px 0px 200px 0px' }); + expect([...observer().targets]).toEqual(cards().map(c => c.visibilityRegion!.nativeElement)); + positions([[900, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + expect(observer().targets.size).toBe(5); expect(panels()[0].result().status).toBe('ready'); + expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(4); + }); + it('salir y volver conserva panel, resultado y selección sin HTTP redundante', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + const panel = panels()[0], result = panel.result(); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(0, false); await idle(); + expect(cards()[0].visible).toBe(false); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await idle(); + expect(panel.result()).toBe(result); http.expectNone(() => true); + }); + it('filtro fuera de vista conserva host y consulta únicamente el último aplicado al regresar', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart'); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle(); const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; - filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); - page.applyFilters(); await render(); await idle(); - expect(cards().every(card => !card.figuresActivated)).toBe(true); http.expectNone(() => true); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); - const first = http.expectOne(r => r.url.includes('/i0/figuras/')); - expect(first.request.params.get('periodos')).toBe('2025-S1'); first.flush({ data: [], layout: {} }); - expect(panels()[0].applied.revision).toBe(1); await idle(); - cards()[0].toggle(); await render(); - filters.unit = 'S2'; filters.add(); page.applyFilters(); await render(); await idle(); - expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); - positions([[-1000, 0], [200, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); - const second = http.expectOne(r => r.url.includes('/i1/figuras/')); - expect(second.request.params.get('periodos')).toBe('2025-S1,2025-S2'); second.flush({ data: [], layout: {} }); - expect(panels()[0].applied.revision).toBe(2); await idle(); - notify(1); await idle(); page.applyFilters(); await render(); http.expectNone(() => true); + filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render(); + filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle(); + expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred'); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/i0/figuras/')); + expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro'); + request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true); + }); + it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); + const old = http.expectOne(r => r.url.includes('/i0/figuras/')); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); + page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; page.applyFilters(); await render(); + expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('deferred'); http.expectNone(() => true); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); await idle(); + }); + it('cambio rápido de representación cancela saliente y fuera de vista difiere seleccionada', async () => { + await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm(); + const old = http.expectOne(r => r.url.endsWith('/figuras/f')); cards()[0].selectFigure('g'); await render(); + expect(old.cancelled).toBe(true); const next = http.expectOne(r => r.url.endsWith('/figuras/g')); + cards()[0].selectFigure('h'); await render(); expect(next.cancelled).toBe(true); + http.expectOne(r => r.url.endsWith('/figuras/h')).flush({ data: [], layout: {} }); await render(); + expect(panels()).toHaveLength(1); positions([[-1000, 0]]); notify(0, false); await idle(); + cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred'); + positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} }); + }); + it('fijación y búsqueda conservan componentes y descartan callbacks con geometría antigua', async () => { + await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); + const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render(); + page.changeSearchQuery('Indicador 3'); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0])); + observer().emit(target); await idle(); http.expectNone(() => true); + expect(cards()[0]).toBe(before[3]); expect(cards()[1]).toBe(before[4]); expect(cards().every(c => before.includes(c))).toBe(true); + positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm(); + http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render(); + expect(cards()[0].selectedFigure).toBe('f'); + }); + it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + http.expectOne(r => r.url.includes('/figuras/')).flush(figure); await render(); + expect(panels()[0].result().status).toBe('ready'); expect(panels()[0].result().figure).toEqual(figure); + expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + if (figure.layout.annotations) expect(panels()[0].result().figure?.layout['annotations']).toEqual(figure.layout.annotations); + }); + it('error HTTP termina skeleton y reintenta sólo la figura visible', async () => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + http.expectOne(r => r.url.includes('/figuras/')).flush('private', { status: 503, statusText: 'Unavailable' }); await render(); + expect(panels()[0].result().status).toBe('error'); expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); + panels()[0].requestFigure(); respond(); await render(); expect(panels()[0].result().status).toBe('ready'); + }); + it('fallback sin IntersectionObserver muestra las figuras sin interacción manual', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create(); + await load([items[0]]); respond(); await render(); expect(panels()[0].result().status).toBe('ready'); + expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); http.expectNone(() => true); + }); + it('dominio cancela solicitudes, desobserva tarjetas retiradas e ignora callback antiguo', async () => { + await load(); const oldObserver = observer(), retired = cards()[0].visibilityRegion!.nativeElement; + page.catalog.set(items.slice(1)); await render(); expect(oldObserver.unobserve).toHaveBeenCalledWith(retired); + oldObserver.emit(retired); await idle(); http.expectNone(() => true); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/figuras/')); + page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true); + expect(oldObserver.disconnect).toHaveBeenCalled(); oldObserver.emit(retired); await idle(); http.expectNone(() => true); + }); + it('destrucción desconecta observers, cancela frame y vuelve inocuos callbacks tardíos', async () => { + await load(); const active = observer(), target = cards()[0].visibilityRegion!.nativeElement; + notify(); const pending = [...frames.keys()]; fixture.destroy(); + expect(active.disconnect).toHaveBeenCalled(); expect(ResizeControl.instances.some(o => o.disconnect.mock.calls.length)).toBe(true); + expect(pending.some(id => vi.mocked(window.cancelAnimationFrame).mock.calls.some(call => call[0] === id))).toBe(true); + const remaining = frames.size; active.emit(target); window.dispatchEvent(new Event('scroll')); expect(frames.size).toBe(remaining); + }); + it('hosts Plotly permanecen montados fuera de vista y se purgan al destruir', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); await render(); + for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart, host = chart.host.nativeElement; + expect(runtime.react).toHaveBeenCalledTimes(1); positions([[-1000, 0]]); notify(0, false); await idle(); + expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled(); + positions([[200, 0]]); notify(); await idle(); expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true); + fixture.destroy(); expect(runtime.purge).toHaveBeenCalledWith(host); }); }); From 4685a91a7cdb46797d37098041e6c33bc93cfee8 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 14 Oct 2026 13:00:54 -0600 Subject: [PATCH 18/51] feat(ui): mejorar presentacion y disponibilidad inicial de KPI --- .../indicadores/indicador-kpi-card.spec.ts | 16 ++ .../indicadores/indicador-kpi-card.ts | 11 +- .../indicadores/indicador-kpi-initial.spec.ts | 121 +++++++++++++++ .../indicadores/indicador-kpi-panel.spec.ts | 140 +++++++++++++++++- .../indicadores/indicador-kpi-panel.ts | 86 +++++++---- .../indicadores/indicador-period-filters.html | 2 +- .../indicadores/indicador-period-filters.ts | 1 + .../indicadores-global-filters.spec.ts | 21 ++- .../indicadores/indicadores-kpi-queries.ts | 23 +++ .../features/indicadores/indicadores-kpi.ts | 6 +- .../indicadores/indicadores-memory.ts | 3 + .../indicadores-navigation.spec.ts | 1 + .../indicadores/indicadores-page.html | 25 ++-- .../indicadores/indicadores-page.scss | 4 +- .../indicadores/indicadores-page.spec.ts | 46 +++--- .../features/indicadores/indicadores-page.ts | 18 ++- .../indicadores-periodos-integration.spec.ts | 5 +- .../indicadores/indicadores-periodos.ts | 4 +- .../indicadores/indicadores-requests.ts | 35 +++++ 19 files changed, 466 insertions(+), 102 deletions(-) create mode 100644 src/app/features/indicadores/indicador-kpi-initial.spec.ts create mode 100644 src/app/features/indicadores/indicadores-kpi-queries.ts create mode 100644 src/app/features/indicadores/indicadores-requests.ts diff --git a/src/app/features/indicadores/indicador-kpi-card.spec.ts b/src/app/features/indicadores/indicador-kpi-card.spec.ts index 913be29..ae3a5a1 100644 --- a/src/app/features/indicadores/indicador-kpi-card.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-card.spec.ts @@ -29,6 +29,22 @@ import { IndicadorKpiCard } from './indicador-kpi-card'; expect(fixture.nativeElement.textContent).toContain('Referencia de prueba'); expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba'); expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba'); + expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); + fixture.destroy(); + }); + it('separa valor y unidad y reúne descripción y notas útiles en una sola línea', () => { + const fixture = TestBed.createComponent(IndicadorKpiCard); + fixture.componentRef.setInput('title', 'Días de la toma al resultado'); + fixture.componentRef.setInput('value', 7.5); + fixture.componentRef.setInput('unit', 'días (mediana)'); + fixture.componentRef.setInput('additionalInfo', '98 mastografías; Q1 a Q3: 3 a 11 días.'); + fixture.componentRef.setInput('notes', ['La referencia de 60 días es provisional.', 'La referencia de 60 días es provisional.']); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.value').firstChild.textContent.trim()).toBe('7.5'); + expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('días (mediana)'); + expect(getComputedStyle(fixture.nativeElement.querySelector('.value span')).marginInlineStart).toBe('0.3em'); + expect(fixture.nativeElement.querySelectorAll('.additional-info')).toHaveLength(1); + expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('98 mastografías; Q1 a Q3: 3 a 11 días. La referencia de 60 días es provisional.'); fixture.destroy(); }); }); diff --git a/src/app/features/indicadores/indicador-kpi-card.ts b/src/app/features/indicadores/indicador-kpi-card.ts index f7cd85c..363d5b1 100644 --- a/src/app/features/indicadores/indicador-kpi-card.ts +++ b/src/app/features/indicadores/indicador-kpi-card.ts @@ -9,14 +9,12 @@ import { MatCardModule } from '@angular/material/card';

{{ title }}

@if (loading) { } - @if (provisional) {

Definición provisional

} @if (value !== null && value !== undefined) {

{{ value }}@if (unit) { {{ unit }} }

} @if (temporalReference) {

{{ temporalReference }}

}

{{ state }}

- @if (additionalInfo) {

{{ additionalInfo }}

} - @for (note of notes; track $index) {

{{ note }}

} + @if (informationLine) {

{{ informationLine }}

}
`, styles: ` @@ -28,8 +26,8 @@ import { MatCardModule } from '@angular/material/card'; 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); } - .provisional { border-left: 3px solid var(--issste-text-secondary); padding-left: .75rem; font-weight: 600; } .value { font: var(--mat-sys-headline-medium); } + .value span { margin-inline-start: .3em; } `, }) export class IndicadorKpiCard { @@ -38,8 +36,11 @@ export class IndicadorKpiCard { @Input() unit?: string; @Input() temporalReference?: string; @Input() loading = false; - @Input() provisional = false; @Input() notes: string[] = []; @Input() state = 'Pendiente de definición'; @Input() additionalInfo?: string; + get informationLine(): string | undefined { + const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value); + return [...new Set(lines)].join(' '); + } } diff --git a/src/app/features/indicadores/indicador-kpi-initial.spec.ts b/src/app/features/indicadores/indicador-kpi-initial.spec.ts new file mode 100644 index 0000000..c712fd5 --- /dev/null +++ b/src/app/features/indicadores/indicador-kpi-initial.spec.ts @@ -0,0 +1,121 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; + +describe('KPI búsqueda inicial del último dato visible', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + const definition = KPI_BY_DOMAIN.cacu[0]; + const periods = ['2025-S2', '2025-S1', '2024-S2']; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorKpiPanel], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadorKpiPanel); + http = TestBed.inject(HttpTestingController); + const availability = emptyAvailability('ready'); + availability.byIndicator[definition.id] = [periods[2], '2026-01', periods[0], periods[1]].map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })); + fixture.componentRef.setInput('dominio', 'cacu'); + fixture.componentRef.setInput('definition', definition); + fixture.componentRef.setInput('indicador', { id: definition.id, contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: [], titulo: definition.title }); + fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }); + fixture.componentRef.setInput('initialPresentation', true); + fixture.componentRef.setInput('availability', availability); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function request(period: string) { + return http.expectOne(r => r.url.endsWith('/datos') && r.params.get('periodos') === period); + } + function data(period: string, kind: 'visible' | 'suppressed' | 'incomplete' | 'null' = 'visible', value = 5) { + return { id: definition.id, contrato: 'C2', tipo_periodo: 'semestre', periodos: [period], + categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} }, + filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] }; + } + it('consulta secuencialmente por granularidad, detiene al visible y explica supresión posterior', () => { + const latest = request(periods[0]); http.expectNone(() => true); + expect(fixture.componentInstance.result().loading).toBe(true); + latest.flush(data(periods[0], 'suppressed')); + request(periods[1]).flush(data(periods[1])); fixture.detectChanges(); + expect(fixture.componentInstance.result().value).toBe(5); + expect(fixture.nativeElement.textContent).toContain('Último dato visible · 2025-S1'); + expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.'); + http.expectNone(() => true); + }); + it('recorre varios suprimidos sin consultar todos los periodos a la vez', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + const second = request(periods[1]); http.expectNone(() => true); + second.flush(data(periods[1], 'suppressed')); + request(periods[2]).flush(data(periods[2])); + expect(fixture.componentInstance.temporalReference).toBe('Último dato visible · 2024-S2'); + expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño'); + }); + it('agotado el inventario conserva el estado del último reporte', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + request(periods[1]).flush(data(periods[1], 'incomplete')); + request(periods[2]).flush(data(periods[2], 'null')); + expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño'); + expect(fixture.componentInstance.result().value).toBeUndefined(); + expect(fixture.componentInstance.temporalReference).toBe(periods[0]); + }); + it('acepta cero legítimo del último periodo y termina sin retroceder', () => { + request(periods[0]).flush(data(periods[0], 'visible', 0)); + expect(fixture.componentInstance.result().value).toBe(0); + expect(fixture.componentInstance.temporalReference).toBe(periods[0]); + http.expectNone(() => true); + }); + it.each(['incomplete', 'null', 'missing'] as const)('no muestra %s ni afirma supresión si encuentra un anterior', kind => { + const latest = request(periods[0]); + if (kind === 'missing') latest.flush('', { status: 404, statusText: 'Not Found' }); + else latest.flush(data(periods[0], kind)); + expect(fixture.componentInstance.result().value).toBeUndefined(); + request(periods[1]).flush(data(periods[1])); + expect(fixture.componentInstance.result().value).toBe(5); + expect(fixture.componentInstance.result().info).not.toContain('datos ocultos por tamaño'); + }); + it('un error HTTP detiene, se comunica y reintenta sin repetir datos resueltos', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + request(periods[1]).flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(fixture.componentInstance.result().state).toBe('Error de consulta'); + expect(fixture.componentInstance.result().value).toBeUndefined(); + expect(fixture.nativeElement.textContent).not.toContain('private'); + expect(fixture.nativeElement.textContent).not.toContain('datos ocultos por tamaño'); + http.expectNone(() => true); + (fixture.nativeElement.querySelector('button') as HTMLButtonElement).click(); + request(periods[1]).flush(data(periods[1])); + expect(fixture.componentInstance.result().value).toBe(5); http.expectNone(() => true); + }); + it('aplicar Todos durante la búsqueda cancela el pasado y recupera solo el último reporte', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); + const old = request(periods[1]); + fixture.componentRef.setInput('initialPresentation', false); fixture.detectChanges(); + expect(old.cancelled).toBe(true); + expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño'); + expect(fixture.componentInstance.temporalReference).toBe(periods[0]); http.expectNone(() => true); + }); + it('aplicar explícito cancela el recorrido e impide sobrescritura antigua', () => { + request(periods[0]).flush(data(periods[0], 'suppressed')); const old = request(periods[1]); + fixture.componentRef.setInput('initialPresentation', false); + fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [periods[2]] }, revision: 1 }); fixture.detectChanges(); + expect(old.cancelled).toBe(true); request(periods[2]).flush(data(periods[2], 'visible', 0)); + expect(fixture.componentInstance.result().value).toBe(0); expect(fixture.componentInstance.temporalReference).toBe(periods[2]); + http.expectNone(() => true); + }); + it('comparte el límite cuatro entre periodos y datos; cancela trabajos en cola', () => { + const latest = request(periods[0]); + const service = TestBed.inject(IndicadoresPeriodos); + const subscriptions = ['a', 'b', 'c', 'd', 'e'].map(id => service.periodos('cacu', id).subscribe()); + const inventory = http.match(r => r.url.endsWith('/periodos')); + expect(inventory).toHaveLength(3); + subscriptions[4].unsubscribe(); + latest.flush(data(periods[0], 'suppressed')); + const fourth = http.expectOne('/cacu/indicadores/d/periodos'); + http.expectNone(() => true); + inventory[0].flush({ id: 'a', periodos: [] }); + request(periods[1]).flush(data(periods[1])); + inventory.slice(1).forEach((r, i) => r.flush({ id: ['b', 'c'][i], periodos: [] })); + fourth.flush({ id: 'd', periodos: [] }); http.expectNone('/cacu/indicadores/e/periodos'); + subscriptions.forEach(subscription => subscription.unsubscribe()); + }); +}); diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 8cb546a..6a0676b 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -17,10 +17,10 @@ describe('KPI integración con autoridad global', () => { http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); }); - function load(domain: Dominio, missing = false) { + function load(domain: Dominio, missing = false, periods = ['2025-S1']) { 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: [{ tipo: 'semestre', periodo: '2025-S1' }] }); + for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) }); fixture.detectChanges(); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); } @@ -33,8 +33,9 @@ describe('KPI integración con autoridad global', () => { const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] }; fixture.componentInstance.applyFilters(); fixture.detectChanges(); } - it('TEA conserva dos preliminares y no consulta datos', () => { - expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); + it('TEA sin definiciones oculta toda la sección y no consulta datos', () => { + expect(fixture.nativeElement.querySelector('.kpi-section, #kpi-section-title, .kpi-grid')).toBeNull(); + expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(0); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); }); it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => { load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true); @@ -42,14 +43,15 @@ describe('KPI integración con autoridad global', () => { req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges(); expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']); expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private'); - expect(fixture.nativeElement.querySelector('.provisional').textContent).toBe('Definición provisional'); + expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2'))); }); it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => { load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i))); const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true); - fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(3); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0); + expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3); @@ -68,8 +70,130 @@ describe('KPI integración con autoridad global', () => { load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i))); }); - it('ID ausente bloquea sólo esa tarjeta sin sustituir ni consultar otro indicador', () => { - load('cacu', true); expect(panels()[0].result().state).toBe('Indicador no publicado'); expect(panels()[0].result().info).toContain('cacu_eu7'); + it('el catálogo gráfico no determina membresía de los KPI destacados', () => { + load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.map(d => d.id)); + expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3); const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1))); }); + it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => { + load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); + const page = fixture.componentInstance, before = panels(), state = page.filters!; + state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] }; + const snapshot = structuredClone(state), definitions = page.kpisByDomain.cacu; + try { + page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges(); + expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i])); + expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7].slice(0, count)); + expect(page.filters).toBe(state); expect(state).toEqual(snapshot); + const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null; + if (count) { + expect(grid!.children).toHaveLength(count); + expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count)); + } else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); + http.expectNone(() => true); + page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges(); + const added = requests(); expect(added).toHaveLength(0); + added.forEach((r, i) => r.flush(response(count + i))); + expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot); + } finally { page.kpisByDomain.cacu = definitions; } + }); + it('retirar un ID del catálogo gráfico conserva todos los KPI configurados', () => { + load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); + const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters); + page.catalog.set(page.catalog().slice(1)); fixture.detectChanges(); + expect(panels()).toEqual(before); expect(page.filters).toEqual(filters); + expect(panels()).toHaveLength(3); http.expectNone(() => true); + }); + it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => { + const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges(); + expect(page.catalogLoading()).toBe(true); expect(panels()).toHaveLength(3); + expect(fixture.nativeElement.textContent).toContain('Cargando catálogo'); + http.expectOne('/cacu/indicadores').flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(page.catalogError()).toBeTruthy(); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); + expect(fixture.nativeElement.querySelector('.kpi-section')).toBeTruthy(); expect(panels()).toHaveLength(3); + expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); + page.retryCatalog(); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges(); + expect(page.catalogError()).toBe(''); expect(page.catalogLoading()).toBe(false); + expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(3); + http.expectNone(() => true); + }); + it.each(['suprimido', 'nulo', 'sin filas'] as const)('KPI publicado con resultado %s conserva tarjeta y definición', scenario => { + load('cacu'); const before = panels(); + const data = response(1); + if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1; + if (scenario === 'nulo') data.filas[0]['valor'] = 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()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables'); + expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true); + }); + it('KPI publicado sin periodos con reporte mantiene sus tres tarjetas sin consultar datos', () => { + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] }))); + http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges(); + expect(panels()).toHaveLength(3); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true); + http.expectNone(r => r.url.endsWith('/datos')); + }); + it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => { + for (const domain of ['cacu', 'cama'] as const) { + load(domain); + const req = requests(); expect(req).toHaveLength(3); + req.forEach((r, i) => r.flush(response(i, domain))); + fixture.detectChanges(); + const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')]; + expect(cards).toHaveLength(3); + expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', '40.0', '7']); + expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', '%', 'días (mediana)']); + expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(['Disponible', 'Disponible', 'Disponible']); + expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ + expect.stringContaining('2025-S1'), expect.stringContaining('2 de 5'), + expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`), + ])); + expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); + } + }); + it('Aplicar equivalente termina el modo inicial sin cambiar revisión, borrador o selección', () => { + load('cacu', false, ['2025-S2', '2025-S1']); + requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); + requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); + expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); + const page = fixture.componentInstance, applied = page.filters!.applied, snapshot = structuredClone(page.filters); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); + (fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); expect(page.filters).toEqual(snapshot); + expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.temporalReference === '2025-S2')).toBe(true); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true); + load('cama'); requests().forEach((r, i) => r.flush(response(i, 'cama'))); expect(page.initialKpiPresentation).toBe(true); + load('cacu'); expect(page.initialKpiPresentation).toBe(false); expect(panels()).toHaveLength(3); + expect(panels().every(p => p.temporalReference === '2025-S2' && p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true); + }); + it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => { + load('cacu'); requests().forEach((r, i) => r.flush(response(i))); + load('cama'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); requests().forEach((r, i) => r.flush(response(i, 'cama'))); + load('cacu'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); + expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true); + }); + it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => { + load('cacu', false, ['2025-S2', '2025-S1']); + requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); + const old = requests(); expect(old).toHaveLength(3); + load('cama'); expect(old.every(r => r.cancelled)).toBe(true); + requests().forEach((r, i) => r.flush(response(i, 'cama'))); + load('cacu'); const resumed = requests(); expect(resumed).toHaveLength(3); + resumed.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i)); }); + expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); http.expectNone(() => true); + }); + it('aplicado explícito y luego Todos nunca buscan periodos anteriores', () => { + load('cacu', false, ['2025-S2', '2025-S1']); const outgoing = requests(); + apply(['2025-S1']); expect(outgoing.every(r => r.cancelled)).toBe(true); + requests().forEach((r, i) => { const data = response(i); data.filas[0]['suprimido'] = 1; r.flush(data); }); + expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true); + fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' }; + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + const latest = requests(); expect(latest).toHaveLength(3); + latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); + expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true); + }); }); diff --git a/src/app/features/indicadores/indicador-kpi-panel.ts b/src/app/features/indicadores/indicador-kpi-panel.ts index ac78114..dacc93e 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.ts @@ -1,21 +1,27 @@ import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { HttpErrorResponse } from '@angular/common/http'; -import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; import { Dominio, Indicador } from './indicadores.models'; import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory'; -import { IndicadoresService } from './indicadores.service'; +import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi'; import { PeriodAvailability, sortedPeriods } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; +interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; } + @Component({ selector: 'app-indicador-kpi-panel', - imports: [IndicadorKpiCard], + imports: [IndicadorKpiCard, MatButtonModule], template: ``, + [loading]="result().loading ?? false" [notes]="result().notes ?? []" /> + @if (result().state === 'Error de consulta') { + + }`, styles: ':host { display: block; min-width: 0; }', }) export class IndicadorKpiPanel implements OnChanges { @@ -24,46 +30,68 @@ export class IndicadorKpiPanel implements OnChanges { @Input() indicador?: Indicador; @Input() applied?: GlobalApplied; @Input() availability?: PeriodAvailability; - @Input() catalogPending = false; - private readonly service = inject(IndicadoresService); + @Input() initialPresentation = false; + private readonly queries = inject(IndicadoresKpiQueries); private readonly destroyRef = inject(DestroyRef); private readonly requests = new Subject(); private key = ''; readonly usedPeriod = signal(undefined); - readonly result = signal({ state: 'Esperando catálogo' }); - get temporalReference() { return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'); } + readonly result = signal({ state: 'Esperando catálogo' }); + get temporalReference() { + if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod(); + return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'); + } + retry() { this.requests.next(); } constructor() { - this.requests.pipe(switchMap(() => { + this.requests.pipe(switchMap((): Observable => { const applied = this.applied, definition = this.definition, domain = this.dominio; this.usedPeriod.set(undefined); - if (this.catalogPending) return of({ state: 'Esperando catálogo' }); - if (!this.indicador) return of({ state: 'Indicador no publicado', info: 'No está disponible en el catálogo: ' + definition.id }); - if (this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' }); - const compatible = filterCompatibility(applied, this.indicador.tipos_periodo); + if (!applied) return of({ state: 'Esperando filtro aplicado' }); + if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' }); + const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]); if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' }); if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' }); - let resolved = applied; + let periods: string[]; if (applied.selection.mode === 'todos') { + if (!this.indicador) return of({ state: 'Sin reportes disponibles' }); const availability = this.availability; if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true }); if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' }); - const periods = availability.byIndicator[definition.id]; - if (!periods) return of({ state: 'Error de disponibilidad' }); - const latest = sortedPeriods(periods.filter(p => p.tipo === applied.tipo).map(p => p.periodo))[0]; - if (!latest) return of({ state: 'Sin reportes disponibles' }); - resolved = { ...applied, selection: { mode: 'explicit', periodos: [latest] } }; - } - const periodos = resolved.selection.mode === 'explicit' ? resolved.selection.periodos : undefined; - this.usedPeriod.set(periodos?.[0]); - return defer(() => this.service.datos(domain, definition.id, applied.tipo, periodos)).pipe( - map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas })), - catchError(error => of({ state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta', - info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })), - startWith({ state: 'Cargando…', loading: true })); - }), takeUntilDestroyed(this.destroyRef)).subscribe(result => this.result.set(result)); + const available = availability.byIndicator[definition.id]; + if (!available) return of({ state: 'Error de disponibilidad' }); + periods = sortedPeriods(available.filter(p => p.tipo === applied.tipo).map(p => p.periodo)); + if (!periods.length) return of({ state: 'Sin reportes disponibles' }); + if (!this.initialPresentation) periods = periods.slice(0, 1); + } else periods = applied.selection.periodos; + // One request per KPI at a time: the three configured panels start only after + // the existing availability queue (concurrency four) has finished. + const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable => { + const period = periods[index]; + const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } }; + return this.queries.datos(domain, definition.id, applied.tipo, period).pipe( + map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period } as KpiDisplay)), + catchError(error => of({ period, + state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta', + info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })), + switchMap(result => { + // Network/contract transport failures stay visible and can be retried. + if (result.state === 'Error de consulta') return of(result); + if (result.state === 'Disponible' && result.value !== undefined) return of({ ...result, earlier: index > 0, + info: [result.info, index > 0 && allSuppressed ? 'Existen reportes posteriores con datos ocultos por tamaño.' : ''].filter(Boolean).join(' ') }); + const first = latest ?? result; + return index + 1 < periods.length + ? search(index + 1, first, allSuppressed && result.state === 'Dato oculto por tamaño') : of(first); + })); + }; + return search(0).pipe(startWith({ state: this.initialPresentation && applied.selection.mode === 'todos' + ? 'Buscando último dato visible…' : 'Cargando…', loading: true })); + }), takeUntilDestroyed(this.destroyRef)).subscribe(result => { + this.usedPeriod.set(result.period); + this.result.set(result); + }); } ngOnChanges() { - const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.catalogPending, this.applied && selectionKey(this.applied), + const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied && selectionKey(this.applied), this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]); if (key === this.key) return; this.key = key; diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html index 5aa1025..7a12fe8 100644 --- a/src/app/features/indicadores/indicador-period-filters.html +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -61,6 +61,6 @@ @if (!canApply) {

Selecciona al menos un periodo válido para aplicar.

} @if (!hasPending) {

Sin cambios pendientes.

} @if (hasPending) {

Hay cambios sin aplicar.

} - +

Filtro general aplicado: {{ appliedSummary }}

diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts index 1dd7369..170abce 100644 --- a/src/app/features/indicadores/indicador-period-filters.ts +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -18,6 +18,7 @@ export class IndicadorPeriodFilters implements OnChanges { @Input({ required: true }) state!: FilterState; @Input({ required: true }) types!: TipoPeriodo[]; @Input() availability?: PeriodAvailability; + @Input() initialPresentation = false; @Output() retryAvailability = new EventEmitter(); @Output() edited = new EventEmitter(); @Output() apply = new EventEmitter(); diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts index b73cbf3..06ce761 100644 --- a/src/app/features/indicadores/indicadores-global-filters.spec.ts +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -43,15 +43,26 @@ describe('D.2 integración de autoridad global y consumidores', () => { } function apply() { page.applyFilters(); fixture.detectChanges(); } - it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s antes de KPI y sin HTTP inicial', domain => { + it('Aplicar Todos inicial equivalente no cambia el filtro gráfico ni repite su HTTP', () => { + http.expectOne('/tea/indicadores').flush([]); + page.changeDominio('cacu'); load(undefined, 'cacu'); open(); respond(); + const applied = page.filters!.applied, before = panels()[0].result(); + expect(page.initialKpiPresentation).toBe(true); + apply(); + expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); + expect(applied.revision).toBe(0); expect(panels()[0].result()).toBe(before); http.expectNone(() => true); + }); + + it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s sin KPI no publicados ni HTTP inicial', domain => { if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } load(undefined, domain); expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]); - expect(sections[1].querySelectorAll('app-indicador-kpi-card')).toHaveLength(domain === 'tea' ? 2 : 3); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(domain === 'tea' ? 0 : 3); + expect(sections[domain === 'tea' ? 1 : 2].getAttribute('aria-labelledby')).toBe('graphic-section-title'); expect(page.filters!.applied.selection.mode).toBe('todos'); - expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(domain === 'tea'); http.expectNone(() => true); }); it('edición y vacío no consultan ni cambian el resultado vigente', () => { @@ -135,7 +146,9 @@ describe('D.2 integración de autoridad global y consumidores', () => { expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos'); draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load(); expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); - expect(cards()[0].visible).toBe(false); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); + http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); + http.expectNone(() => true); }); it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => { load(); draft('mes', ['2025-01']); apply(); open(); respond(); diff --git a/src/app/features/indicadores/indicadores-kpi-queries.ts b/src/app/features/indicadores/indicadores-kpi-queries.ts new file mode 100644 index 0000000..e173597 --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi-queries.ts @@ -0,0 +1,23 @@ +import { inject, Injectable } from '@angular/core'; +import { Observable, shareReplay } from 'rxjs'; +import { Dominio, IndicadorDatos, TipoPeriodo } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; +import { IndicadoresRequests } from './indicadores-requests'; + +@Injectable({ providedIn: 'root' }) +export class IndicadoresKpiQueries { + private readonly service = inject(IndicadoresService); + private readonly requests = inject(IndicadoresRequests); + // Only resolved KPI payloads survive navigation. Errors and cancelled requests reset. + private readonly cache = new Map>(); + datos(domain: Dominio, id: string, tipo: TipoPeriodo, period: string) { + const key = JSON.stringify([domain, id, tipo, period]); + let request = this.cache.get(key); + if (!request) { + request = this.requests.run(() => this.service.datos(domain, id, tipo, [period])).pipe( + shareReplay({ bufferSize: 1, refCount: true })); + this.cache.set(key, request); + } + return request; + } +} diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 70a28dc..ba69a36 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -1,10 +1,10 @@ import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; -export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; provisional?: boolean; } +export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } const definitions = (): KpiDefinition[] => [ { id: '', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, - { id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%', provisional: true }, + { id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%' }, { id: '', title: 'Días de la toma al resultado', contrato: 'C3r', unit: 'días (mediana)' }, ]; export const KPI_BY_DOMAIN: Record = { @@ -46,7 +46,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai if (!rows.every(row => count(row['n']))) return empty; const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0); if (!count(value)) return empty; - return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Pacientes con mastografía tomada en el periodo.' }; + return { state: 'Disponible', value, info: 'Conteo de pacientes únicos en el periodo.' }; } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index a63dc8c..7c0c764 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -62,6 +62,9 @@ export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boo @Injectable({ providedIn: 'root' }) export class IndicadoresMemory { + private readonly manuallyApplied = new Set(); + initialKpiPresentation(domain: Dominio) { return !this.manuallyApplied.has(domain); } + finishInitialKpiPresentation(domain: Dominio) { this.manuallyApplied.add(domain); } private readonly pinnedIndicators = signal>(new Set()); isPinned(domain: Dominio, indicador: string) { return this.pinnedIndicators().has(JSON.stringify([domain, indicador])); diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index 82670bc..c77b088 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -96,6 +96,7 @@ describe('UX-04 navegación Angular', () => { (harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges(); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); const url = TestBed.inject(Router).url; + http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); http.verify(); TestBed.resetTestingModule(); harness = await setup(); const restarted = await harness.navigateByUrl(url, IndicadoresPage); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 5a68abb..73e9689 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -14,25 +14,24 @@

Filtros generales de {{ domainLabels[dominio] }}

La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.

-
} -
-

Indicadores destacados{{ dominio === 'tea' ? ' — Vista preliminar' : '' }}

-

{{ dominio === 'tea' ? 'Muestra visual de TEA. Las definiciones y fuentes de estos indicadores están pendientes.' : 'Todos con reporte muestra el último periodo disponible de cada indicador. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.' }}

-
- @if (dominio === 'tea') { - @for (preview of kpiPreviewsByDomain.tea; track preview.id) { } - } @else { - @for (definition of kpisByDomain[dominio]; track dominio + ':' + definition.id) { + @let kpis = availableKpis; + @if (kpis.length) { +
+

Indicadores destacados

+

La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.

+
+ @for (definition of kpis; track dominio + ':' + definition.id) { + [applied]="filters?.applied" [availability]="availability()" [initialPresentation]="initialKpiPresentation" /> } - } -
-
+
+
+ }
diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index 292f360..fe52754 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -21,7 +21,7 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; } .search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right; overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); } -@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } } @container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } nav { @@ -54,4 +54,4 @@ nav a[aria-current='page'] { .global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; } -@container dashboard (min-width: 1000px) { .kpi-grid:has(app-indicador-kpi-panel) { grid-template-columns: repeat(3, minmax(0, 1fr)); } } +@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 4b0f265..0dc65d8 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -32,7 +32,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); }); - afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + afterEach(() => { http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function load(items: Indicador[] = [item, second], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } @@ -43,34 +43,26 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } - it.each(['tea'] as const)('D.1 muestra dos KPI pendientes propios de %s fuera del catálogo', domain => { - if (domain !== 'tea') { - const initial = http.expectOne('/tea/indicadores'); - page.changeDominio(domain); expect(initial.cancelled).toBe(true); - } - fixture.detectChanges(); - const section = fixture.nativeElement.querySelector('.kpi-section') as HTMLElement; - expect(section.dataset['domain']).toBe(domain); - expect(section.querySelector('h2')?.textContent).toBe('Indicadores destacados — Vista preliminar'); - expect(section.textContent).toContain('Muestra visual de ' + page.domainLabels[domain]); - const kpis = section.querySelectorAll('app-indicador-kpi-card'); - expect(Array.from(kpis).map(kpi => kpi.querySelector('h3')?.textContent)).toEqual(['Indicador destacado 1', 'Indicador destacado 2']); - expect(Array.from(kpis).map(kpi => kpi.querySelector('.kpi-state')?.textContent)).toEqual(['Pendiente de definición', 'Pendiente de definición']); - expect(section.querySelector('.value, button, input, app-plotly-chart')).toBeNull(); - expect(section.textContent).not.toContain('publicados'); - load([], domain); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); - http.expectNone(() => true); + it('KPI-DYNAMIC TEA no deja sección, encabezado, tarjetas ni grid residual', () => { + load(); + expect(fixture.nativeElement.querySelector('.kpi-section, #kpi-section-title, .kpi-grid, app-indicador-kpi-card')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain('Indicadores destacados'); + http.expectNone(r => r.url.endsWith('/datos')); }); - it('D.1 conserva KPI durante carga, error, reintento y catálogo vacío sin HTTP propio', () => { + it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { fixture.detectChanges(); - const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')); - expect(kpis).toHaveLength(2); + expect(page.catalogLoading()).toBe(true); + expect(fixture.nativeElement.textContent).toContain('Cargando catálogo'); + expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); http.expectOne('/tea/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); - expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis); - page.retryCatalog(); fixture.detectChanges(); - expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis); - load([]); expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis); - expect(fixture.nativeElement.querySelector('.catalog-count')).toBeNull(); http.expectNone(() => true); + expect(page.catalogError()).toBeTruthy(); + expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); + expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); + page.retryCatalog(); fixture.detectChanges(); load([]); + expect(page.catalogLoading()).toBe(false); expect(page.catalogError()).toBe(''); + expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); + expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); + http.expectNone(() => true); }); it('D.1 separa secciones y conserva tarjetas, orden, identidades y figuras dentro del grid', () => { load(); const before = cards(); @@ -79,7 +71,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(grid.children).toHaveLength(2); expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true); const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; - expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']); + expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right'); toggle(0); toggle(1); flushAll(); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 3375ef2..90fbfdc 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -13,19 +13,18 @@ import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory } from './indicadores-memory'; +import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; -import { IndicadorKpiCard } from './indicador-kpi-card'; import { indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiCard, IndicadorKpiPanel, IndicadorPeriodFilters], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -171,10 +170,8 @@ export class IndicadoresPage { readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly kpisByDomain = KPI_BY_DOMAIN; kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } - // TEA has no approved KPI definitions; its previews never request data. - readonly kpiPreviewsByDomain: { tea: readonly { id: string; title: string }[] } = { - tea: [{ id: 'preview-1', title: 'Indicador destacado 1' }, { id: 'preview-2', title: 'Indicador destacado 2' }], - }; + get availableKpis() { return this.kpisByDomain[this.dominio]; } + get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); } private readonly catalogRequests = new Subject(); readonly catalog = signal([]); readonly searchQuery = signal(''); @@ -207,7 +204,12 @@ export class IndicadoresPage { filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); } applyFilters() { this.evaluateVisibility(); - if (!this.filters || !applyGlobal(this.filters, this.filterTypes())) return; + if (!this.filters) return; + const draft = this.filters.editors[this.filters.tipo]?.draft; + if (!draft || !validDraft(draft, this.filters.tipo, this.filterTypes())) return; + const initial = this.initialKpiPresentation; + this.memory.finishInitialKpiPresentation(this.dominio); + if (!applyGlobal(this.filters, this.filterTypes()) && !initial) return; this.filtersEdited(); this.changeDetector.markForCheck(); } diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts index 6256449..a02b251 100644 --- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -56,8 +56,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { expect(fixture.componentInstance.filters!.applied.revision).toBe(0); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); }); - it('supresión del último no busca periodos anteriores ni sustituye cifras', () => { + it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => { load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2'])); + const initial = http.match(r => r.url.endsWith('/datos')); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + expect(initial.every(r => r.cancelled)).toBe(true); const requests = flushDatos('cacu', true); expect(requests.every(r => r.request.params.get('periodos') === '2026-S2')).toBe(true); expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.result().value === undefined)).toBe(true); diff --git a/src/app/features/indicadores/indicadores-periodos.ts b/src/app/features/indicadores/indicadores-periodos.ts index fc4031b..f5fca93 100644 --- a/src/app/features/indicadores/indicadores-periodos.ts +++ b/src/app/features/indicadores/indicadores-periodos.ts @@ -3,6 +3,7 @@ import { HttpClient } from '@angular/common/http'; import { catchError, from, map, mergeMap, Observable, of, shareReplay, toArray } from 'rxjs'; import { Dominio, Indicador, parsePeriodos, requireDominio, TipoPeriodo } from './indicadores.models'; import { httpMessage } from './indicadores-http'; +import { IndicadoresRequests } from './indicadores-requests'; export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; } export interface PeriodAvailability { @@ -39,6 +40,7 @@ export function parseAvailability(value: unknown, id: string): AvailablePeriod[] @Injectable({ providedIn: 'root' }) export class IndicadoresPeriodos { private readonly http = inject(HttpClient); + private readonly requests = inject(IndicadoresRequests); // Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached. private readonly cache = new Map>(); periodos(domain: Dominio, id: string) { @@ -46,7 +48,7 @@ export class IndicadoresPeriodos { const key = JSON.stringify([dominio, id]); let request = this.cache.get(key); if (!request) { - request = this.http.get(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`).pipe( + request = this.requests.run(() => this.http.get(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`)).pipe( map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true })); this.cache.set(key, request); } diff --git a/src/app/features/indicadores/indicadores-requests.ts b/src/app/features/indicadores/indicadores-requests.ts new file mode 100644 index 0000000..f96a7db --- /dev/null +++ b/src/app/features/indicadores/indicadores-requests.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@angular/core'; +import { defer, finalize, Observable, Subscription } from 'rxjs'; + +// Shared by availability and KPI data; figure requests retain their existing lifecycle. +@Injectable({ providedIn: 'root' }) +export class IndicadoresRequests { + private active = 0; + private readonly queue: (() => void)[] = []; + run(request: () => Observable): Observable { + return new Observable(subscriber => { + let started = false; + let subscription: Subscription | undefined; + const start = () => { + started = true; + this.active++; + subscription = defer(request).pipe(finalize(() => { + this.active--; + this.drain(); + })).subscribe(subscriber); + }; + if (this.active < 4) start(); + else this.queue.push(start); + return () => { + if (!started) { + const index = this.queue.indexOf(start); + if (index >= 0) this.queue.splice(index, 1); + } + subscription?.unsubscribe(); + }; + }); + } + private drain() { + while (this.active < 4 && this.queue.length) this.queue.shift()!(); + } +} From 11337679dc530a8b362f5262761b8a4af9ef54d7 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 15 Oct 2026 13:45:59 -0600 Subject: [PATCH 19/51] =?UTF-8?q?feat(indicadores):=20mejorar=20presentaci?= =?UTF-8?q?=C3=B3n=20y=20legibilidad=20de=20figuras=20multidominio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicador-catalog-card.spec.ts | 41 ++++ .../indicadores/indicador-catalog-card.ts | 12 +- .../indicadores/indicador-figure-card.html | 19 +- .../indicadores/indicador-figure-card.scss | 19 ++ .../indicadores/indicador-figure-card.spec.ts | 78 +++++- .../indicadores/indicador-figure-card.ts | 16 +- .../indicador-figure-panel.spec.ts | 80 ++++++ .../indicadores/indicador-figure-panel.ts | 50 +++- .../indicadores-axis-labels.spec.ts | 230 ++++++++++++++++++ .../indicadores/indicadores-axis-labels.ts | 191 +++++++++++++++ .../indicadores-figure-labels.spec.ts | 28 +++ .../indicadores/indicadores-figure-labels.ts | 17 ++ .../indicadores/indicadores-page.spec.ts | 4 +- .../indicadores-visual-profile.spec.ts | 228 +++++++++++++++++ .../indicadores/indicadores-visual-profile.ts | 31 +++ .../indicadores/indicadores.presentation.ts | 134 +++++++++- src/app/shared/plotly/plotly-chart.spec.ts | 26 ++ src/app/shared/plotly/plotly-chart.ts | 18 +- 18 files changed, 1197 insertions(+), 25 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-axis-labels.spec.ts create mode 100644 src/app/features/indicadores/indicadores-axis-labels.ts create mode 100644 src/app/features/indicadores/indicadores-figure-labels.spec.ts create mode 100644 src/app/features/indicadores/indicadores-figure-labels.ts create mode 100644 src/app/features/indicadores/indicadores-visual-profile.spec.ts create mode 100644 src/app/features/indicadores/indicadores-visual-profile.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index 0327366..1427933 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -32,6 +32,47 @@ describe('UX-06E.D.2.1 selector de representación', () => { function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); } function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } + it.each(['C1', 'C2', 'C3r'])('UX-07A omite IDs y contrato %s y conserva título y contador', contrato => { + fixture.componentRef.setInput('indicador', { id: 'K05_eeg_20_minutos', titulo: 'EEG con ≥ 20 min de registro', contrato, + figuras: ['fig_c1_grupos', 'fig_c1_puntos'], tipos_periodo: ['semestre'] }); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro'); + expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull(); + expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); + // The internal panel heading is deliberately visually hidden and retains identity. + const copy = fixture.nativeElement.cloneNode(true) as HTMLElement; + copy.querySelectorAll('.visually-hidden').forEach(node => node.remove()); + expect(copy.textContent).not.toMatch(/K05_eeg_20_minutos|Contrato|fig_c1_/); + expect(fixture.componentInstance.indicador.id).toBe('K05_eeg_20_minutos'); + expect(fixture.componentInstance.indicador.contrato).toBe(contrato); + http.expectNone(() => true); + }); + it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => { + fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); + expect(select().options.map(option => [option.value, option.viewValue])).toEqual([ + ['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], + ]); + http.expectNone(() => true); + open(); request('fig_c1_grupos').flush({ data: [], layout: {} }); + for (const [id, label] of [ + ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ['fig_c9_futura', 'Representación 5'], + ]) { + select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges(); + const pending = request(id); + expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id); + expect(pending.request.params.get('tema')).toBe('claro'); + expect(pending.request.params.get('periodos')).toBe('2025-S1'); + pending.flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(fixture.componentInstance.selectedFigure).toBe(id); + expect(TestBed.inject(IndicadoresMemory).figure('cacu', 'i')).toBe(id); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`); + } + http.expectNone(() => true); + }); it('una opción publicada está deshabilitada y sólo consulta esa figura', () => { fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 4fc63e5..f35a152 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -8,6 +8,8 @@ import { Dominio, Indicador, Tema } from './indicadores.models'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; @Component({ selector: 'app-indicador-catalog-card', @@ -17,7 +19,6 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';

{{ indicador.titulo }}

-

{{ indicador.id }}

- + @if (selectedFigure) { Representación gráfica - @for (figure of indicador.figuras; track figure) { {{ figure }} } + @for (figure of indicador.figuras; track figure) { {{ figureDisplayName(figure, indicador.figuras) }} }
@for (figure of [selectedFigure]; track panelIdentity(figure)) { - + }
} @else {

El indicador no tiene figuras disponibles.

} @@ -53,7 +54,6 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; .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; } - .indicator-id { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } .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; } @@ -65,11 +65,13 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; `, }) export class IndicadorCatalogCard implements OnChanges { + readonly figureDisplayName = figureDisplayName; @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() pinned = false; + @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; readonly pinChanged = output(); @ViewChild('visibilityRegion') visibilityRegion?: ElementRef; readonly host = inject>(ElementRef); diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index e295488..7378b91 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -31,13 +31,28 @@

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

}

-

Figura: {{ figuraId }}

+

Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}

} @else {

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

} @if (chartFigure) {
- + + @if (state.footnotes?.length) { +
+ @for (note of state.footnotes; track $index) {

{{ note }}

} +
+ } + @if (state.categoryLabels?.length) { +
+ Nombres completos de las categorías +
    + @for (label of state.categoryLabels; track $index) { +
  • {{ label.abbreviated }}: {{ label.original }}
  • + } +
+
+ }
} diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index ac364c4..c62cf22 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -28,6 +28,25 @@ .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } +.methodological-footnotes { + padding: .75rem 1rem 1rem; + min-width: 0; + max-width: 100%; + box-sizing: border-box; + font: var(--mat-sys-body-small); + font-family: var(--issste-font-body); + font-size: .875rem; + color: var(--issste-text-secondary); + line-height: 1.5; +} +.dark .methodological-footnotes { color: var(--mat-sys-outline); } +.methodological-footnotes p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } +.methodological-footnotes p + p { margin-top: .75rem; } +.category-labels { padding: 0 1rem 1rem; overflow-wrap: anywhere; font: var(--mat-sys-body-small); line-height: 1.5; } +.category-labels summary { cursor: pointer; min-height: 44px; align-content: center; } +.category-labels summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } +.category-labels ul { margin: .25rem 0 0; padding-left: 1.25rem; } +.category-labels li + li { margin-top: .5rem; } .figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } .skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 80640b2..8df5a30 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -46,6 +46,57 @@ describe('IndicadorFigureCard', () => { state({ status: 'ready', figure: original, presentationFigure: copy }); return copy; } + it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => { + fixture.componentRef.setInput('dominio', dominio); + const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; + const notes = ['Fuente: A & B\nSegunda línea', '', '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.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes); + expect(section.querySelector('img, script, a')).toBeNull(); + expect(section.previousElementSibling?.tagName).toBe('APP-PLOTLY-CHART'); + expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull(); + expect(section.nextElementSibling?.classList.contains('category-labels')).toBe(true); + for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) { + state({ status }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + } + state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva'); + }); + it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => { + const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} }; + state({ status: 'ready', figure: original, presentationFigure: original, minimumPlotWidth: 598 }); await settle(); + const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement; + const host = chart.querySelector('.plot'); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px'); + expect(chart.querySelector('.plot-viewport')!.getAttribute('tabindex')).toBe('0'); + state({ status: 'loading' }); await settle(); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px'); + state({ status: 'ready', figure: original, presentationFigure: original }); await settle(); + expect(chart.style.getPropertyValue('--plot-min-width')).toBe(''); + expect(chart.querySelector('.plot')).toBe(host); expect(original.data[0]['y']).toEqual([0, null, 20]); + }); + it('UX-07C ofrece nombres completos en un details nativo sin rerenderizar Plotly ni ocultar notas', async () => { + const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; + const copy = presentationFigure(original, { indicador: 'i1', figura: 'fig_c1_puntos', tema: 'claro' }); + state({ status: 'ready', figure: original, presentationFigure: copy, + categoryLabels: [{ axis: 'x', abbreviated: 'Fármaco…', original: 'Fármaco de riesgo para el neurodesarrollo' }], + footnotes: ['Nota metodológica siempre visible'] }); await settle(); + const details = fixture.nativeElement.querySelector('details') as HTMLDetailsElement; + const summary = details.querySelector('summary')!; + expect(summary.textContent).toContain('Nombres completos'); expect(details.open).toBe(false); + expect(details.querySelector('li')!.textContent).toContain('Fármaco de riesgo para el neurodesarrollo'); + const plot = fixture.nativeElement.querySelector('.plot'), calls = react.mock.calls.length; + summary.focus(); summary.click(); fixture.detectChanges(); await settle(); + expect(details.open).toBe(true); expect(document.activeElement).toBe(summary); + expect(react).toHaveBeenCalledTimes(calls); expect(fixture.nativeElement.querySelector('.plot')).toBe(plot); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').closest('details')).toBeNull(); + state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.category-labels')).toBeNull(); + expect(fixture.nativeElement.querySelector('.plot').closest('[hidden]')).not.toBeNull(); + }); it('muestra carga, error y emite reintento sin coordinar HTTP', () => { state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true'); @@ -65,7 +116,7 @@ describe('IndicadorFigureCard', () => { fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles'); }); - it('presenta título del JSON, identificación secundaria y conserva datos incluso si Plotly los muta', async () => { + it('presenta título del JSON, nombre amigable y conserva datos incluso si Plotly los muta', async () => { const original: PlotlyFigure = { data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }], layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] }, @@ -79,7 +130,8 @@ describe('IndicadorFigureCard', () => { const copy = ready(original); await settle(); expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado'); - expect(fixture.nativeElement.querySelector('.figure-id').textContent).toContain('fig_c1_puntos'); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe('Figura: Puntos'); + expect(fixture.nativeElement.textContent).not.toContain('fig_c1_puntos'); expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy); expect(JSON.stringify(original)).toBe(snapshot); expect(copy.data).toEqual(original.data); @@ -94,6 +146,19 @@ describe('IndicadorFigureCard', () => { await settle(); expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles'); }); + it('UX-07B representa pies como texto seguro, sin duplicación ni notas genéricas', async () => { + const figure = { data: [{ y: [42] }], layout: {} }; + const note = 'Primera línea\n\nAviso completo'; + state({ status: 'ready', figure, presentationFigure: figure, footnotes: [note] }); await settle(); + const notes = fixture.nativeElement.querySelector('.methodological-footnotes'); + expect(notes.textContent).toBe(note); expect(notes.querySelector('img')).toBeNull(); + expect(fixture.nativeElement.querySelectorAll('.methodological-footnotes p')).toHaveLength(1); + expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.showNotes).toBe(false); + state({ status: 'loading' }); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + state({ status: 'ready', figure, presentationFigure: figure, footnotes: [] }); await settle(); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + }); it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => { fixture.componentRef.setInput('dominio', dominio); state({ status: 'loading' }); @@ -174,6 +239,15 @@ describe('IndicadorFigureCard', () => { expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls')) .toBe(fixture.nativeElement.querySelector('.methodology-detail').id); }); + it.each([ + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ])('UX-07D.1 identifica %s con el nombre %s en la tarjeta de figura', (id, label) => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', figuras: [id] }); + fixture.componentRef.setInput('figuraId', id); + ready({ data: [], layout: {} }); + expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`); + }); it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => { fixture.componentRef.setInput('figuraId', figura); if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' }); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index b5eb099..fbfdd16 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -5,6 +5,8 @@ import { MatCardModule } from '@angular/material/card'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; import { figureTitle } from './indicadores.presentation'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { CategoryLabel } from './indicadores-axis-labels'; import { figureIdentity, identityElementId } from './indicadores-identities'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; @@ -13,6 +15,9 @@ export interface FigureState { status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; + footnotes?: readonly string[]; + categoryLabels?: readonly CategoryLabel[]; + minimumPlotWidth?: number; message?: string; } @@ -49,9 +54,13 @@ export class IndicadorFigureCard { // Keep the mounted host's last presentation only. The template hides it whenever // it is not the current result; this is neither applied state nor a results cache. chartFigure?: PlotlyFigure; + chartMinimumWidth?: number; @Input({ required: true }) set state(value: FigureState) { this.currentState = value; - if (value.status === 'ready') this.chartFigure = value.presentationFigure; + if (value.status === 'ready') { + this.chartFigure = value.presentationFigure; + this.chartMinimumWidth = value.minimumPlotWidth; + } } get state() { return this.currentState; } @Input() selected?: Indicador; @@ -59,6 +68,10 @@ export class IndicadorFigureCard { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) tema!: Tema; readonly retry = output(); + readonly plotWidthChanged = output(); + reportPlotWidth(width: unknown) { + if (typeof width === 'number') this.plotWidthChanged.emit(width); + } readonly methodologyExpanded = signal(false); get methodologyId(): string { return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology'; @@ -83,6 +96,7 @@ export class IndicadorFigureCard { } readonly hasNoVisibleValues = hasNoVisibleValues; readonly figureTitle = figureTitle; + readonly figureDisplayName = figureDisplayName; get interpretation(): readonly string[] { const contract = this.contract; diff --git a/src/app/features/indicadores/indicador-figure-panel.spec.ts b/src/app/features/indicadores/indicador-figure-panel.spec.ts index 3badbd6..570d589 100644 --- a/src/app/features/indicadores/indicador-figure-panel.spec.ts +++ b/src/app/features/indicadores/indicador-figure-panel.spec.ts @@ -10,6 +10,7 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { figure?: PlotlyFigure; } @@ -47,6 +48,60 @@ describe('IndicadorFigurePanel', () => { function load() { fixture.detectChanges(); } function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => { + fixture.componentRef.setInput('dominio', 'cama'); + fixture.componentRef.setInput('indicador', { ...catalog[0], figuras: ['fig_c2_barras'], contrato: 'C2' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_barras'); + const request = () => http.expectOne(req => req.url.includes('/cama/indicadores/') && req.url.includes('/figuras/')); + const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }], + layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22, + xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } }); + load(); request().flush(response('Nota vigente')); fixture.detectChanges(); + for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); + for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width); + expect(page.result().footnotes).toEqual(['Nota vigente']); http.expectNone(() => true); + } + page.requestFigure(); const old = request(); fixture.detectChanges(); + expect(page.result().footnotes).toBeUndefined(); + expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + expect(old.cancelled).toBe(true); + const current = request(); current.flush(response('Nota del periodo actual')); fixture.detectChanges(); + expect(page.result().footnotes).toEqual(['Nota del periodo actual']); + expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota del periodo actual'); + http.expectNone(() => true); + }); + + it('UX-07C alterna etiquetas desde el original sin HTTP, conserva el host y restaura hover/categorías', () => { + const label = 'Fármaco de riesgo para el neurodesarrollo'; + const received: PlotlyFigure = { data: [{ type: 'bar', x: [label], y: [0], customdata: [null], + hovertemplate: '%{x}
%{y:.1f}%' }], layout: { xaxis: { type: 'category' } } }; + load(); figure().flush(received); fixture.detectChanges(); + const before = structuredClone(received), host = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + expect(page.result().categoryLabels?.[0].original).toBe(label); + expect(fixture.nativeElement.querySelector('.category-labels')).not.toBeNull(); + page.updatePlotWidth(1400); fixture.detectChanges(); + expect(page.result().categoryLabels).toEqual([]); + const unchanged = page.result(); + for (const width of [1400.7, 1399, 1350, 0, NaN]) page.updatePlotWidth(width); + expect(page.result()).toBe(unchanged); + page.updatePlotWidth(320); fixture.detectChanges(); + expect(page.result().categoryLabels).toHaveLength(1); + http.expectNone(() => true); + for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); + http.expectNone(() => true); + expect(page.result().figure).toEqual(before); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(host); + if (profile === BASE_VISUAL_PROFILE) { + expect(page.result().presentationFigure?.data).toEqual(before.data); + expect(page.result().categoryLabels).toEqual([]); + } else expect(page.result().categoryLabels).toHaveLength(1); + } + expect(received).toEqual(before); + }); + it.each([ ['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']], ['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']], @@ -132,6 +187,31 @@ describe('IndicadorFigurePanel', () => { expect(all.request.params.has('periodos')).toBe(false); all.flush({ data: [], layout: {} }); }); + it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => { + load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 }; + figure().flush(received); fixture.detectChanges(); + const base = structuredClone(page.result().presentationFigure); + const original = page.result().figure; + const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; + const applied = page.applied; + fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); + expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); + expect(page.result().figure).toBe(original); expect(page.applied).toBe(applied); + expect(page.result().presentationFigure?.data).toEqual(received.data); + expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); + http.expectNone(() => true); + fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); + expect(page.result().presentationFigure).toEqual(base); + expect(page.result().figure).toEqual(received); http.expectNone(() => true); + }); + it('UX-07B cambiar perfil durante carga no cancela ni inicia solicitudes', () => { + load(); const pending = figure(); + fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); + expect(pending.cancelled).toBe(false); http.expectNone(() => true); + pending.flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); + http.expectNone(() => true); + }); it('cancela figuras al cambiar tema rápidamente', () => { load(); const old = figure(); diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index b605e7b..c1c3b6a 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -1,10 +1,11 @@ -import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; +import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { presentationFigure } from './indicadores.presentation'; +import { figurePresentation } from './indicadores.presentation'; +import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory'; import { httpMessage } from './indicadores-http'; @@ -18,7 +19,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities';

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

Filtro general aplicado: {{ appliedSummary }}

+ [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
`, styles: ` @@ -38,6 +39,9 @@ export class IndicadorFigurePanel implements OnChanges { @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; + @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; + private readySelection?: FigureSelection; + private plotWidth?: number; private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>(); @@ -49,7 +53,7 @@ export class IndicadorFigurePanel implements OnChanges { constructor() { this.figureRequests.pipe(switchMap(request => request ? defer(() => this.service.figura(request.selection)).pipe( - map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, request.selection) }) as FigureState), + map(figure => this.present(figure, request.selection)), catchError(error => of({ status: 'error', message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 @@ -57,17 +61,43 @@ export class IndicadorFigurePanel implements OnChanges { ? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''), } as FigureState)), startWith({ status: 'loading' } as FigureState), - map(state => ({ state, revision: request.revision, generation: request.generation }))) - : of({ state: { status: 'idle' } as FigureState, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef)) - .subscribe(({ state, revision, generation }) => { - if (generation === this.generation && revision === this.applied?.revision) this.result.set(state); + map(state => ({ state, selection: request.selection, revision: request.revision, generation: request.generation }))) + : of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef)) + .subscribe(({ state, selection, revision, generation }) => { + if (generation === this.generation && revision === this.applied?.revision) { + if (state.status === 'ready') this.readySelection = selection; + this.result.set(state); + } }); } - ngOnChanges() { + private present(figure: NonNullable, selection: FigureSelection): FigureState { + const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth); + return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes, + categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth }; + } + updatePlotWidth(width: number) { + if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return; + this.plotWidth = Math.floor(width); + const state = this.result(); + if (this.visualProfile.axisLabels?.enabled && state.status === 'ready' && state.figure && this.readySelection) { + const next = this.present(state.figure, this.readySelection); + // A width change within the same label budget must not hide/repaint an + // equivalent graph (for example when only the scrollbar gutter changes). + if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth]) + !== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth])) this.result.set(next); + } + } + ngOnChanges(changes: SimpleChanges) { const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); this.titleId = identityElementId(identity) + '-title'; const key = this.requestKey(); - if (key === this.currentKey) return; + if (key === this.currentKey) { + const state = this.result(); + if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) { + this.result.set(this.present(state.figure, this.readySelection)); + } + return; + } if (this.visible) this.requestFigure(); else { // Cancel stale work immediately but retain the panel and its Plotly host. diff --git a/src/app/features/indicadores/indicadores-axis-labels.spec.ts b/src/app/features/indicadores/indicadores-axis-labels.spec.ts new file mode 100644 index 0000000..24ace9f --- /dev/null +++ b/src/app/features/indicadores/indicadores-axis-labels.spec.ts @@ -0,0 +1,230 @@ +import { abbreviateCategories, categoryMinimumWidth } from './indicadores-axis-labels'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { figurePresentation } from './indicadores.presentation'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' }; +const long = 'Fármaco de riesgo para el neurodesarrollo'; +const hover = '2025-S1
%{x}
%{y:.1f}% (%{customdata[0]} de %{customdata[1]})'; +function source(): PlotlyFigure { + return { data: [{ type: 'scatter', mode: 'markers', x: [long, 'Otra'], y: [20, null], + customdata: [[2, 10], [null, 'SUPRIMIDO']], error_y: { array: [5, null] }, hovertemplate: hover, + future: { keep: true } }], layout: { xaxis: { type: 'category', categoryorder: 'array', categoryarray: [long, 'Otra'], future: 7 }, + yaxis: { range: [0, 100] }, margin: { b: 150 }, annotations: [{ text: 'Nota desconocida', y: -0.3 }] }, + config: { displaylogo: false }, future: { keep: [null, 0] } }; +} +const present = (figure: PlotlyFigure) => figurePresentation(figure, selection, READABLE_VISUAL_PROFILE); +function freezeDeep(value: unknown) { + if (value && typeof value === 'object') { Object.values(value).forEach(freezeDeep); Object.freeze(value); } +} + +describe('UX-07C etiquetas de ejes', () => { + it('UX-07D reserva espacio para las cinco áreas cortas sin perder ticks ni modificar observaciones', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', name: 'Desarrollo adecuado', x: ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo'], y: [20, null, 0, 40, 60] }], + layout: { xaxis: {}, margin: { l: 60, r: 30 } } }; + const before = structuredClone(figure); freezeDeep(figure); + const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253); + expect(result.minimumPlotWidth).toBeGreaterThan(253); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', tickmode: 'linear', dtick: 1, automargin: true }); + expect(result.figure.data).toEqual(before.data); expect(figure).toEqual(before); + expect(figurePresentation(figure, selection, BASE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined(); + expect(figurePresentation(figure, { ...selection, dominio: 'cacu' }, READABLE_VISUAL_PROFILE, 253).minimumPlotWidth).toBeUndefined(); + expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, result.minimumPlotWidth).minimumPlotWidth).toBe(result.minimumPlotWidth); + }); + it('UX-07D mantiene todos los pares semestre/área con un mínimo estable y sin ticks simples', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', x: [Array(5).fill('2025-S1').concat(Array(5).fill('2025-S2')), + ['Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo', 'Cognoscitivo', 'Lingüístico', 'Físico', 'Socioemocional', 'Adaptativo']], y: Array(10).fill(null) }], layout: { xaxis: {} } }; + const before = structuredClone(figure); + const result = figurePresentation(figure, { ...selection, figura: 'fig_c2_apiladas' }, READABLE_VISUAL_PROFILE, 253); + expect(result.minimumPlotWidth).toBeGreaterThan(253); + expect(result.figure.layout['xaxis']).toEqual({}); expect(result.figure.data).toEqual(before.data); + expect(figure).toEqual(before); + }); + it('UX-07D no reserva ancho en estructuras desconocidas, ejes numéricos, notas sin reconocer o dimensiones fijas', () => { + const base: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: { xaxis: { type: 'category' } } }; + for (const layout of [{ width: 700 }, { autosize: false }, { xaxis2: {} }, { annotations: [{ text: 'Advertencia desconocida' }] }, { xaxis: { type: 'date' } }, { template: { layout: { xaxis: { tickvals: ['A'] } } } }]) { + expect(categoryMinimumWidth({ ...base, layout: { ...base.layout, ...layout } })).toBeUndefined(); + } + expect(categoryMinimumWidth({ ...base, data: [{ type: 'box', x: ['A', 'B', 'C'], y: [0, null, 20] }] })).toBeUndefined(); + expect(categoryMinimumWidth({ ...base, frames: [{}] })).toBeUndefined(); + }); + it('deja las etiquetas cortas intactas y abrevia por palabras sólo las extensas', () => { + expect([...abbreviateCategories(['Corta', long], 22)]).toEqual([['Corta', 'Corta'], [long, 'Fármaco de riesgo…']]); + const result = present(source()); + expect(result.figure.layout['xaxis']).toMatchObject({ tickvals: [long, 'Otra'], ticktext: ['Fármaco de riesgo…', 'Otra'], + categoryarray: [long, 'Otra'], categoryorder: 'array', future: 7, automargin: true }); + expect(result.categoryLabels).toEqual([{ axis: 'x', original: long, abbreviated: 'Fármaco de riesgo…' }]); + }); + it('sin etiquetas extensas no crea ticks ni cambia el hover', () => { + const figure = source(); figure.data[0]['x'] = ['Corta', 'Otra']; figure.layout['xaxis'] = { type: 'category' }; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).categoryLabels).toEqual([]); + }); + it('conserva etiquetas completas cuando hay ancho suficiente y abrevia al estrechar la misma figura', () => { + const figure = source(), before = structuredClone(figure); + const spacious = figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 1400); + expect(spacious.categoryLabels).toEqual([]); expect(spacious.figure.data).toEqual(before.data); + expect(spacious.figure.layout['xaxis']).toEqual(before.layout['xaxis']); + expect(figurePresentation(figure, selection, READABLE_VISUAL_PROFILE, 320).categoryLabels).toHaveLength(1); + expect(figurePresentation(figure, selection, { axisLabels: { enabled: true, preserveWhenFits: false } }, 1400).categoryLabels).toHaveLength(1); + expect(figure).toEqual(before); + }); + it('acota la ampliación tipográfica opcional en tarjetas estrechas sin cambiar la fuente original ni el perfil amplio', () => { + const figure = source(); figure.layout['font'] = { size: 13, future: true }; + const profile = { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE }; + expect(figurePresentation(figure, selection, profile, 270).figure.layout['font']).toMatchObject({ size: 12, future: true }); + expect(figurePresentation(figure, selection, profile, 646).figure.layout['font']).toMatchObject({ size: 15 }); + expect(figure.layout['font']).toEqual({ size: 13, future: true }); + }); + it('las colisiones y las abreviaciones iguales a otra categoría vuelven al original', () => { + const a = 'Fármaco de riesgo para el neurodesarrollo', b = 'Fármaco de riesgo para otra condición'; + const labels = abbreviateCategories([a, b, 'Fármaco de riesgo…'], 22); + expect([...labels.values()]).toEqual([a, b, 'Fármaco de riesgo…']); + expect(new Set(labels.values()).size).toBe(labels.size); + }); + it('deduplica la correspondencia sin retirar puntos duplicados', () => { + const figure = source(); figure.data[0]['x'] = [long, long]; + const result = present(figure); + expect(result.categoryLabels).toHaveLength(1); + expect(result.figure.data[0]['x']).toEqual([long, long]); + expect((result.figure.layout['xaxis'] as Record)['tickvals']).toEqual([long, 'Otra']); + }); + it('conserva grafemas Unicode, acentos, símbolos y palabras indivisibles', () => { + const value = 'Área 👩🏽‍⚕️ y comunicación extensa'; + expect(abbreviateCategories([value], 12).get(value)).toBe('Área 👩🏽‍⚕️ y…'); + const word = 'Neurodesarrollosuperextenso'; + expect(abbreviateCategories([word], 10).get(word)).toBe(word); + expect(abbreviateCategories([word], 10, false).get(word)).toBe('Neurodesa…'); + const symbol = 'Área α ± lenguaje y comunicación'; + expect(abbreviateCategories([symbol], 12).get(symbol)).toBe('Área α ±…'); + }); + it('preserva profundamente el original, datos, customdata, anotaciones, configuración y atributos desconocidos', () => { + const figure = source(), before = structuredClone(figure); freezeDeep(figure); + const result = present(figure); + expect(figure).toEqual(before); + const { hovertemplate: ignored, ...observations } = result.figure.data[0]; + const { hovertemplate: originalHover, ...originalObservations } = before.data[0]; + expect(observations).toEqual(originalObservations); + expect(result.figure.data[0]).not.toBe(figure.data[0]); + expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']); + expect(result.figure.layout['margin']).toEqual(before.layout['margin']); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + }); + it('restituye exclusivamente la categoría en hover y conserva porcentajes, intervalos y conteos', () => { + const figure = source(); figure.data[0]['hovertemplate'] = hover.replace('', '
IC %{error_y.array}'); + const result = present(figure); + expect(result.figure.data[0]['hovertemplate']).toEqual([long, 'Otra'].map(label => + (figure.data[0]['hovertemplate'] as string).replace('%{x}', label))); + expect(figure.data[0]['hovertemplate']).toContain('%{x}'); + }); + it('conserva símbolos de reemplazo y ampersands como texto literal en el hover', () => { + const figure = source(), label = 'Área $& y salud & comunicación extensa'; + figure.data[0]['x'] = [label, 'Otra']; + expect((present(figure).figure.data[0]['hovertemplate'] as string[])[0]).toBe(hover.replace('%{x}', () => label.replaceAll('&', '&'))); + }); + it.each([NaN, 0, 7, 81, 20.5])('opciones inválidas conservan los ejes: %s', maxCharacters => { + const figure = source(); + const result = figurePresentation(figure, selection, { axisLabels: { enabled: true, maxCharacters } }); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + }); + it('conserva plantillas por punto, hovertext, hoverinfo y contenido suprimido sin exponer valores', () => { + const figure = source(); figure.data[0]['hovertemplate'] = [hover, '%{x}
dato suprimido (conteo bajo)']; + figure.data[0]['hovertext'] = ['Observación publicada', 'SUPRIMIDO']; figure.data[0]['hoverinfo'] = 'text'; + const result = present(figure).figure.data[0]; + expect((result['hovertemplate'] as string[])[1]).toBe('Otra
dato suprimido (conteo bajo)'); + expect((result['hovertemplate'] as string[])[1]).not.toMatch(/customdata|%\{y|20|0 %/); + expect(result['hovertext']).toEqual(figure.data[0]['hovertext']); expect(result['customdata']).toEqual(figure.data[0]['customdata']); + expect(result['hoverinfo']).toBe('text'); expect(result['y']).toEqual([20, null]); + }); + it.each([undefined, '%{x:.2f}
%{y}', '%{customdata[0]}', ['%{x}'], ['%{x}', null]])('fallback de hover desconocido o incompatible: %j', template => { + const figure = source(); figure.data[0]['hovertemplate'] = template; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).categoryLabels).toEqual([]); + }); + it.each(['linear', 'date', 'log', 'multicategory'])('no adapta un eje simple declarado %s', type => { + const figure = source(); figure.layout['xaxis'] = { type }; + expect(present(figure).figure.data).toEqual(figure.data); + expect(present(figure).figure.layout['xaxis']).toEqual({ type }); + }); + it.each(['2025-01', '2025-S1', '2025-10-14T14:00:00', 'Primer semestre del año 2025', '1234567890123456789012345'])('no abrevia fechas, periodos ni texto numérico: %s', label => { + expect(abbreviateCategories([label], 8).get(label)).toBe(label); + }); + it.each([{ ticktext: ['Alias'] }, { tickmode: 'auto' }, { labelalias: { [long]: 'Alias' } }, { range: [0, 2] }, + { showticklabels: false }, { tickprefix: 'Grupo: ' }, { matches: 'x2' }])('respeta ticks/semántica explícita del eje: %j', axis => { + const figure = source(); figure.layout['xaxis'] = { type: 'category', ...axis }; + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + }); + it('respeta ticks heredados de una plantilla y una orientación publicada', () => { + const figure = source(); figure.layout['template'] = { layout: { xaxis: { ticktext: ['Alias'] } } }; + expect(present(figure).categoryLabels).toEqual([]); + delete figure.layout['template']; (figure.layout['xaxis'] as Record)['tickangle'] = 30; + expect(present(figure).figure.layout['xaxis']).toMatchObject({ tickangle: 30 }); + }); + it('soporta barras horizontales sin cambiar categorías Y ni valores X', () => { + const figure: PlotlyFigure = { data: [{ type: 'bar', orientation: 'h', y: [long], x: [0], customdata: [null], + hovertemplate: '%{y}
%{x:.1f}%' }], layout: { yaxis: { type: 'category' } } }; + const result = present(figure); + expect(result.figure.layout['yaxis']).toMatchObject({ ticktext: ['Fármaco de riesgo…'], tickvals: [long] }); + expect(result.figure.data[0]['x']).toEqual([0]); expect(result.figure.data[0]['y']).toEqual([long]); + expect(result.figure.data[0]['hovertemplate']).toEqual([long + '
%{x:.1f}%']); + }); + it('multicategoría conserva niveles, periodos, agrupación, hover y reserva de margen', () => { + const figure = source(); figure.data[0]['type'] = 'bar'; figure.data[0]['x'] = [['2025-S1', '2025-S2'], [long, long]]; + figure.layout['xaxis'] = { type: 'multicategory', future: true }; + const result = present(figure); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + expect(result.figure.layout['xaxis']).toEqual({ type: 'multicategory', future: true, automargin: true, tickfont: { size: 11 } }); + expect(result.figure.layout['margin']).toEqual(figure.layout['margin']); + const preserve = figurePresentation(figure, selection, { axisLabels: { enabled: true, multicategory: 'preserve' } }); + expect(preserve.figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + }); + it.each([{ levels: [['2025-S1'], [long, long]] }, { levels: [['Grupo', 'Grupo'], [long, long]] }, + { levels: [['2025-S1', '2025-S2'], [long, long], ['a', 'b']] }])('preserva multicategorías no validadas: %j', ({ levels }) => { + const figure = source(); figure.data[0]['x'] = levels; figure.layout['xaxis'] = { type: 'multicategory' }; + expect(present(figure).figure.layout['xaxis']).toEqual(figure.layout['xaxis']); + expect(present(figure).figure.data).toEqual(figure.data); + }); + it.each(['pie', 'box', 'heatmap', 'future'])('conserva familias incompatibles: %s', type => { + const figure = source(); figure.data[0]['type'] = type; + expect(present(figure).categoryLabels).toEqual([]); expect(present(figure).figure.data).toEqual(figure.data); + }); + it('conserva frames/menús/subplots y no infiere identidades o HTML', () => { + for (const extra of [{ frames: [{ name: 'f', data: [{ x: [long] }], future: 3 }] }, + { layout: { ...source().layout, updatemenus: [] } }, { layout: { ...source().layout, xaxis2: {} } }]) { + const figure = { ...source(), ...extra }, before = structuredClone(figure); + expect(present(figure).figure.data).toEqual(before.data); expect(present(figure).figure.frames).toEqual(before.frames); + expect(present(figure).categoryLabels).toEqual([]); + } + for (const label of ['Texto extenso publicado', 'Área & texto extenso', 'Área %{customdata} muy extensa']) { + const figure = source(); figure.data[0]['x'] = [label, 'Otra']; + expect(present(figure).categoryLabels).toEqual([]); + } + }); + it('revierte al perfil base desde el original y combina el perfil de demostración sin acumulación', () => { + const figure = source(), original = structuredClone(figure); + const compact = present(figure); compact.figure.data[0]['x'] = ['mutación del runtime']; + const restored = figurePresentation(figure, selection, BASE_VISUAL_PROFILE); + expect(restored.figure.data).toEqual(original.data); expect(restored.categoryLabels).toEqual([]); + expect(restored.figure.layout['xaxis']).toEqual(original.layout['xaxis']); + const demo = figurePresentation(figure, selection, { ...DEMO_VISUAL_PROFILE, ...READABLE_VISUAL_PROFILE }); + expect(demo.figure.layout['paper_bgcolor']).toBe('#f2f7fc'); expect(demo.categoryLabels).toHaveLength(1); + expect(figure).toEqual(original); + }); + it('extrae el pie TEA sin perder el mapa de categorías ni alterar anotaciones desconocidas', () => { + const figure = source(); figure.layout['annotations'] = [{ + text: 'Nota sintética.
Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01
Uso exclusivo de investigación. No usar para decisiones clínicas.', + xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 }, + }]; + const result = present(figure); + expect(result.footnotes).toHaveLength(1); expect(result.figure.layout['annotations']).toEqual([]); + expect(result.categoryLabels[0].original).toBe(long); + }); + it.each(['cacu', 'cama'] as const)('mantiene la adaptación mensual %s con el perfil legible', dominio => { + const figure: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0], hovertemplate: hover }], layout: {} }; + const result = figurePresentation(figure, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, READABLE_VISUAL_PROFILE); + expect(result.figure.layout['xaxis']).toMatchObject({ categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'] }); + expect(result.figure.data).toEqual(figure.data); expect(result.categoryLabels).toEqual([]); + }); +}); diff --git a/src/app/features/indicadores/indicadores-axis-labels.ts b/src/app/features/indicadores/indicadores-axis-labels.ts new file mode 100644 index 0000000..42de694 --- /dev/null +++ b/src/app/features/indicadores/indicadores-axis-labels.ts @@ -0,0 +1,191 @@ +import { PlotlyFigure } from './indicadores.models'; +import { AxisLabelOptions } from './indicadores-visual-profile'; + +export interface CategoryLabel { + readonly axis: 'x' | 'y'; + readonly abbreviated: string; + readonly original: string; +} + +const graphemes = new Intl.Segmenter('es', { granularity: 'grapheme' }); +const characters = (text: string) => [...graphemes.segment(text)].map(part => part.segment); +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function plainLabel(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0 + && !/[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);|%\{/i.test(value); +} +function temporalOrNumeric(value: string): boolean { + // Conservative: published years, dates, semester/month codes and numeric text. + return /(?:^|\D)\d{4}(?:\D|$)/u.test(value) || /^[\d\s.,+−\-/%:]+$/u.test(value) + || /^(?:S[12]|T[1-4]|Q[1-4]|\d{1,2}[-/]\d{1,2})$/iu.test(value); +} + +/** A collision falls back to the original; identical categories share one label. */ +export function abbreviateCategories(values: readonly string[], limit: number, preferWords = true): Map { + const originals = [...new Set(values)]; + const labels = new Map(originals.map(value => { + if (temporalOrNumeric(value) || characters(value).length <= limit) return [value, value]; + let prefix = characters(value).slice(0, limit - 1).join(''); + if (preferWords && !/^\s/u.test(characters(value)[limit - 1] ?? '')) { + const boundary = prefix.search(/\s+\S*$/u); + if (boundary < 1) return [value, value]; // Do not split an indivisible word. + prefix = prefix.slice(0, boundary); + } + return [value, prefix.trimEnd() + '…']; + })); + const counts = new Map(); + for (const label of labels.values()) counts.set(label, (counts.get(label) ?? 0) + 1); + for (const [original, label] of labels) { + if ((counts.get(label) ?? 0) > 1 || (label !== original && labels.has(label))) labels.set(original, original); + } + return labels; +} + +function templates(trace: Record, coordinate: 'x' | 'y', size: number): string[] | undefined { + const template = trace['hovertemplate']; + const list = typeof template === 'string' ? Array(size).fill(template) + : Array.isArray(template) && template.length === size ? template : undefined; + // Do not reconstruct default hovers, formatted coordinates, expressions, or + // templates whose category is in a different field. Preserve those axes. + return list?.every(text => typeof text === 'string' && text.includes(`%{${coordinate}}`) + && !text.includes(`%{${coordinate}:`) && !text.includes(`%{${coordinate}|`)) ? list : undefined; +} + +// Keep dense categories readable inside the existing keyboard-scrollable plot +// viewport. The minimum is independent of the measured host width, preventing +// ResizeObserver feedback when the host grows to this minimum. +export function categoryMinimumWidth(figure: PlotlyFigure): number | undefined { + const published = figure.layout['xaxis']; + const template = figure.layout['template']; + const templateLayout = record(template) && record(template['layout']) ? template['layout'] : {}; + const axis = { ...(record(templateLayout['xaxis']) ? templateLayout['xaxis'] : {}), ...(record(published) ? published : {}) }; + if ((published !== undefined && !record(published)) || (axis['type'] !== undefined && !['category', 'multicategory'].includes(String(axis['type']))) + || figure.frames?.length || figure.layout['width'] !== undefined || figure.layout['autosize'] === false + || ['annotations', 'shapes', 'images', 'sliders', 'updatemenus'].some(key => { + const value = figure.layout[key]; return value !== undefined && (!Array.isArray(value) || value.length > 0); + }) || Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key)) + || ['tickvals', 'ticktext', 'tickmode', 'dtick', 'tick0', 'range', 'matches', 'overlaying', 'ticklabelstep'].some(key => axis[key] !== undefined) + || !figure.data.length) return undefined; + const multi = figure.data.some(trace => Array.isArray(trace['x']) && trace['x'].some(Array.isArray)); + if ((multi && axis['type'] === 'category') || (!multi && axis['type'] === 'multicategory')) return undefined; + const positions: string[] = []; + for (const trace of figure.data) { + if (!['scatter', 'bar'].includes(String(trace['type'])) || trace['orientation'] === 'h' + || ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined) + || (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y') + || !Array.isArray(trace['x']) || !Array.isArray(trace['y'])) return undefined; + const x = trace['x'] as unknown[], y = trace['y'] as unknown[]; + if (y.some(value => value !== null && typeof value !== 'number')) return undefined; + if (multi) { + if (trace['type'] !== 'bar' || x.length !== 2 || !x.every(Array.isArray) + || x.some(level => level.length !== y.length) || !(x[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value)) + || !(x[1] as unknown[]).every(plainLabel)) return undefined; + (x[0] as string[]).forEach((period, index) => positions.push(JSON.stringify([period, (x[1] as string[])[index]]))); + } else { + if (x.length !== y.length || !x.every(plainLabel) || x.some(temporalOrNumeric)) return undefined; + positions.push(...x as string[]); + } + } + const count = new Set(positions).size; + if (count < 3) return undefined; + const font = record(figure.layout['font']) ? figure.layout['font'] : {}; + const tickfont = record(axis['tickfont']) ? axis['tickfont'] : font; + const size = typeof tickfont['size'] === 'number' ? tickfont['size'] : 12; + const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {}; + const legendWidth = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0 + : Math.max(0, ...figure.data.filter(trace => trace['showlegend'] !== false).map(trace => + characters(String(trace['name'] ?? '')).length * 7 + 48)); + const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {}; + return Math.ceil(count * Math.max(20, size * 1.8) + legendWidth + + (typeof margin['l'] === 'number' ? margin['l'] : 80) + + (typeof margin['r'] === 'number' ? margin['r'] : 80)); +} + +/** Mutates only the independent presentation clone supplied by figurePresentation. */ +export function applyAxisLabels(figure: PlotlyFigure, options?: AxisLabelOptions, availableWidth?: number): CategoryLabel[] { + const result: CategoryLabel[] = []; + const limit = options?.maxCharacters ?? 22; + if (!options?.enabled || !Number.isInteger(limit) || limit < 8 || limit > 80 || figure.frames?.length + || figure.layout['updatemenus'] !== undefined || figure.layout['sliders'] !== undefined) return result; + // Multiple/linked axes and subplots require an explicit mapping contract. + if (Object.keys(figure.layout).some(key => /^[xy]axis\d+$/.test(key))) return result; + for (const coordinate of ['x', 'y'] as const) { + const axisKey = `${coordinate}axis`, other = coordinate === 'x' ? 'y' : 'x'; + const published = figure.layout[axisKey]; + if (published !== undefined && !record(published)) continue; + const axis = record(published) ? published : {}; + const templateLayout = record(figure.layout['template']) ? figure.layout['template']['layout'] : undefined; + const templateAxis = record(templateLayout) && record(templateLayout[axisKey]) ? templateLayout[axisKey] : {}; + const effective = { ...templateAxis, ...axis }; + if (['tickvals', 'ticktext', 'tickmode', 'labelalias', 'tickformat', 'tickprefix', 'ticksuffix', 'dtick', 'tick0', + 'ticklabelstep', 'range', 'matches', 'overlaying', 'ticklabelindex'].some(key => effective[key] !== undefined) + || effective['showticklabels'] === false) continue; + const traces = figure.data; + if (!traces.length || traces.some(trace => !['scatter', 'bar'].includes(String(trace['type'])) + || (trace[axisKey] !== undefined && trace[axisKey] !== coordinate) + || ['transforms', 'hovertemplatesrc', `${coordinate}src`].some(key => trace[key] !== undefined) + || !Array.isArray(trace[coordinate]) || !Array.isArray(trace[other]) + || (trace[other] as unknown[]).some(value => value !== null && typeof value !== 'number'))) continue; + const arrays = traces.map(trace => trace[coordinate] as unknown[]); + const fits = (values: readonly string[], count: number): boolean => { + if (coordinate !== 'x' || options.preserveWhenFits === false || !Number.isFinite(availableWidth) || !count) return false; + const margin = record(figure.layout['margin']) ? figure.layout['margin'] : {}; + const font = record(effective['tickfont']) ? effective['tickfont'] + : record(figure.layout['font']) ? figure.layout['font'] : {}; + const fontSize = typeof font['size'] === 'number' ? font['size'] : 12; + const textWidth = (text: string) => characters(text).reduce((size, char) => size + + fontSize * (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Extended_Pictographic}]/u.test(char) ? 1.1 : 0.58), 0); + const legend = record(figure.layout['legend']) ? figure.layout['legend'] : {}; + const legendSize = figure.layout['showlegend'] === false || legend['orientation'] === 'h' ? 0 + : Math.max(0, ...traces.filter(trace => trace['showlegend'] !== false).map(trace => + textWidth(String(trace['name'] ?? '')) + 40)); + const width = availableWidth! - (typeof margin['l'] === 'number' ? margin['l'] : 80) + - (typeof margin['r'] === 'number' ? margin['r'] : 80) - legendSize; + // A conservative estimate with padding; no SVG measurements or font loads. + return values.every(value => textWidth(value) + 16 <= width / count); + }; + const multi = arrays.some(values => values.some(Array.isArray)); + if (multi) { + // Plotly 4.1.2 does not safely map tickvals/ticktext to both levels. + // Keep every published coordinate, grouping, period and hover unchanged. + if (coordinate !== 'x' || options.multicategory !== 'fit' || traces.some(trace => trace['type'] !== 'bar') + || (effective['type'] !== undefined && effective['type'] !== 'multicategory') + || arrays.some((levels, i) => levels.length !== 2 || !levels.every(Array.isArray) + || (levels[0] as unknown[]).length !== (levels[1] as unknown[]).length + || (levels[0] as unknown[]).length !== (traces[i][other] as unknown[]).length + || !(levels[0] as unknown[]).every(value => typeof value === 'string' && /^\d{4}-S[12]$/.test(value)) + || !(levels[1] as unknown[]).every(plainLabel)) + || !arrays.some(levels => (levels[1] as string[]).some(value => characters(value).length > limit))) continue; + if (fits(arrays.flatMap(levels => levels[1] as string[]), Math.max(...arrays.map(levels => (levels[1] as string[]).length)))) continue; + const font = record(effective['tickfont']) ? effective['tickfont'] : {}; + figure.layout[axisKey] = { ...axis, automargin: true, + tickfont: { ...font, size: Math.min(typeof font['size'] === 'number' ? font['size'] : 12, 11) } }; + continue; + } + if ((effective['type'] !== undefined && effective['type'] !== 'category') + || arrays.some((values, i) => values.length !== (traces[i][other] as unknown[]).length || !values.every(plainLabel))) continue; + const order = effective['categoryarray']; + if (order !== undefined && (!Array.isArray(order) || !order.every(plainLabel))) continue; + const values = [...new Set([...(Array.isArray(order) ? order as string[] : []), ...arrays.flat() as string[]])]; + if (fits(values, values.length)) continue; + const labels = abbreviateCategories(values, limit, options.preferWords ?? true); + if (![...labels].some(([original, label]) => original !== label)) continue; + const hoverTemplates = traces.map((trace, i) => templates(trace, coordinate, arrays[i].length)); + if (hoverTemplates.some(value => value === undefined)) continue; + // Only the bare coordinate token changes, per point. All statistical and + // suppression tokens/text remain exactly as published; no customdata added. + traces.forEach((trace, i) => { + trace['hovertemplate'] = hoverTemplates[i]!.map((template, j) => template.replaceAll( + `%{${coordinate}}`, () => (arrays[i][j] as string).replaceAll('&', '&'))); + }); + figure.layout[axisKey] = { ...axis, type: 'category', tickmode: 'array', tickvals: values, + ticktext: values.map(value => labels.get(value)!), automargin: true, + ...(effective['tickangle'] === undefined ? { tickangle: coordinate === 'x' ? -60 : 0 } : {}) }; + for (const [original, abbreviated] of labels) { + if (original !== abbreviated) result.push({ axis: coordinate, original, abbreviated }); + } + } + return result; +} diff --git a/src/app/features/indicadores/indicadores-figure-labels.spec.ts b/src/app/features/indicadores/indicadores-figure-labels.spec.ts new file mode 100644 index 0000000..1e6db48 --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-labels.spec.ts @@ -0,0 +1,28 @@ +import { figureDisplayName } from './indicadores-figure-labels'; + +describe('UX-07A nombres de representaciones', () => { + it.each([ + ['fig_c1_grupos', 'Grupos'], + ['fig_c1_puntos', 'Puntos'], + ['fig_c2_apiladas', 'Barras apiladas'], + ['fig_c2_barras', 'Barras'], + ['fig_c2_donas', 'Donas'], + ['fig_c3r_caja', 'Caja de cuartiles'], + ])('presenta %s como %s', (id, label) => { + expect(figureDisplayName(id, [id])).toBe(label); + }); + + it('no infiere tipos por prefijo y distingue opciones desconocidas en orden de publicación', () => { + const figures = ['fig_c1_grupos', 'fig_c1_futura', 'fig_c2_futura']; + const snapshot = [...figures]; + expect(figureDisplayName(figures[1], figures)).toBe('Representación 2'); + expect(figureDisplayName(figures[2], figures)).toBe('Representación 3'); + expect(figureDisplayName(figures[1], [...figures])).toBe('Representación 2'); + expect(figures).toEqual(snapshot); + }); + + it('no usa propiedades heredadas ni revela IDs ajenos al catálogo', () => { + expect(figureDisplayName('constructor', ['constructor'])).toBe('Representación 1'); + expect(figureDisplayName('sin_publicar', [])).toBe('Representación adicional'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts new file mode 100644 index 0000000..46c48dd --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -0,0 +1,17 @@ +// Presentation labels for representations confirmed in the published catalog. +// Exact IDs remain the option values and HTTP identities; never infer a type +// from a prefix. Unknown options keep a neutral label in publication order. +const FIGURE_LABELS: Readonly> = { + fig_c1_grupos: 'Grupos', + fig_c1_puntos: 'Puntos', + fig_c2_apiladas: 'Barras apiladas', + fig_c2_barras: 'Barras', + fig_c2_donas: 'Donas', + fig_c3r_caja: 'Caja de cuartiles', +}; + +export function figureDisplayName(figureId: string, publishedFigures: readonly string[]): string { + if (Object.hasOwn(FIGURE_LABELS, figureId)) return FIGURE_LABELS[figureId]; + const index = publishedFigures.indexOf(figureId); + return index >= 0 ? `Representación ${index + 1}` : 'Representación adicional'; +} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 0dc65d8..67eb0b6 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -86,7 +86,9 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(host.querySelector('header button')).toBeNull(); expect(host.querySelector('mat-select')).toBeTruthy(); expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); - expect(host.textContent).toContain('Contrato C1'); http.expectNone(() => true); + expect(host.textContent).not.toContain('Contrato C1'); + expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); + http.expectNone(() => true); }); it('D.3.A conserva encabezado y contenido al salir del viewport', () => { load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); diff --git a/src/app/features/indicadores/indicadores-visual-profile.spec.ts b/src/app/features/indicadores/indicadores-visual-profile.spec.ts new file mode 100644 index 0000000..0dc955b --- /dev/null +++ b/src/app/features/indicadores/indicadores-visual-profile.spec.ts @@ -0,0 +1,228 @@ +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { figurePresentation } from './indicadores.presentation'; +import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE } from './indicadores-visual-profile'; +import { syntheticFigures } from './indicadores.synthetic-fixtures'; + +const selection: FigureSelection = { dominio: 'tea', indicador: 'synthetic', figura: 'fig_c1_grupos', tema: 'claro' }; +const footer = { + text: 'Explicación sintética. Los valores suprimidos no son cero.
Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01
Uso exclusivo de investigación. No usar para decisiones clínicas.', + xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', + align: 'left', showarrow: false, font: { size: 11, color: '#52514e' }, +}; +function freezeDeep(value: unknown) { + if (value && typeof value === 'object') { + Object.values(value).forEach(freezeDeep); + Object.freeze(value); + } +} +function original(): PlotlyFigure { + return { + data: [{ type: 'bar', x: [['2025-S1', '2025-S2'], ['Área extensa de ejemplo', 'Otra área']], y: [null, 0], + marker: { color: ['gray', 'blue'] }, customdata: [[null, 'SUPRIMIDO'], [0, 10]], future: { untouched: true } }], + layout: { title: 'Título', xaxis: { type: 'multicategory', future: 17 }, yaxis: { range: [0, 100] }, + font: { future: 2 }, margin: { b: 150, future: 3 }, annotations: [structuredClone(footer)], future: { keep: true } }, + config: { staticPlot: false }, future: { keep: [1, null] }, + }; +} +describe('UX-07B perfiles y pies metodológicos', () => { + it('deriva desde el original congelado, preserva íntegramente trazas, frames y atributos desconocidos', () => { + const source = original(); source.frames = [{ name: 'frame', data: [{ y: [null, 0] }], layout: { annotations: [footer] }, future: 9 }]; + const before = structuredClone(source); freezeDeep(source); + const result = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(source).toEqual(before); + expect(result.figure.data).toEqual(before.data); expect(result.figure.data).not.toBe(source.data); + expect(result.figure.frames).toEqual(before.frames); expect(result.figure.frames).not.toBe(source.frames); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + expect(result.figure.layout['future']).toEqual(before.layout['future']); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'multicategory', future: 17 }); + expect(result.figure.layout['font']).toMatchObject({ future: 2 }); + expect(result.figure.layout['margin']).toMatchObject({ b: 150, future: 3 }); + expect(result.footnotes).toEqual([]); // An animated annotation could otherwise reappear. + expect(result.figure.layout['annotations']).toEqual(before.layout['annotations']); + }); + it('aplica y revierte el perfil sin acumular estilos ni mutaciones del runtime', () => { + const source = original(), snapshot = structuredClone(source); + const base = figurePresentation(source, selection); + const demo = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(demo.figure.layout).toMatchObject({ paper_bgcolor: '#f2f7fc', plot_bgcolor: '#ffffff', height: 640, + font: { family: 'Arial, sans-serif', size: 15 }, xaxis: { type: 'multicategory', showgrid: true, gridcolor: '#c6d7e8' } }); + demo.figure.data[0]['y'] = [999]; demo.figure.layout['annotations'] = [{ text: 'runtime' }]; + expect(figurePresentation(source, selection, BASE_VISUAL_PROFILE)).toEqual(base); + expect(source).toEqual(snapshot); + }); + it('extrae sólo el pie reconocido, preserva texto y orden sin duplicarlo en Plotly', () => { + const source = original(); const annotation = { text: 'Meta', x: 1, y: 90 }; + const second = { ...footer, text: footer.text.replace('Explicación sintética.', 'Segunda explicación.') }; + source.layout['annotations'] = [footer, annotation, second]; + const result = figurePresentation(source, selection); + expect(result.footnotes).toEqual([footer.text.replaceAll('
', '\n'), second.text.replaceAll('
', '\n')]); + expect(result.figure.layout['annotations']).toEqual([annotation]); + expect(source.layout['annotations']).toEqual([footer, annotation, second]); + expect(result.figure.layout['margin']).toEqual(source.layout['margin']); + }); + it.each([ + { xref: 'x' }, { yref: 'y' }, { y: -0.23 }, { x: 0.1 }, { showarrow: true }, + { xanchor: 'center' }, { yanchor: 'bottom' }, { align: 'center' }, { opacity: 0.4 }, + { font: { size: 11, future: true } }, { text: 'Nota desconocida' }, + { text: footer.text.replace('Explicación sintética.', 'Explicación sintética.') }, + { text: footer.text.replace('Explicación sintética.', '<script>') }, + { text: footer.text.replace('Explicación sintética.', '') }, + ])('conserva anotaciones ambiguas o marcado no trasladable: %j', change => { + const source = original(); source.layout['annotations'] = [{ ...footer, ...change }]; + const result = figurePresentation(source, selection); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + }); + it.each([{ dominio: 'cacu' as const }, { figura: 'fig_c3r_cajas' }, { dominio: undefined }])('no infiere familias ni dominios: %j', change => { + const source = original(); const result = figurePresentation(source, { ...selection, ...change }); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + }); + it.each([{ data: [] }, { data: [{ y: [null, null], customdata: ['SUPRIMIDO', 'SIN_DATO'] }] }, { data: [{ y: [0, NaN, null] }] }])('preserva vacíos, supresión, nulos y cero: %j', ({ data }) => { + const source = { ...original(), data }; const snapshot = structuredClone(source); + expect(figurePresentation(source, selection, DEMO_VISUAL_PROFILE).figure.data).toEqual(snapshot.data); + expect(source).toEqual(snapshot); + }); + it('admite saltos br equivalentes y conserva cada línea sin trim ni HTML', () => { + const source = original(); const text = footer.text.replaceAll('
', '
'); + source.layout['annotations'] = [{ ...footer, text }]; + expect(figurePresentation(source, selection).footnotes).toEqual([footer.text.replaceAll('
', '\n')]); + }); + it('reconoce los tres pies de fixtures sintéticos existentes sin alterar los datos', () => { + const tea = syntheticFigures.filter(item => item.name.startsWith('tea')); + expect(tea).toHaveLength(3); + for (const item of tea) { + const result = figurePresentation(item.figure, selection); + expect(result.footnotes).toHaveLength(1); + const annotations = item.figure.layout['annotations'] as { text: string }[]; + expect(result.footnotes[0]).toBe(annotations[0].text.replaceAll('
', '\n')); + expect(result.figure.layout['annotations']).toEqual([]); expect(result.figure.data).toEqual(item.figure.data); + } + }); + it('respeta dimensiones fijas y no crea ejes para figuras que no los publican', () => { + const source = { data: [], layout: { width: 800, height: 400, autosize: false } }; + const result = figurePresentation(source, selection, DEMO_VISUAL_PROFILE); + expect(result.figure.layout).toMatchObject({ width: 800, height: 400, autosize: false }); + expect(result.figure.layout['xaxis']).toBeUndefined(); + }); + it('reduce sólo la reserva conocida de un eje simple con automargin efectivo', () => { + const source = original(); source.data = [{ type: 'bar', x: ['Grupo'], y: [0] }]; + source.layout['xaxis'] = { type: 'category', automargin: true }; + expect(figurePresentation(source, selection).figure.layout['margin']).toMatchObject({ b: 80, future: 3 }); + expect(source.layout['margin']).toMatchObject({ b: 150 }); + for (const change of [{ xaxis: { type: 'multicategory', automargin: true } }, { legend: { y: -0.2 } }, + { legend: { orientation: 'h' } }, { legend: { y: 0, yanchor: 'top' } }, + { shapes: [] }, { xaxis2: { automargin: true } }, { height: 620 }, { xaxis: { type: 'category' } }]) { + expect(figurePresentation({ ...source, layout: { ...source.layout, ...change } }, selection).figure.layout['margin']).toMatchObject({ b: 150 }); + } + }); + it.each(['cacu', 'cama'] as const)('conserva adaptación mensual de %s con ambos perfiles', dominio => { + const source: PlotlyFigure = { data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01'], y: [null, 0] }], layout: { xaxis: { future: true } } }; + for (const profile of [BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE]) { + const result = figurePresentation(source, { ...selection, dominio, figura: 'fig_c1_puntos', tipoPeriodo: 'mes' }, profile); + expect(result.figure.layout['xaxis']).toMatchObject({ type: 'category', categoryarray: ['2025-01', '2025-03'], ticktext: ['2025-01', '2025-03'], automargin: true, future: true }); + expect(result.figure.data).toEqual(source.data); + } + }); +}); + +describe('UX-07D.2 pies documentales de familias verificadas', () => { + const note = { ...footer, text: 'Fuente: ejemplo sintético.' }; + const donutTotal = { text: '12', xref: 'paper', yref: 'paper', x: 0.5, y: 0.5, + showarrow: false, font: { size: 18, color: '#000000' } }; + const selected = (dominio: 'tea' | 'cacu' | 'cama', figura = 'fig_c2_barras'): FigureSelection => + ({ ...selection, dominio, figura }); + const figure = (annotations: unknown[] = [note]): PlotlyFigure => ({ + data: [{ type: 'bar', x: ['Categoría íntegra'], y: [null, 0], customdata: ['SUPRIMIDO', 'SIN_DATO'], + hovertemplate: '%{x}: %{y}', marker: { color: 'gray' }, future: { untouched: true } }], + layout: { margin: { b: 150 }, annotations, future: { untouched: true } }, + config: { displaylogo: false }, future: { unchanged: true }, + }); + it.each(['cacu', 'cama'] as const)('extrae pies de barras, donas y cajas %s con la firma completa', dominio => { + for (const id of ['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']) { + const source = figure([donutTotal, note]); + const result = figurePresentation(source, selected(dominio, id)); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.layout['annotations']).toEqual([donutTotal]); + expect(result.figure.data).toEqual(source.data); + expect(result.figure.layout['margin']).toEqual({ b: 150 }); + } + }); + it.each(['fig_c2_barras', 'fig_c2_donas'])('amplía TEA %s conservando su firma de fuente e investigación', id => { + expect(figurePresentation(figure([donutTotal, footer]), selected('tea', id)).footnotes) + .toEqual([footer.text.replaceAll('
', '\n')]); + expect(figurePresentation(figure(), selected('tea', id)).footnotes).toEqual([]); + }); + it.each(['Fuente: X.', 'Nota: ' + 'Texto extenso. '.repeat(100), 'Primera\n\nSegunda
Tercera
Cuarta', + ' Fuente: A & B · «Sin dato» ≤ 5 — 日本語\n '])('preserva texto independientemente de longitud o saltos: %s', text => { + const result = figurePresentation(figure([{ ...note, text }]), selected('cama')); + expect(result.footnotes).toEqual([text.replace(//gi, '\n')]); + expect(result.figure.layout['annotations']).toEqual([]); + }); + it.each([ + { text: 'Nota' }, { text: '' }, { text: '<img>' }, + { text: 'Fuente' }, { text: 'Texto & más' }, + { text: ' \n ' }, { text: 17 }, { xref: 'x' }, { yref: 'y' }, { yref: 'y domain' }, + { y: -0.23 }, { x: 0.5 }, { y: 0.5 }, { showarrow: true }, { ax: 0, ay: 20 }, + { xanchor: 'center' }, { yanchor: 'bottom' }, { align: 'center' }, { opacity: 0.5 }, + { visible: false }, { name: 'unknown' }, { font: { size: 11, future: true } }, + ])('conserva en Plotly marcado, geometría o atributos incompatibles: %j', change => { + const source = figure([{ ...note, ...change }]); + for (const domain of ['cacu', 'cama'] as const) { + const result = figurePresentation(source, selected(domain)); + expect(result.footnotes).toEqual([]); + expect(result.figure.layout['annotations']).toEqual(source.layout['annotations']); + } + }); + it('particiona cada ocurrencia una sola vez, en orden, conservando anotaciones internas', () => { + const internal = [{ text: 'Dato', xref: 'x', yref: 'y', x: 1, y: 3, showarrow: false }, + { text: 'Observación', x: 1, y: 3, showarrow: true }, donutTotal, + { text: 'Larga\n'.repeat(100), xref: 'paper', yref: 'paper', y: -0.22 }]; + const annotations = [note, internal[0], { ...note, text: 'Segunda
línea' }, ...internal.slice(1), note]; + const source = figure(annotations), before = structuredClone(source); freezeDeep(source); + const result = figurePresentation(source, selected('cacu')); + expect(result.footnotes).toEqual([note.text, 'Segunda\nlínea', note.text]); + expect(result.figure.layout['annotations']).toEqual(internal); + expect(result.footnotes.length + internal.length).toBe(annotations.length); + expect(source).toEqual(before); expect(result.figure.data).toEqual(before.data); + expect(result.figure.config).toEqual(before.config); expect(result.figure['future']).toEqual(before['future']); + expect(result.figure.layout['future']).toEqual(before.layout['future']); + }); + it('conserva animaciones, plantilla, ejes multicategoría y atributos desconocidos', () => { + const source = figure(); source.frames = [{ name: 'frame', layout: { annotations: [note] }, future: 1 }]; + source.layout['template'] = { layout: { annotations: [note] } }; + source.layout['xaxis'] = { type: 'multicategory', future: 3 }; + const result = figurePresentation(source, selected('cama')); + expect(result.footnotes).toEqual([]); expect(result.figure.frames).toEqual(source.frames); + expect(result.figure.layout['annotations']).toEqual([note]); + expect(result.figure.layout['template']).toEqual(source.layout['template']); + expect(result.figure.layout['xaxis']).toEqual(source.layout['xaxis']); + }); + it('no impone nuevas reducciones de márgenes ni cambia multicategoría al extraer', () => { + const source = figure(); source.layout['xaxis'] = { type: 'multicategory', automargin: true }; + source.layout['legend'] = { orientation: 'h', y: -0.3 }; source.layout['height'] = 620; + const result = figurePresentation(source, selected('cama')); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.layout['xaxis']).toEqual(source.layout['xaxis']); + expect(result.figure.layout['margin']).toEqual(source.layout['margin']); + expect(result.figure.layout['legend']).toEqual(source.layout['legend']); + expect(result.figure.layout['height']).toBe(620); + }); + it('no inventa pies para figuras sin notas ni familias desconocidas', () => { + expect(figurePresentation(figure([]), selected('cacu')).footnotes).toEqual([]); + const source = figure(); + for (const id of ['fig_c1_puntos', 'fig_desconocida']) { + const result = figurePresentation(source, selected('cacu', id)); + expect(result.footnotes).toEqual([]); expect(result.figure.layout['annotations']).toEqual([note]); + } + }); + it('deriva las mismas notas desde el original al alternar perfiles y anchos', () => { + const source = figure(), snapshot = structuredClone(source); + for (const profile of [BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { + for (const width of [230, 320, 768, 1440]) { + const result = figurePresentation(source, selected('cama'), profile, width); + expect(result.footnotes).toEqual([note.text]); + expect(result.figure.data).toEqual(snapshot.data); + } + } + expect(source).toEqual(snapshot); + }); +}); diff --git a/src/app/features/indicadores/indicadores-visual-profile.ts b/src/app/features/indicadores/indicadores-visual-profile.ts new file mode 100644 index 0000000..4cfb857 --- /dev/null +++ b/src/app/features/indicadores/indicadores-visual-profile.ts @@ -0,0 +1,31 @@ +// Presentation preferences. Trace colours retain their published semantic roles. +export interface AxisLabelOptions { + readonly enabled: boolean; + readonly maxCharacters?: number; + readonly preferWords?: boolean; + readonly preserveWhenFits?: boolean; + readonly multicategory?: 'preserve' | 'fit'; +} + +export interface FigureVisualProfile { + readonly axisLabels?: AxisLabelOptions; + readonly paperBackground?: string; + readonly plotBackground?: string; + readonly font?: Readonly<{ family?: string; size?: number; color?: string }>; + readonly margin?: Readonly<{ l?: number; r?: number; t?: number; b?: number; pad?: number }>; + readonly grid?: Readonly<{ color?: string; visible?: boolean }>; + readonly minimumHeight?: number; +} + +// Base keeps the received styling plus the dashboard's existing adaptations. +export const BASE_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({}); +export const READABLE_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({ + axisLabels: Object.freeze({ enabled: true, maxCharacters: 22, preferWords: true, preserveWhenFits: true, multicategory: 'fit' }), +}); +export const DEMO_VISUAL_PROFILE: FigureVisualProfile = Object.freeze({ + paperBackground: '#f2f7fc', plotBackground: '#ffffff', + font: Object.freeze({ family: 'Arial, sans-serif', size: 15, color: '#17324d' }), + margin: Object.freeze({ t: 30, pad: 8 }), + grid: Object.freeze({ color: '#c6d7e8', visible: true }), + minimumHeight: 640, +}); diff --git a/src/app/features/indicadores/indicadores.presentation.ts b/src/app/features/indicadores/indicadores.presentation.ts index acaac56..0b5bd89 100644 --- a/src/app/features/indicadores/indicadores.presentation.ts +++ b/src/app/features/indicadores/indicadores.presentation.ts @@ -1,4 +1,102 @@ import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { BASE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; +import { applyAxisLabels, categoryMinimumWidth, CategoryLabel } from './indicadores-axis-labels'; + +export interface FigurePresentation { + figure: PlotlyFigure; + // Plain text, including original line breaks; never an HTML fragment. + footnotes: readonly string[]; + categoryLabels: readonly CategoryLabel[]; + minimumPlotWidth?: number; +} + +const TEA_FOOTER_FIGURES = new Set(['fig_c1_grupos', 'fig_c1_puntos', 'fig_c2_apiladas', 'fig_c3r_caja']); +// Verified published families share the complete documentary footer geometry. +// Donut totals (paper 0.5, 0.5), data labels and callouts do not match it. +const DISTRIBUTION_FOOTER_FIGURES = new Set(['fig_c2_barras', 'fig_c2_donas', 'fig_c3r_caja']); +const FOOTER_KEYS = new Set(['text', 'xref', 'yref', 'x', 'y', 'xanchor', 'yanchor', 'align', 'showarrow', 'font']); +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function footerText(annotation: unknown, selection: FigureSelection): string | undefined { + const tea = selection.dominio === 'tea'; + const verifiedFamily = tea + ? TEA_FOOTER_FIGURES.has(selection.figura) || DISTRIBUTION_FOOTER_FIGURES.has(selection.figura) + : (selection.dominio === 'cacu' || selection.dominio === 'cama') && DISTRIBUTION_FOOTER_FIGURES.has(selection.figura); + if (!verifiedFamily || !record(annotation) + || Object.keys(annotation).some(key => !FOOTER_KEYS.has(key)) + || annotation['xref'] !== 'paper' || annotation['yref'] !== 'paper' + || annotation['x'] !== 0 || annotation['y'] !== -0.22 + || annotation['xanchor'] !== 'left' || annotation['yanchor'] !== 'top' + || annotation['align'] !== 'left' || annotation['showarrow'] !== false + || !record(annotation['font']) || annotation['font']['size'] !== 11 + || Object.keys(annotation['font']).some(key => !['size', 'color'].includes(key)) + || typeof annotation['text'] !== 'string') return undefined; + const text = annotation['text'].replace(//gi, '\n'); + // Rich markup, encoded markup, links and unknown formatting stay in Plotly. + if (!text.trim() || /[<>]|&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);/i.test(text)) return undefined; + // CaCu/CaMa publish plain documentary text in this exact exterior slot. + // No length threshold, keywords or indicator-name inference is involved. + if (!tea) return text; + // Retain UX-07B's additional TEA source/restriction guarantees. + const lines = text.split('\n'); + if (lines.length < 3 || !lines[0].trim() + || !/^Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: \d{4}-\d{2}-\d{2}$/.test(lines.at(-2)!) + || lines.at(-1) !== 'Uso exclusivo de investigación. No usar para decisiones clínicas.') return undefined; + return text; +} + +function applyVisualProfile(figure: PlotlyFigure, profile: FigureVisualProfile, availableWidth?: number) { + const layout = figure.layout; + if (profile.paperBackground !== undefined) layout['paper_bgcolor'] = profile.paperBackground; + if (profile.plotBackground !== undefined) layout['plot_bgcolor'] = profile.plotBackground; + if (profile.font) { + // A larger inherited legend/tick font can hide multicategory labels on + // narrow cards. Bound only the optional profile enlargement, not the source. + const narrowCategories = profile.axisLabels?.enabled && availableWidth !== undefined && availableWidth > 0 && availableWidth < 360 + && record(layout['xaxis']) && ['category', 'multicategory'].includes(String(layout['xaxis']['type'])) + && figure.data.every(trace => ['scatter', 'bar'].includes(String(trace['type']))); + layout['font'] = { ...(record(layout['font']) ? layout['font'] : {}), ...profile.font, + ...(narrowCategories && profile.font.size !== undefined && profile.font.size > 12 ? { size: 12 } : {}) }; + } + if (profile.margin) layout['margin'] = { ...(record(layout['margin']) ? layout['margin'] : {}), ...profile.margin }; + if (profile.grid) { + for (const key of Object.keys(layout).filter(key => /^[xy]axis\d*$/.test(key))) { + const axis = layout[key]; + if (!record(axis)) continue; + layout[key] = { ...axis, + ...(profile.grid.color !== undefined ? { gridcolor: profile.grid.color } : {}), + ...(profile.grid.visible !== undefined ? { showgrid: profile.grid.visible } : {}), + }; + } + } + // Respect fixed-size figures and animated layouts. No width feedback loop. + if (profile.minimumHeight !== undefined && Number.isFinite(profile.minimumHeight) && profile.minimumHeight > 0 + && !figure.frames?.length && layout['autosize'] !== false && layout['width'] === undefined + && (layout['height'] === undefined || typeof layout['height'] === 'number')) { + layout['height'] = Math.max(typeof layout['height'] === 'number' ? layout['height'] : 620, profile.minimumHeight); + } +} + +function relaxFooterMargin(figure: PlotlyFigure) { + const layout = figure.layout, axis = layout['xaxis'], margin = layout['margin']; + const template = layout['template']; + const templateLayout = record(template) ? template['layout'] : undefined; + const templateAxis = record(templateLayout) ? templateLayout['xaxis'] : undefined; + const legend = layout['legend']; + // Only the known footer reserve on a single, automatic Cartesian axis. + // Multicategory ticks, lower legends and other paper objects keep their space. + if (!record(axis) || !record(margin) || margin['b'] !== 150 + || (axis['automargin'] !== true && !(record(templateAxis) && templateAxis['automargin'] === true)) + || axis['type'] === 'multicategory' || figure.data.some(trace => !['scatter', 'bar', 'box'].includes(String(trace['type'])) + || (Array.isArray(trace['x']) && trace['x'].some(Array.isArray))) + || Object.keys(layout).some(key => /^[xy]axis[1-9]\d*$/.test(key)) + || ['shapes', 'images', 'sliders', 'updatemenus'].some(key => layout[key] !== undefined) + || (record(legend) && (legend['orientation'] === 'h' || (typeof legend['y'] === 'number' && legend['y'] <= 0))) + || layout['autosize'] === false || layout['width'] !== undefined || layout['height'] !== undefined) return; + layout['margin'] = { ...margin, b: 80 }; +} export function figureTitle(figure: PlotlyFigure, fallback: string): string { const title = figure.layout['title']; @@ -9,7 +107,8 @@ export function figureTitle(figure: PlotlyFigure, fallback: string): string { } // Adapt only the dashboard copy; HTTP figures and all observations stay intact. -export function presentationFigure(original: PlotlyFigure, selection: FigureSelection): PlotlyFigure { +export function figurePresentation(original: PlotlyFigure, selection: FigureSelection, + profile: FigureVisualProfile = BASE_VISUAL_PROFILE, availableWidth?: number): FigurePresentation { const figure = structuredClone(original); const title = figure.layout['title']; figure.layout['title'] = title && typeof title === 'object' ? { ...title, text: '' } : { text: '' }; @@ -27,5 +126,36 @@ export function presentationFigure(original: PlotlyFigure, selection: FigureSele tickangle: 0, automargin: true, }; } - return figure; + const footnotes: string[] = []; + const annotations = figure.layout['annotations']; + // Frames may reintroduce annotations. Keep animated figures entirely in Plotly. + if (!figure.frames?.length && Array.isArray(annotations)) { + figure.layout['annotations'] = annotations.filter(annotation => { + const text = footerText(annotation, selection); + if (text === undefined) return true; + footnotes.push(text); + return false; + }); + // Only the previously verified TEA reserve can be relaxed. Newly supported + // families keep their margins, legends, colorbars and fixed dimensions. + if (footnotes.length && selection.dominio === 'tea' && TEA_FOOTER_FIGURES.has(selection.figura) + && (figure.layout['annotations'] as unknown[]).length === 0) relaxFooterMargin(figure); + } + applyVisualProfile(figure, profile, availableWidth); + const minimumPlotWidth = profile.axisLabels?.enabled && Number.isFinite(availableWidth) && availableWidth! > 0 + && selection.dominio === 'tea' && ['fig_c1_grupos', 'fig_c2_apiladas'].includes(selection.figura) + ? categoryMinimumWidth(figure) : undefined; + const categoryLabels = applyAxisLabels(figure, profile.axisLabels, availableWidth); + if (minimumPlotWidth !== undefined && !categoryLabels.length + && figure.data.every(trace => Array.isArray(trace['x']) && !trace['x'].some(Array.isArray))) { + figure.layout['xaxis'] = { ...(record(figure.layout['xaxis']) ? figure.layout['xaxis'] : {}), + type: 'category', tickmode: 'linear', dtick: 1, automargin: true }; + } + return { figure, footnotes, categoryLabels, minimumPlotWidth }; +} + +// Compatibility for existing consumers that only need the Plotly copy. +export function presentationFigure(original: PlotlyFigure, selection: FigureSelection, + profile: FigureVisualProfile = BASE_VISUAL_PROFILE): PlotlyFigure { + return figurePresentation(original, selection, profile).figure; } diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts index 7d69942..75b325d 100644 --- a/src/app/shared/plotly/plotly-chart.spec.ts +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -36,6 +36,32 @@ describe('PlotlyChart lifecycle', () => { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); expect(fixture.componentInstance.status()).toBe('ready'); fixture.destroy(); }); + it('UX-07C comunica sólo cambios reales de ancho, agrupa notificaciones y cancela al destruir', async () => { + const frames: FrameRequestCallback[] = [], cancel = vi.fn(), disconnect = vi.fn(); + let notify!: ResizeObserverCallback; + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frames.push(callback); return frames.length; }); + vi.stubGlobal('cancelAnimationFrame', cancel); + vi.stubGlobal('ResizeObserver', class { + constructor(callback: ResizeObserverCallback) { notify = callback; } + observe = vi.fn(); disconnect = disconnect; + }); + const fixture = TestBed.createComponent(PlotlyChart), widths: number[] = []; + fixture.componentInstance.widthChanged.subscribe(width => widths.push(width)); + fixture.componentRef.setInput('figure', { data: [], layout: {} }); fixture.detectChanges(); + const host = fixture.nativeElement.querySelector('.plot') as HTMLElement; + let width = 640; + vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => ({ width } as DOMRect)); + const resize = () => notify([], {} as ResizeObserver); + const flush = () => frames.splice(0).forEach(callback => callback(0)); + const pending = frames.length; // Angular may also schedule a render frame. + resize(); resize(); expect(frames).toHaveLength(pending); + flush(); expect(widths).toEqual([640]); + resize(); flush(); expect(widths).toEqual([640]); // Height-only notification. + width = 900; resize(); flush(); expect(widths).toEqual([640, 900]); + width = 0; resize(); flush(); expect(widths).toEqual([640, 900]); // Hidden host. + resize(); fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(cancel).toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); }); diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts index ba2ea24..e5015ab 100644 --- a/src/app/shared/plotly/plotly-chart.ts +++ b/src/app/shared/plotly/plotly-chart.ts @@ -22,7 +22,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
} `, - styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, + styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-width: var(--plot-min-width, 0px); min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, }) export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input() showNotes = true; @@ -30,6 +30,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); + readonly widthChanged = output(); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); get notes(): string[] { const annotations = this.figure?.layout['annotations']; @@ -40,7 +41,17 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { private readonly loadPlotly = inject(PLOTLY_LOADER); private controller?: PlotlyController; private observer?: ResizeObserver; - private readonly windowResize = () => this.controller?.resize(); + private lastWidth = 0; + private widthFrame?: number; + private readonly windowResize = () => { + this.controller?.resize(); + if (this.widthFrame !== undefined) return; + this.widthFrame = requestAnimationFrame(() => { + this.widthFrame = undefined; + const width = Math.floor(this.host.nativeElement.getBoundingClientRect().width); + if (width > 0 && width !== this.lastWidth) { this.lastWidth = width; this.widthChanged.emit(width); } + }); + }; ngAfterViewInit() { this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { this.status.set(state); @@ -51,11 +62,14 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { this.observer.observe(this.host.nativeElement); } else window.addEventListener('resize', this.windowResize); this.controller.setFigure(this.figure); + // Also supply the initial width in browsers without ResizeObserver. + this.windowResize(); } ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); } retry() { this.controller?.setFigure(this.figure); } ngOnDestroy() { this.observer?.disconnect(); + if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame); window.removeEventListener('resize', this.windowResize); this.controller?.destroy(); } From 1fc23bd0bdb61919c6b4912a4d93b3c8fa562d1d Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 15 Oct 2026 22:23:39 +0000 Subject: [PATCH 20/51] =?UTF-8?q?TEA:=20indicadores=20destacados=20(M23?= =?UTF-8?q?=E2=80=93M25),=20ocultar=20indicadores=20y=20renombrar=20a=20pa?= =?UTF-8?q?cientes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores/indicador-kpi-panel.spec.ts | 17 +++++++++--- .../indicadores-global-filters.spec.ts | 14 +++++----- .../indicadores/indicadores-kpi.spec.ts | 26 +++++++++++++----- .../features/indicadores/indicadores-kpi.ts | 27 ++++++++++++++----- .../indicadores-navigation.spec.ts | 6 ++--- .../indicadores/indicadores-page.spec.ts | 16 ++++++----- .../indicadores-periodos.testing.ts | 7 ++++- .../indicadores-plotly-lifecycle.spec.ts | 4 +-- .../indicadores/indicadores-search.spec.ts | 6 ++--- .../indicadores-visibility.spec.ts | 8 +++--- 10 files changed, 87 insertions(+), 44 deletions(-) diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 6a0676b..6c0efd1 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -27,15 +27,24 @@ describe('KPI integración con autoridad global', () => { function requests() { return http.match(r => r.url.endsWith('/datos')); } 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: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] }; + { periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] }; } function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') { const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] }; fixture.componentInstance.applyFilters(); fixture.detectChanges(); } - it('TEA sin definiciones oculta toda la sección y no consulta datos', () => { - expect(fixture.nativeElement.querySelector('.kpi-section, #kpi-section-title, .kpi-grid')).toBeNull(); - expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(0); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); + it('TEA sin catálogo muestra sus tres destacados sin consultar datos', () => { + expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); + expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.tea.map(d => d.id)); + expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); + }); + it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => { + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]); + load('tea'); const req = requests(); + expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.map(d => '/tea/indicadores/' + d.id + '/datos')); + req.forEach((r, i) => r.flush(response(i, 'tea'))); fixture.detectChanges(); + expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]); + expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.'); }); it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => { load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true); diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts index 06ce761..ff3e0bf 100644 --- a/src/app/features/indicadores/indicadores-global-filters.spec.ts +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -23,7 +23,7 @@ describe('D.2 integración de autoridad global y consumidores', () => { let http: HttpTestingController; beforeEach(() => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); }); @@ -59,10 +59,10 @@ describe('D.2 integración de autoridad global y consumidores', () => { expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]); - expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(domain === 'tea' ? 0 : 3); - expect(sections[domain === 'tea' ? 1 : 2].getAttribute('aria-labelledby')).toBe('graphic-section-title'); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(3); + expect(sections[2].getAttribute('aria-labelledby')).toBe('graphic-section-title'); expect(page.filters!.applied.selection.mode).toBe('todos'); - expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(domain === 'tea'); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); http.expectNone(() => true); }); it('edición y vacío no consultan ni cambian el resultado vigente', () => { @@ -128,7 +128,7 @@ describe('D.2 integración de autoridad global y consumidores', () => { load(); open(); respond(); const host = fixture.nativeElement.querySelector('app-plotly-chart'); draft('semestre', ['2025-S1']); apply(); const old = request('a'); expect(panels()[0].result().figure).toBeUndefined(); expect((host as HTMLElement).parentElement!.hidden).toBe(true); - editor().unit = 'S2'; editor().add(); apply(); const current = request('a'); + editor().year = '2025'; editor().unit = 'S2'; editor().add(); apply(); const current = request('a'); expect(old.cancelled).toBe(true); current.flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges(); expect(panels()[0].result().figure!.data[0]['y']).toEqual([7]); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); expect((host as HTMLElement).parentElement!.hidden).toBe(false); @@ -142,7 +142,7 @@ describe('D.2 integración de autoridad global y consumidores', () => { }); it('dominio durante carga cancela saliente y restaura borrador separado del aplicado', () => { load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('a'); - editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges(); + editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges(); expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos'); draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load(); expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index 9243dcb..0d1f655 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -6,26 +6,28 @@ const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 function data(domain: Dominio, index: number, filas: Record[]): IndicadorDatos { const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas }; } -describe.each(['cacu', 'cama'] as const)('KPI %s', domain => { +describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => { + const c1Group = domain === 'tea' ? 'TOTAL' : 'total'; const run = (index: number, rows: Record[]) => kpiResult(data(domain, index, rows), KPI_BY_DOMAIN[domain][index], domain, applied); it('C2 suma categorías disjuntas del único TOTAL incluyendo SIN_DATO y cero', () => { expect(run(0, [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'SIN_DATO', n: 0 }]).value).toBe(5); expect(run(0, [{ ...total, categoria: 'A', n: 0 }]).value).toBe(0); }); it('C1 consume porcentaje sin recalcular y muestra numerador y denominador', () => { - const result = run(1, [{ ...total, grupo: 'total', valor: 33.36, numerador: 2, denominador: 6 }]); + const result = run(1, [{ ...total, grupo: c1Group, valor: 33.36, numerador: 2, denominador: 6 }]); expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6'); - expect(run(1, [{ ...total, grupo: 'total', valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0'); + expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0'); }); - it('C3r conserva mediana cero y Q1/Q3, referencia provisional', () => { + it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => { const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]); - expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días'); expect(result.info).toContain('provisional'); + expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días'); + if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional'); }); it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => { - expect(run(index, [{ ...total, grupo: index === 1 ? 'total' : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' }); + expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' }); }); it.each([0, 1, 2])('nulos en %s no se convierten en cero', index => { - const result = run(index, [{ ...total, grupo: index === 1 ? 'total' : 'TOTAL', categoria: 'A', n: null, valor: null, mediana: null }]); + const result = run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: null, valor: null, mediana: null }]); expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible'); }); it('no suma grupos superpuestos, estratos ni categorías duplicadas', () => { @@ -48,3 +50,13 @@ it('categorías incompletas nunca producen un total parcial', () => { const d = data('cacu', 0, [{ ...total, categoria: 'A', n: 5 }]); d['categorias'] = { A: {}, B: {} }; expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined(); }); + +it('TEA usa sus tres indicadores destacados y su grupo C1 es TOTAL', () => { + expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([ + ['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r']]); + const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]); + expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0', + info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' }); + expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state) + .toBe('Selección no consolidable'); +}); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index ba69a36..2cd74f6 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -7,11 +7,28 @@ const definitions = (): KpiDefinition[] => [ { id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%' }, { id: '', title: 'Días de la toma al resultado', contrato: 'C3r', unit: 'días (mediana)' }, ]; +const TEA_KPI: KpiDefinition[] = [ + { id: 'M23_pacientes_evaluados', title: 'Pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, + { id: 'M24_confirmacion_diagnostico', title: 'Confirmación de diagnóstico', contrato: 'C1', unit: '%' }, + { id: 'M25_dias_mchat_diagnostico', title: 'Días de M-CHAT a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, +]; export const KPI_BY_DOMAIN: Record = { - tea: [], + tea: TEA_KPI, cacu: definitions().map((d, i) => ({ ...d, id: ['cacu_eu7', 'cacu_eu13', 'cacu_eu_tiempo_reporte'][i] })), cama: definitions().map((d, i) => ({ ...d, id: ['cama_birads', 'cama_confirmacion_birads45', 'cama_eu38a'][i] })), }; +// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. +const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; +const C1_INFO: Record string> = { + tea: (n, d) => `${n} de ${d} pacientes con nota médica con diagnóstico CIE-10 F84.0.`, + cacu: (n, d) => `${n} de ${d} pacientes con lesión de alto grado o mayor en biopsia.`, + cama: (n, d) => `${n} de ${d} mastografías BI-RADS 4 y 5 con reporte de biopsia.`, +}; +const C3R_INFO: Record string> = { + tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`, + cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. La referencia de 60 días es provisional.`, + cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. La referencia de 60 días es provisional.`, +}; export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; } const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0; @@ -29,7 +46,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped; const rows = data.filas; if (!rows.length) return { state: 'Sin filas utilizables' }; - const group = definition.contrato === 'C1' ? 'total' : 'TOTAL'; + const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL'; if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped; if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped; if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' }; @@ -50,10 +67,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; - return { state: 'Disponible', value: row['valor'].toFixed(1), info: domain === 'cacu' - ? `${row['numerador']} de ${row['denominador']} pacientes con lesión de alto grado o mayor en biopsia.` - : `${row['numerador']} de ${row['denominador']} mastografías BI-RADS 4 y 5 con reporte de biopsia.` }; + return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) }; } if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; - return { state: 'Disponible', value: row['mediana'], info: `${row['n']} ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: ${row['q1']} a ${row['q3']} días. La referencia de 60 días es provisional.` }; + return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; } diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index c77b088..c2cb052 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -23,7 +23,7 @@ describe('UX-04 navegación Angular', () => { let http: HttpTestingController; async function setup() { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); - TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); return RouterTestingHarness.create(); @@ -76,7 +76,7 @@ describe('UX-04 navegación Angular', () => { control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add(); (harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges(); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} }); - control.unit = 'S2'; control.add(); + control.year = '2025'; control.unit = 'S2'; control.add(); await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu', harness); await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama', harness); const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 67eb0b6..abd357e 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -41,12 +41,14 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } + function kpiMissing() { http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); fixture.detectChanges(); } function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } - it('KPI-DYNAMIC TEA no deja sección, encabezado, tarjetas ni grid residual', () => { + it('KPI-DYNAMIC TEA muestra sus tres destacados sin consultar datos fuera del catálogo', () => { load(); - expect(fixture.nativeElement.querySelector('.kpi-section, #kpi-section-title, .kpi-grid, app-indicador-kpi-card')).toBeNull(); - expect(fixture.nativeElement.textContent).not.toContain('Indicadores destacados'); + expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); + expect(Array.from(fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')).map(h => (h as HTMLElement).textContent)) + .toEqual(['Pacientes evaluados', 'Confirmación de diagnóstico', 'Días de M-CHAT a diagnóstico']); http.expectNone(r => r.url.endsWith('/datos')); }); it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { @@ -61,7 +63,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { page.retryCatalog(); fixture.detectChanges(); load([]); expect(page.catalogLoading()).toBe(false); expect(page.catalogError()).toBe(''); expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); - expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(3); http.expectNone(() => true); }); it('D.1 separa secciones y conserva tarjetas, orden, identidades y figuras dentro del grid', () => { @@ -71,7 +73,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(grid.children).toHaveLength(2); expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true); const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; - expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']); + expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right'); toggle(0); toggle(1); flushAll(); @@ -190,7 +192,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { page.applyFilters(); fixture.detectChanges(); const appliedA = request('f1'); expect(appliedA.request.params.get('periodos')).toBe('2025-S1'); - appliedA.flush({ data: [], layout: {} }); a.unit = 'S2'; a.add(); + appliedA.flush({ data: [], layout: {} }); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add(); page.changeTema('oscuro'); fixture.detectChanges(); const themedA = request('f1'); expect(themedA.request.params.get('periodos')).toBe('2025-S1'); @@ -216,7 +218,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { }); it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => { load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); - page.applyFilters(); fixture.detectChanges(); flushAll(); a.unit = 'S2'; a.add(); + page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add(); cards()[0].setVisible(false); fixture.detectChanges(); toggle(); expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-periodos.testing.ts b/src/app/features/indicadores/indicadores-periodos.testing.ts index adabe64..5cee482 100644 --- a/src/app/features/indicadores/indicadores-periodos.testing.ts +++ b/src/app/features/indicadores/indicadores-periodos.testing.ts @@ -1,6 +1,7 @@ -import { of } from 'rxjs'; +import { NEVER, of } from 'rxjs'; import { Indicador } from './indicadores.models'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; +import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; // Existing figure/search/visibility suites isolate their HTTP from availability. // The new P0.1 suites exercise the real availability HTTP separately. @@ -16,3 +17,7 @@ export const periodAvailabilityProvider = { return of(state); } }, }; + +// Figure/search/visibility suites also isolate their HTTP from the KPI panels, +// which every domain (TEA included) now renders. KPI suites use the real queries. +export const kpiQueriesProvider = { provide: IndicadoresKpiQueries, useValue: { datos: () => NEVER } }; diff --git a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts index f02e6a9..51019e9 100644 --- a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts +++ b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -23,7 +23,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => // Material outline labels also observe size; track only Plotly hosts here. observe = vi.fn((target: Element) => { if (target.classList.contains('plot')) disconnects.push(this.disconnect); }); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); fixture = TestBed.createComponent(IndicadoresPage); vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts index 660a706..ad8db27 100644 --- a/src/app/features/indicadores/indicadores-search.spec.ts +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -33,7 +33,7 @@ describe('UX-05C búsqueda local y partición estable', () => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); @@ -143,7 +143,7 @@ describe('UX-05C búsqueda local y partición estable', () => { const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); page.applyFilters(); fixture.detectChanges(); respond(); await settle(); - c.unit = 'S2'; c.add(); c.year = '2026'; + c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026'; fixture.detectChanges(); await settle(); const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result()); const titleIds = beforePanels.map(p => p.titleId); diff --git a/src/app/features/indicadores/indicadores-visibility.spec.ts b/src/app/features/indicadores/indicadores-visibility.spec.ts index eae5fea..5aacf8e 100644 --- a/src/app/features/indicadores/indicadores-visibility.spec.ts +++ b/src/app/features/indicadores/indicadores-visibility.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -69,7 +69,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { sticky = document.createElement('header'); sticky.className = 'institutional-header'; document.body.append(sticky); geometry.set(sticky, rect(0, 0, 1440, 100)); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); create(); @@ -137,7 +137,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle(); const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render(); - filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle(); + filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle(); expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred'); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); @@ -209,7 +209,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { }); it('hosts Plotly permanecen montados fuera de vista y se purgan al destruir', async () => { http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); await render(); for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart, host = chart.host.nativeElement; From d9462283195b5bec0fea668d4e029c5a306b612f Mon Sep 17 00:00:00 2001 From: rodrigo Date: Fri, 16 Oct 2026 07:09:36 +0000 Subject: [PATCH 21/51] =?UTF-8?q?Destacados:=20t=C3=ADtulos=20de=20los=20T?= =?UTF-8?q?OML=20y=20Tiempo=20de=20tamizaje=20a=20diagn=C3=B3stico?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Los títulos de las tarjetas de indicadores destacados son ahora los `title` de los TOML del kit (M23, M24, M25, cacu_eu7, cacu_eu13, cama_birads, cama_confirmacion_birads45), copiados a mano: solución provisional hasta que las tarjetas lean el `titulo` que ya manda la API. - La tercera tarjeta de CaCu y CaMa pasa de los días de la toma al resultado (cacu_eu_tiempo_reporte, cama_eu38a) a los días de la toma al diagnóstico (cacu_dias_toma_diagnostico, cama_dias_toma_diagnostico), «Tiempo de tamizaje a diagnóstico», con su horizonte provisional de 180 días. CSO5.5 Co-Authored-By: Claude Opus 5.5 --- .../features/indicadores/indicadores-kpi.ts | 35 +++++++++++-------- .../indicadores/indicadores-page.spec.ts | 2 +- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 2cd74f6..fe55b4c 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -2,20 +2,25 @@ import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } -const definitions = (): KpiDefinition[] => [ - { id: '', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, - { id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%' }, - { id: '', title: 'Días de la toma al resultado', contrato: 'C3r', unit: 'días (mediana)' }, -]; -const TEA_KPI: KpiDefinition[] = [ - { id: 'M23_pacientes_evaluados', title: 'Pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, - { id: 'M24_confirmacion_diagnostico', title: 'Confirmación de diagnóstico', contrato: 'C1', unit: '%' }, - { id: 'M25_dias_mchat_diagnostico', title: 'Días de M-CHAT a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, -]; +// Provisional (oct 2026): each title is the `title` of the indicator's TOML in indicadores_kit, +// copied by hand. If a TOML title changes, change it here too, until the cards read the +// `titulo` that the API already sends. export const KPI_BY_DOMAIN: Record = { - tea: TEA_KPI, - cacu: definitions().map((d, i) => ({ ...d, id: ['cacu_eu7', 'cacu_eu13', 'cacu_eu_tiempo_reporte'][i] })), - cama: definitions().map((d, i) => ({ ...d, id: ['cama_birads', 'cama_confirmacion_birads45', 'cama_eu38a'][i] })), + tea: [ + { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, + { id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' }, + { id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' }, + ], + cacu: [ + { id: 'cacu_eu7', title: 'Distribución de resultados citológicos', contrato: 'C2', unit: 'pacientes' }, + { id: 'cacu_eu13', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, + { id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + ], + cama: [ + { id: 'cama_birads', title: 'Distribución de BI-RADS', contrato: 'C2', unit: 'pacientes' }, + { id: 'cama_confirmacion_birads45', title: 'Mastografías BI-RADS 4 y 5 con reporte de biopsia', contrato: 'C1', unit: '%' }, + { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + ], }; // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; @@ -26,8 +31,8 @@ const C1_INFO: Record strin }; const C3R_INFO: Record string> = { tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`, - cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. La referencia de 60 días es provisional.`, - cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. La referencia de 60 días es provisional.`, + cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, + cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, }; export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; } const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index abd357e..65f04e7 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -48,7 +48,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { load(); expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); expect(Array.from(fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')).map(h => (h as HTMLElement).textContent)) - .toEqual(['Pacientes evaluados', 'Confirmación de diagnóstico', 'Días de M-CHAT a diagnóstico']); + .toEqual(['Total de pacientes evaluados', 'Porcentaje de confirmación diagnóstica', 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo']); http.expectNone(r => r.url.endsWith('/datos')); }); it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { From 30946823c497310c0398f74b096c55a096b28dbb Mon Sep 17 00:00:00 2001 From: rodrigo Date: Fri, 16 Oct 2026 07:16:51 +0000 Subject: [PATCH 22/51] =?UTF-8?q?CaMa:=20t=C3=ADtulo=20=C2=ABTasa=20de=20c?= =?UTF-8?q?onfirmaci=C3=B3n=20histopatol=C3=B3gica=C2=BB,=20como=20en=20Ca?= =?UTF-8?q?Cu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Título de cama_confirmacion_birads45 (usuario, 2026-10-16), en el TOML y en la tarjeta de indicadores destacados. Solo cambia el texto. CSO5.5 Co-Authored-By: Claude Opus 5.5 --- src/app/features/indicadores/indicadores-kpi.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index fe55b4c..7e5b9f5 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -18,7 +18,7 @@ export const KPI_BY_DOMAIN: Record = { ], cama: [ { id: 'cama_birads', title: 'Distribución de BI-RADS', contrato: 'C2', unit: 'pacientes' }, - { id: 'cama_confirmacion_birads45', title: 'Mastografías BI-RADS 4 y 5 con reporte de biopsia', contrato: 'C1', unit: '%' }, + { 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)' }, ], }; From 2cf3a5a40dfeacdfcb4880b6427c68229920a1cf Mon Sep 17 00:00:00 2001 From: rodrigo Date: Fri, 16 Oct 2026 07:39:08 +0000 Subject: [PATCH 23/51] =?UTF-8?q?Destacados:=20la=20tasa=20de=20confirmaci?= =?UTF-8?q?=C3=B3n=20de=20CaMa=20con=20su=20indicador=20oculto,=20y=20paci?= =?UTF-8?q?entes=20evaluadas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - cama_confirmacion_birads45 está `oculto` en su TOML a propósito (no sale en el catálogo ni tiene gráfica), pero su tarjeta destacada se quedaba en «Sin reportes disponibles» con el filtro por omisión: la disponibilidad y la tarjeta solo miraban el catálogo. Una definición marcada `hiddenInCatalog` pide sus periodos y datos por su id, que WebApi sigue sirviendo; no aparece en los indicadores gráficos. Las demás tarjetas no cambian. - Primera tarjeta: «Pacientes evaluadas» (cacu_eu7) y «Pacientes evaluadas con BI-RADS 4, 5 y 6», que suma las categorías de cama_birads_456_paciente. - Pruebas: indicadores-kpi-ocultos.spec.ts (con el catálogo real de CaMa), indicadores-kpi-cama-real.spec.ts (respuestas reales de WebApi sobre una base montada por dev-data: 31 pacientes, 66.7 % y la mediana del C3r). Las suites de catálogo y fijación aíslan sus peticiones de las tarjetas (kpiQueriesProvider), como las demás. CSO5.5 Co-Authored-By: Claude Opus 5.5 --- .../indicadores-kpi-cama-real.spec.ts | 154 ++++++++++++++++++ .../indicadores-kpi-ocultos.spec.ts | 57 +++++++ .../features/indicadores/indicadores-kpi.ts | 27 ++- .../indicadores/indicadores-page.html | 2 +- .../indicadores/indicadores-page.spec.ts | 4 +- .../features/indicadores/indicadores-page.ts | 8 +- .../indicadores/indicadores-pinning.spec.ts | 4 +- 7 files changed, 240 insertions(+), 16 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts create mode 100644 src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts diff --git a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts new file mode 100644 index 0000000..349df3d --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts @@ -0,0 +1,154 @@ +import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi'; +import { IndicadorDatos } from './indicadores.models'; + +// /cama/indicadores//datos?periodos=2025-S2 as WebApi served it (oct 2026) over a CaMa base +// mounted by dev-data (n = 300, semilla 7, referencia 2026-01-01), trimmed to what the card reads. +const DATOS_2025_S2: Record = { + "cama_birads_456_paciente": { + "id": "cama_birads_456_paciente", + "contrato": "C2", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "categorias": { + "B4": {}, + "B4A": {}, + "B4B": {}, + "B4C": {}, + "B5": {}, + "B6": {}, + "SIN_DATO": {} + }, + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4", + "n": 0, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4A", + "n": 9, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4B", + "n": 0, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B4C", + "n": 4, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B5", + "n": 18, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "B6", + "n": 0, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_DATO", + "n": 0, + "orden": 6, + "suprimido": 0 + } + ] + }, + "cama_confirmacion_birads45": { + "id": "cama_confirmacion_birads45", + "contrato": "C1", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "categorias": {}, + "filas": [ + { + "periodo": "2025-S2", + "grupo": "total", + "estrato": null, + "numerador": 22, + "denominador": 33, + "valor": 66.6666666667, + "ic_bajo": 49.6078942936, + "ic_alto": 80.2497724059, + "suprimido": 0, + "n_sin_evento": 11, + "n_excluido": 0 + } + ] + }, + "cama_dias_toma_diagnostico": { + "id": "cama_dias_toma_diagnostico", + "contrato": "C3r", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "categorias": {}, + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "n": 25, + "mediana": 42.0, + "q1": 24.0, + "q3": 76.0, + "n_sin_evento": 0, + "n_excluido": 58, + "suprimido": 0, + "unidad": "dias" + } + ] + } +}; + +describe('KPI de CaMa con respuestas reales de WebApi', () => { + const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 }; + const result = (index: number) => kpiResult(DATOS_2025_S2[KPI_BY_DOMAIN.cama[index].id], KPI_BY_DOMAIN.cama[index], 'cama', applied); + + it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => { + expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 })); + }); + it('tasa de confirmación histopatológica: el valor del C1', () => { + expect(result(1)).toEqual(expect.objectContaining({ state: 'Disponible', value: '66.7' })); + expect(result(1).info).toBe('22 de 33 mastografías BI-RADS 4 y 5 con reporte de biopsia.'); + }); + it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => { + expect(result(2).state).toBe('Disponible'); + expect(result(2).info).toContain('El horizonte de 180 días es provisional.'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts b/src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts new file mode 100644 index 0000000..06a11bf --- /dev/null +++ b/src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts @@ -0,0 +1,57 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { IndicadorDatos } from './indicadores.models'; + +// The CaMa catalog as WebApi serves it with indicadores_kit v0.6.0: `cama_birads` and +// `cama_confirmacion_birads45` are `oculto` in their TOML, so they are not listed, but +// WebApi still answers /periodos and /datos for their ids. +const CATALOGO_CAMA = ['cama_biopsias', 'cama_birads_456_mastografia', 'cama_birads_456_paciente', 'cama_dias_toma_diagnostico', 'cama_eu38a'] + .map(id => ({ id, titulo: id, contrato: id.includes('dias') || id.includes('eu38a') ? 'C3r' : 'C2', figuras: [], tipos_periodo: ['semestre', 'mes'] })); +const CONFIRMACION = 'cama_confirmacion_birads45'; + +describe('KPI de un indicador oculto en el catálogo', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + 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(); + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + http.expectOne('/cama/indicadores').flush(CATALOGO_CAMA); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.match(() => true); vi.unstubAllGlobals(); }); + const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)) + .map(e => e.componentInstance as IndicadorKpiPanel).find(p => p.definition.id === id)!; + + it('pide los periodos del oculto y muestra la tasa de su último periodo con datos', () => { + expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toContain(CONFIRMACION); + // Availability asks four at a time: answer until no /periodos request is left. + const pedidos: string[] = []; + for (let pendientes = http.match(r => r.url.endsWith('/periodos')); pendientes.length; pendientes = http.match(r => r.url.endsWith('/periodos'))) { + pendientes.forEach(r => { pedidos.push(r.request.url); r.flush({ id: r.request.url.split('/')[3], periodos: [{ periodo: '2025-S2', tipo: 'semestre' }] }); }); + fixture.detectChanges(); + } + expect(pedidos).toContain(`/cama/indicadores/${CONFIRMACION}/periodos`); + + const datos = http.match(r => r.url === `/cama/indicadores/${CONFIRMACION}/datos`); + expect(datos.map(r => r.request.params.get('periodos'))).toEqual(['2025-S2']); + const respuesta: IndicadorDatos = { + id: CONFIRMACION, contrato: 'C1', tipo_periodo: 'semestre', periodos: ['2025-S2'], categorias: {}, + filas: [{ periodo: '2025-S2', grupo: 'total', estrato: null, numerador: 22, denominador: 33, valor: 66.6666666667, suprimido: 0 }], + }; + datos[0].flush(respuesta); fixture.detectChanges(); + + expect(panel(CONFIRMACION).result().state).toBe('Disponible'); + expect(panel(CONFIRMACION).result().value).toBe('66.7'); + }); + + it('el oculto no aparece en los indicadores gráficos', () => { + expect(fixture.componentInstance.catalog().map(i => i.id)).not.toContain(CONFIRMACION); + }); +}); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 7e5b9f5..f2c9fbc 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -1,10 +1,11 @@ -import { Dominio, IndicadorDatos } from './indicadores.models'; +import { Dominio, Indicador, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; -export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } -// Provisional (oct 2026): each title is the `title` of the indicator's TOML in indicadores_kit, -// copied by hand. If a TOML title changes, change it here too, until the cards read the -// `titulo` that the API already sends. +export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; hiddenInCatalog?: boolean; } +// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML +// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories +// (patients), not the distribution. If a TOML title changes, change it here too, until the +// cards read the `titulo` that the API already sends. export const KPI_BY_DOMAIN: Record = { tea: [ { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, @@ -12,16 +13,26 @@ export const KPI_BY_DOMAIN: Record = { { id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' }, ], cacu: [ - { id: 'cacu_eu7', title: 'Distribución de resultados citológicos', contrato: 'C2', unit: 'pacientes' }, + { id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, { id: 'cacu_eu13', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, { id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, ], cama: [ - { id: 'cama_birads', title: 'Distribución de BI-RADS', contrato: 'C2', unit: 'pacientes' }, - { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, + { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, + { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%', hiddenInCatalog: true }, { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, ], }; +// A KPI marked `hiddenInCatalog` has its indicator `oculto` in its TOML on purpose: it is +// not in the catalog (no graphic card), but WebApi still answers its /periodos and /datos. +// These are its catalog entries, built from the definition and without figures: only the +// KPI cards and the period availability use them. Nothing until the catalog has loaded. +// Any other KPI missing from the catalog keeps the usual behavior (no query). +export function hiddenKpiIndicators(catalog: readonly Indicador[], kpis: readonly KpiDefinition[]): Indicador[] { + if (!catalog.length) return []; + return kpis.filter(d => d.hiddenInCatalog && !catalog.some(item => item.id === d.id)) + .map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })); +} // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; const C1_INFO: Record string> = { diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 73e9689..1985d09 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -26,7 +26,7 @@

La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.

@for (definition of kpis; track dominio + ':' + definition.id) { - }
diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 65f04e7..a4a7271 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -27,7 +27,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { let http: HttpTestingController; beforeEach(() => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 90fbfdc..6063cce 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -16,7 +16,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { KPI_BY_DOMAIN, KpiDefinition, hiddenKpiIndicators } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; @@ -169,7 +169,9 @@ export class IndicadoresPage { dominio: Dominio = 'tea'; readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly kpisByDomain = KPI_BY_DOMAIN; - kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } + /** The catalog plus the KPIs it hides: what the KPI cards and the period availability read. */ + kpiSources() { return [...this.catalog(), ...hiddenKpiIndicators(this.catalog(), this.kpisByDomain[this.dominio])]; } + kpiIndicator(definition: KpiDefinition) { return this.kpiSources().find(item => item.id === definition.id); } get availableKpis() { return this.kpisByDomain[this.dominio]; } get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); } private readonly catalogRequests = new Subject(); @@ -235,7 +237,7 @@ export class IndicadoresPage { this.tema = this.memory.theme(this.dominio); this.availabilityRequests.pipe(switchMap(() => { this.availability.set(emptyAvailability()); - return this.periodService.dominio(this.dominio, this.catalog()); + return this.periodService.dominio(this.dominio, this.kpiSources()); }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { this.clearVisibility(); diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index 8906a5e..5c39c46 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -1,4 +1,4 @@ -import { periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -25,7 +25,7 @@ describe('UX-06E.D.3.B fijación temporal', () => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); load(); }); From 1eda9eea29ea8e83b9412e45cf4ba5690d89283e Mon Sep 17 00:00:00 2001 From: rodrigo Date: Fri, 16 Oct 2026 07:48:21 +0000 Subject: [PATCH 24/51] =?UTF-8?q?CaMa:=20la=20tasa=20de=20confirmaci=C3=B3?= =?UTF-8?q?n=20histopatol=C3=B3gica=20vuelve=20al=20cat=C3=A1logo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cama_confirmacion_birads45 deja de estar oculto (usuario, 2026-10-16): se ve su tarjeta destacada con el filtro por omisión y su gráfica de tendencia (fig_c1_puntos). Así WebApp no necesita un caso especial para un destacado oculto del catálogo: se revierte ese mecanismo y las pruebas del colaborador quedan como estaban. CSO5.5 Co-Authored-By: Claude Opus 5.5 --- .../indicadores-kpi-ocultos.spec.ts | 57 ------------------- .../features/indicadores/indicadores-kpi.ts | 16 +----- .../indicadores/indicadores-page.html | 2 +- .../indicadores/indicadores-page.spec.ts | 4 +- .../features/indicadores/indicadores-page.ts | 8 +-- .../indicadores/indicadores-pinning.spec.ts | 4 +- 6 files changed, 11 insertions(+), 80 deletions(-) delete mode 100644 src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts diff --git a/src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts b/src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts deleted file mode 100644 index 06a11bf..0000000 --- a/src/app/features/indicadores/indicadores-kpi-ocultos.spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { TestBed } from '@angular/core/testing'; -import { provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { provideRouter } from '@angular/router'; -import { By } from '@angular/platform-browser'; -import { IndicadoresPage } from './indicadores-page'; -import { IndicadorKpiPanel } from './indicador-kpi-panel'; -import { KPI_BY_DOMAIN } from './indicadores-kpi'; -import { IndicadorDatos } from './indicadores.models'; - -// The CaMa catalog as WebApi serves it with indicadores_kit v0.6.0: `cama_birads` and -// `cama_confirmacion_birads45` are `oculto` in their TOML, so they are not listed, but -// WebApi still answers /periodos and /datos for their ids. -const CATALOGO_CAMA = ['cama_biopsias', 'cama_birads_456_mastografia', 'cama_birads_456_paciente', 'cama_dias_toma_diagnostico', 'cama_eu38a'] - .map(id => ({ id, titulo: id, contrato: id.includes('dias') || id.includes('eu38a') ? 'C3r' : 'C2', figuras: [], tipos_periodo: ['semestre', 'mes'] })); -const CONFIRMACION = 'cama_confirmacion_birads45'; - -describe('KPI de un indicador oculto en el catálogo', () => { - let fixture: ReturnType>, http: HttpTestingController; - beforeEach(() => { - 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(); - fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); - http.expectOne('/cama/indicadores').flush(CATALOGO_CAMA); fixture.detectChanges(); - }); - afterEach(() => { fixture.destroy(); http.match(() => true); vi.unstubAllGlobals(); }); - const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)) - .map(e => e.componentInstance as IndicadorKpiPanel).find(p => p.definition.id === id)!; - - it('pide los periodos del oculto y muestra la tasa de su último periodo con datos', () => { - expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toContain(CONFIRMACION); - // Availability asks four at a time: answer until no /periodos request is left. - const pedidos: string[] = []; - for (let pendientes = http.match(r => r.url.endsWith('/periodos')); pendientes.length; pendientes = http.match(r => r.url.endsWith('/periodos'))) { - pendientes.forEach(r => { pedidos.push(r.request.url); r.flush({ id: r.request.url.split('/')[3], periodos: [{ periodo: '2025-S2', tipo: 'semestre' }] }); }); - fixture.detectChanges(); - } - expect(pedidos).toContain(`/cama/indicadores/${CONFIRMACION}/periodos`); - - const datos = http.match(r => r.url === `/cama/indicadores/${CONFIRMACION}/datos`); - expect(datos.map(r => r.request.params.get('periodos'))).toEqual(['2025-S2']); - const respuesta: IndicadorDatos = { - id: CONFIRMACION, contrato: 'C1', tipo_periodo: 'semestre', periodos: ['2025-S2'], categorias: {}, - filas: [{ periodo: '2025-S2', grupo: 'total', estrato: null, numerador: 22, denominador: 33, valor: 66.6666666667, suprimido: 0 }], - }; - datos[0].flush(respuesta); fixture.detectChanges(); - - expect(panel(CONFIRMACION).result().state).toBe('Disponible'); - expect(panel(CONFIRMACION).result().value).toBe('66.7'); - }); - - it('el oculto no aparece en los indicadores gráficos', () => { - expect(fixture.componentInstance.catalog().map(i => i.id)).not.toContain(CONFIRMACION); - }); -}); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index f2c9fbc..b8bc560 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -1,7 +1,7 @@ -import { Dominio, Indicador, IndicadorDatos } from './indicadores.models'; +import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; -export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; hiddenInCatalog?: boolean; } +export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } // Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML // in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories // (patients), not the distribution. If a TOML title changes, change it here too, until the @@ -19,20 +19,10 @@ export const KPI_BY_DOMAIN: Record = { ], cama: [ { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, - { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%', hiddenInCatalog: true }, + { 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)' }, ], }; -// A KPI marked `hiddenInCatalog` has its indicator `oculto` in its TOML on purpose: it is -// not in the catalog (no graphic card), but WebApi still answers its /periodos and /datos. -// These are its catalog entries, built from the definition and without figures: only the -// KPI cards and the period availability use them. Nothing until the catalog has loaded. -// Any other KPI missing from the catalog keeps the usual behavior (no query). -export function hiddenKpiIndicators(catalog: readonly Indicador[], kpis: readonly KpiDefinition[]): Indicador[] { - if (!catalog.length) return []; - return kpis.filter(d => d.hiddenInCatalog && !catalog.some(item => item.id === d.id)) - .map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })); -} // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; const C1_INFO: Record string> = { diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 1985d09..73e9689 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -26,7 +26,7 @@

La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.

@for (definition of kpis; track dominio + ':' + definition.id) { - }
diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index a4a7271..65f04e7 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -1,4 +1,4 @@ -import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -27,7 +27,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { let http: HttpTestingController; beforeEach(() => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 6063cce..90fbfdc 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -16,7 +16,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { KPI_BY_DOMAIN, KpiDefinition, hiddenKpiIndicators } from './indicadores-kpi'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; @@ -169,9 +169,7 @@ export class IndicadoresPage { dominio: Dominio = 'tea'; readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly kpisByDomain = KPI_BY_DOMAIN; - /** The catalog plus the KPIs it hides: what the KPI cards and the period availability read. */ - kpiSources() { return [...this.catalog(), ...hiddenKpiIndicators(this.catalog(), this.kpisByDomain[this.dominio])]; } - kpiIndicator(definition: KpiDefinition) { return this.kpiSources().find(item => item.id === definition.id); } + kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } get availableKpis() { return this.kpisByDomain[this.dominio]; } get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); } private readonly catalogRequests = new Subject(); @@ -237,7 +235,7 @@ export class IndicadoresPage { this.tema = this.memory.theme(this.dominio); this.availabilityRequests.pipe(switchMap(() => { this.availability.set(emptyAvailability()); - return this.periodService.dominio(this.dominio, this.kpiSources()); + return this.periodService.dominio(this.dominio, this.catalog()); }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { this.clearVisibility(); diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index 5c39c46..8906a5e 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -1,4 +1,4 @@ -import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -25,7 +25,7 @@ describe('UX-06E.D.3.B fijación temporal', () => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); load(); }); From 9cc67c0ef2546e8f39154bacc6a1b930c80e75a4 Mon Sep 17 00:00:00 2001 From: rodrigo Date: Fri, 16 Oct 2026 08:33:30 +0000 Subject: [PATCH 25/51] =?UTF-8?q?CaMa:=20sin=20la=20barra=20fija=20de=20BI?= =?UTF-8?q?-RADS=204=20sin=20subcategor=C3=ADa?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Los catálogos de despliegue (cama.catalogos.birads y .birads_4_a_6) ya no traen B4: el hospital reporta la subcategoría (usuario, 2026-10-16) y la barra salía siempre en 0. Un 4 a secas sigue contando como sospecha y en BI-RADS 4 a 6, y si llega se reporta tal cual después de «Sin dato». - CAMA_BIRADS 0.1.3, CAMA_BIRADS456_PACIENTE y _MASTOGRAFIA 0.1.1: misma consulta (misma huella), otras categorías publicadas. - El fixture de H-003 pasa de B4 a B4A; pruebas e instantánea (solo agrega). CSO5.5 Co-Authored-By: Claude Opus 5.5 --- .../indicadores/indicadores-kpi-cama-real.spec.ts | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts index 349df3d..a7675bc 100644 --- a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts @@ -3,6 +3,7 @@ import { IndicadorDatos } from './indicadores.models'; // /cama/indicadores//datos?periodos=2025-S2 as WebApi served it (oct 2026) over a CaMa base // mounted by dev-data (n = 300, semilla 7, referencia 2026-01-01), trimmed to what the card reads. +// Since indicadores_kit v0.6.2 the catalog has no plain B4 (only 4A, 4B and 4C). const DATOS_2025_S2: Record = { "cama_birads_456_paciente": { "id": "cama_birads_456_paciente", @@ -12,7 +13,6 @@ const DATOS_2025_S2: Record = { "2025-S2" ], "categorias": { - "B4": {}, "B4A": {}, "B4B": {}, "B4C": {}, @@ -21,15 +21,6 @@ const DATOS_2025_S2: Record = { "SIN_DATO": {} }, "filas": [ - { - "periodo": "2025-S2", - "grupo": "TOTAL", - "estrato": null, - "categoria": "B4", - "n": 0, - "orden": 0, - "suprimido": 0 - }, { "periodo": "2025-S2", "grupo": "TOTAL", From 1fe88dfb45b5156fcf9357ae02b7f8958f366717 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 22 Oct 2026 17:10:35 -0600 Subject: [PATCH 26/51] feat(indicadores): dashboard interactivo multidominio y seguimiento CaCu --- .../indicadores/cacu-seguimiento.models.ts | 29 + .../indicadores/cacu-seguimiento.service.ts | 40 ++ .../indicadores/cacu-seguimiento.spec.ts | 63 ++ ...eu7_datos_estrato_estatus_seguimiento.json | 366 ++++++++++++ .../cacu_eu7_datos_estrato_grupo_edad.json | 561 ++++++++++++++++++ .../fixtures/cacu_seguimiento.json | 256 ++++++++ .../indicador-catalog-card.spec.ts | 1 + .../indicadores/indicador-catalog-card.ts | 71 ++- .../indicadores/indicador-figure-card.html | 46 +- .../indicadores/indicador-figure-card.scss | 40 +- .../indicadores/indicador-figure-card.spec.ts | 63 +- .../indicadores/indicador-figure-card.ts | 113 ++-- .../indicador-figure-panel.spec.ts | 58 +- .../indicadores/indicador-figure-panel.ts | 125 +++- .../indicadores/indicador-kpi-panel.spec.ts | 86 +-- .../indicadores/indicador-kpi-panel.ts | 13 +- .../indicadores/indicador-metadata.spec.ts | 17 + .../indicadores/indicador-metadata.ts | 32 + .../indicadores-c2-adapter.spec.ts | 177 ++++++ .../indicadores-c2-adapter.testing.ts | 7 + .../indicadores/indicadores-c2-adapter.ts | 118 ++++ .../indicadores/indicadores-c2-palette.ts | 14 + .../indicadores/indicadores-c2-panel.spec.ts | 82 +++ .../indicadores/indicadores-definitions.html | 56 ++ .../indicadores/indicadores-definitions.scss | 13 + .../indicadores/indicadores-definitions.ts | 38 ++ .../indicadores-donut-drilldown.spec.ts | 120 ++++ .../indicadores-donut-drilldown.testing.ts | 18 + .../indicadores-donut-drilldown.ts | 170 ++++++ .../indicadores/indicadores-dual-figures.ts | 7 + .../indicadores-global-filters.spec.ts | 12 +- .../indicadores-initial-integration.spec.ts | 223 +++++++ .../indicadores-initial-period.spec.ts | 98 +++ .../indicadores/indicadores-initial-period.ts | 32 + .../indicadores-initial-search.spec.ts | 76 +++ .../indicadores/indicadores-kpi-queries.ts | 22 +- .../indicadores/indicadores-methodology.ts | 38 ++ .../indicadores/indicadores-numeric-rows.ts | 50 ++ .../indicadores-numeric-summary.spec.ts | 218 +++++++ .../indicadores-numeric-summary.ts | 81 +++ .../indicadores/indicadores-page.html | 47 +- .../indicadores/indicadores-page.scss | 18 + .../indicadores/indicadores-page.spec.ts | 17 +- .../features/indicadores/indicadores-page.ts | 96 ++- .../indicadores-periodos-integration.spec.ts | 43 +- .../indicadores-periodos.testing.ts | 14 +- .../indicadores/indicadores-sections.spec.ts | 146 +++++ .../indicadores/indicadores-snapshots.ts | 86 +++ .../indicadores-stratified-panel.spec.ts | 60 ++ .../indicadores-stratified.spec.ts | 63 ++ .../indicadores/indicadores-stratified.ts | 64 ++ .../indicadores/indicadores-tracking.html | 53 ++ .../indicadores/indicadores-tracking.scss | 18 + .../indicadores/indicadores-tracking.ts | 81 +++ .../indicadores-visibility.spec.ts | 21 + .../indicadores/indicadores.models.ts | 18 + .../indicadores/indicadores.service.spec.ts | 2 +- .../indicadores/indicadores.service.ts | 30 +- src/app/shared/plotly/plotly-chart.ts | 5 +- .../shared/plotly/plotly-controller.spec.ts | 16 + src/app/shared/plotly/plotly-controller.ts | 18 +- tsconfig.spec.json | 1 + 62 files changed, 4380 insertions(+), 187 deletions(-) create mode 100644 src/app/features/indicadores/cacu-seguimiento.models.ts create mode 100644 src/app/features/indicadores/cacu-seguimiento.service.ts create mode 100644 src/app/features/indicadores/cacu-seguimiento.spec.ts create mode 100644 src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json create mode 100644 src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_grupo_edad.json create mode 100644 src/app/features/indicadores/fixtures/cacu_seguimiento.json create mode 100644 src/app/features/indicadores/indicador-metadata.spec.ts create mode 100644 src/app/features/indicadores/indicador-metadata.ts create mode 100644 src/app/features/indicadores/indicadores-c2-adapter.spec.ts create mode 100644 src/app/features/indicadores/indicadores-c2-adapter.testing.ts create mode 100644 src/app/features/indicadores/indicadores-c2-adapter.ts create mode 100644 src/app/features/indicadores/indicadores-c2-palette.ts create mode 100644 src/app/features/indicadores/indicadores-c2-panel.spec.ts create mode 100644 src/app/features/indicadores/indicadores-definitions.html create mode 100644 src/app/features/indicadores/indicadores-definitions.scss create mode 100644 src/app/features/indicadores/indicadores-definitions.ts create mode 100644 src/app/features/indicadores/indicadores-donut-drilldown.spec.ts create mode 100644 src/app/features/indicadores/indicadores-donut-drilldown.testing.ts create mode 100644 src/app/features/indicadores/indicadores-donut-drilldown.ts create mode 100644 src/app/features/indicadores/indicadores-dual-figures.ts create mode 100644 src/app/features/indicadores/indicadores-initial-integration.spec.ts create mode 100644 src/app/features/indicadores/indicadores-initial-period.spec.ts create mode 100644 src/app/features/indicadores/indicadores-initial-period.ts create mode 100644 src/app/features/indicadores/indicadores-initial-search.spec.ts create mode 100644 src/app/features/indicadores/indicadores-methodology.ts create mode 100644 src/app/features/indicadores/indicadores-numeric-rows.ts create mode 100644 src/app/features/indicadores/indicadores-numeric-summary.spec.ts create mode 100644 src/app/features/indicadores/indicadores-numeric-summary.ts create mode 100644 src/app/features/indicadores/indicadores-sections.spec.ts create mode 100644 src/app/features/indicadores/indicadores-snapshots.ts create mode 100644 src/app/features/indicadores/indicadores-stratified-panel.spec.ts create mode 100644 src/app/features/indicadores/indicadores-stratified.spec.ts create mode 100644 src/app/features/indicadores/indicadores-stratified.ts create mode 100644 src/app/features/indicadores/indicadores-tracking.html create mode 100644 src/app/features/indicadores/indicadores-tracking.scss create mode 100644 src/app/features/indicadores/indicadores-tracking.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts new file mode 100644 index 0000000..956243e --- /dev/null +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -0,0 +1,29 @@ +export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; } +export interface SeguimientoStatus { codigo: string; etiqueta: string; } +export interface SeguimientoPaciente { + id_seudonimo: string; + grupo_edad: string; + estatus: SeguimientoStatus; + ultima_citologia: { fecha: string; bethesda: string | null; calidad: string } | null; + ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null; + dias_toma_diagnostico: number | null; + prioridad: SeguimientoStatus | null; +} +export interface SeguimientoResponse { + simulado: boolean; + corte: string; + ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string }; + filtros: { estatus: string | null }; + estatus_disponibles: SeguimientoStatus[]; + reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[]; + paginacion: { page: number; page_size: number; total_items: number; total_pages: number }; + items: SeguimientoPaciente[]; +} +export function isoDate(value: unknown): value is string { + if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return false; + const date = new Date(value + 'T00:00:00Z'); + return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value; +} +export function latestStudy(item: SeguimientoPaciente): string | null { + return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null; +} diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts new file mode 100644 index 0000000..1b86c8e --- /dev/null +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -0,0 +1,40 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models'; +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string'; +const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; +export function validSeguimientoQuery(q: SeguimientoQuery) { + return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200; +} +export function seguimientoResponse(v: unknown): SeguimientoResponse { + // The current authorization covers demonstration records only. Validate this + // before passing any item to the component; real-patient activation is separate. + if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); + const p = v['paginacion'], window = v['ventana'], filters = v['filtros']; + if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta']) + || !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string') + || !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status) + || !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string)) + || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages']) + || !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => { + if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; + const c = item['ultima_citologia'], h = item['ultimo_vph']; + return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && typeof c['calidad'] === 'string') + && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) + && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); + })) throw new Error('Respuesta de seguimiento inválida'); + return v as unknown as SeguimientoResponse; +} +@Injectable({ providedIn: 'root' }) +export class CacuSeguimientoService { + private readonly http = inject(HttpClient); + consultar(query: SeguimientoQuery) { + if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos'); + let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size); + if (query.corte) params = params.set('corte', query.corte); + if (query.estatus) params = params.set('estatus', query.estatus); + return this.http.get('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse)); + } +} diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts new file mode 100644 index 0000000..7c8663c --- /dev/null +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -0,0 +1,63 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import fixtureData from './fixtures/cacu_seguimiento.json'; +import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service'; +import { latestStudy } from './cacu-seguimiento.models'; +import { IndicadoresTracking } from './indicadores-tracking'; + +describe('Seguimiento CaCu con contrato de demostración', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers:[provideHttpClient(),provideHttpClientTesting()] }); + fixture=TestBed.createComponent(IndicadoresTracking); http=TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio','cacu'); fixture.componentRef.setInput('domainLabel','CaCu'); + }); + afterEach(()=>{ fixture.destroy(); http.verify(); }); + function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); } + function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); } + it('consulta solo al abrir CaCu, presenta simulación, nulos, calidad y genotipo sin prioridad clínica', () => { + fixture.detectChanges(); http.expectNone(()=>true); respond(); + const root:HTMLElement=fixture.nativeElement; + expect(root.textContent).toContain('Datos simulados — uso de demostración'); + expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado'); + expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8); + expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/); + expect(root.querySelector('tbody tr td:last-child')?.textContent).toBe('No disponible'); + expect(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15'); + expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull(); + }); + it('página y filtros conservan los parámetros aplicados; navegación por pestañas no repite GET', () => { + respond(); fixture.componentInstance.draft={corte:'2026-09-30',meses:6,estatus:'VIGILANCIA',page:1,page_size:10}; fixture.componentInstance.apply(); + let req=http.expectOne(r=>r.url==='/cacu/seguimiento'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('estatus')).toBe('VIGILANCIA'); + req.flush({...fixtureData,ventana:{...fixtureData.ventana,meses:6},filtros:{estatus:'VIGILANCIA'}}); fixture.detectChanges(); + fixture.componentInstance.draft.meses=12; // Draft edits must not affect server pagination. + fixture.componentInstance.navigate(2); req=http.expectOne(r=>r.url==='/cacu/seguimiento'); + expect(req.request.params.get('page')).toBe('2'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('corte')).toBe('2026-09-30'); + req.flush({...fixtureData,ventana:{...fixtureData.ventana,meses:6},filtros:{estatus:'VIGILANCIA'},paginacion:{...fixtureData.paginacion,page:2}}); + fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true); + expect(fixture.componentInstance.data?.paginacion.page).toBe(2); + }); + it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => { + const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'}); + fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private'); + expect(fixture.componentInstance.status).toBe(code===404?'pending':'error'); fixture.componentInstance.retry(); + http.expectOne(r=>r.url==='/cacu/seguimiento').flush({...fixtureData,items:[],paginacion:{page:1,page_size:50,total_items:0,total_pages:0}}); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({}, {status:404,statusText:'Absent'}); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('No hay registros'); + }); + it('no activa registros reales ni acepta respuestas malformadas', () => { + expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow(); + expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow(); + 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'); + }); + it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => { + const service=TestBed.inject(CacuSeguimientoService); + for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow(); + http.expectNone(()=>true); + }); +}); diff --git a/src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json b/src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json new file mode 100644 index 0000000..d3ee915 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json @@ -0,0 +1,366 @@ +{ + "id": "cacu_eu7", + "titulo": "Distribución de resultados citológicos", + "version": "0.2.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "estrato": "estatus_seguimiento", + "valores_estrato": [ + "VIGILANCIA", + "POST_COLPOSCOPIA", + "POST_TRATAMIENTO", + "INFO_INSUFICIENTE" + ], + "etiquetas_estrato": { + "VIGILANCIA": "Vigilancia", + "POST_COLPOSCOPIA": "Post colposcopia", + "POST_TRATAMIENTO": "Post tratamiento", + "INFO_INSUFICIENTE": "Información insuficiente" + }, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "NORMAL": { + "etiqueta": "Normal", + "color": "#9DBFE3", + "grupo": "NO_ANORMAL", + "gravedad": 1 + }, + "ASC-US": { + "etiqueta": "ASC-US", + "color": "#2F6DB3", + "grupo": "NO_ANORMAL", + "gravedad": 2 + }, + "LIEBG": { + "etiqueta": "LIEBG", + "color": "#E8C28E", + "grupo": "ANORMAL", + "gravedad": 3 + }, + "ASC-H": { + "etiqueta": "ASC-H", + "color": "#D98E4A", + "grupo": "ANORMAL", + "gravedad": 4 + }, + "LIEAG": { + "etiqueta": "LIEAG", + "color": "#B55A1F", + "grupo": "ANORMAL", + "gravedad": 5 + }, + "CIS": { + "etiqueta": "Carcinoma in situ", + "color": "#7A2E0E", + "grupo": "ANORMAL", + "gravedad": 6 + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_ANORMAL": "Sin anomalía", + "ANORMAL": "Anormal", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así." + ], + "reportes": [ + { + "periodo": "2025-S2", + "report_id": 44, + "periodo_inicio": "2025-07-01", + "periodo_fin": "2026-01-01", + "fecha_corte": "2026-10-22", + "generado_en": "2026-10-22T20:26:40.633043+00:00", + "kit_version": "0.8.0", + "toml_sha": "94749f578a4d901edf038bca0427e9975bac72de1a1fdea382f4de1d5eb7402b", + "parametros_sha": "091ab456d7f51e865bf31e1fd4201d22a3acf9877f057d0473b4765c20095092", + "parametros": { + "sql": { + "_catalogo": [ + "NORMAL", + "ASC-US", + "LIEBG", + "ASC-H", + "LIEAG", + "CIS" + ], + "_grupos": [ + "TOTAL" + ], + "calidad_insatisfactoria": "INSATISFACTORIO", + "fecha_corte": "2026-10-22", + "periodo_fin": "2026-01-01", + "periodo_inicio": "2025-07-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "NORMAL", + "n": 1027, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "ASC-US", + "n": 145, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "LIEBG", + "n": 65, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "ASC-H", + "n": 22, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "LIEAG", + "n": 36, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "CIS", + "n": 9, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "SIN_DATO", + "n": 46, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "NORMAL", + "n": 117, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "ASC-US", + "n": 39, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "LIEBG", + "n": 30, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "ASC-H", + "n": 5, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "LIEAG", + "n": 11, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "SIN_DATO", + "n": 6, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "NORMAL", + "n": 26, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "ASC-US", + "n": 7, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "LIEBG", + "n": 7, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "ASC-H", + "n": null, + "orden": 3, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "LIEAG", + "n": null, + "orden": 4, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "SIN_DATO", + "n": null, + "orden": 6, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "NORMAL", + "n": 192, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "ASC-US", + "n": 20, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "LIEBG", + "n": 16, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "ASC-H", + "n": null, + "orden": 3, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "LIEAG", + "n": 9, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "SIN_DATO", + "n": 12, + "orden": 6, + "suprimido": 0 + } + ] +} diff --git a/src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_grupo_edad.json b/src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_grupo_edad.json new file mode 100644 index 0000000..dc1e408 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu7_datos_estrato_grupo_edad.json @@ -0,0 +1,561 @@ +{ + "id": "cacu_eu7", + "titulo": "Distribución de resultados citológicos", + "version": "0.2.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "estrato": "grupo_edad", + "valores_estrato": [ + "<25", + "25-34", + "35-44", + "45-54", + "55-64", + "65+", + "sin_dato" + ], + "etiquetas_estrato": { + "<25": "<25", + "25-34": "25-34", + "35-44": "35-44", + "45-54": "45-54", + "55-64": "55-64", + "65+": "65+", + "sin_dato": "Sin dato" + }, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "NORMAL": { + "etiqueta": "Normal", + "color": "#9DBFE3", + "grupo": "NO_ANORMAL", + "gravedad": 1 + }, + "ASC-US": { + "etiqueta": "ASC-US", + "color": "#2F6DB3", + "grupo": "NO_ANORMAL", + "gravedad": 2 + }, + "LIEBG": { + "etiqueta": "LIEBG", + "color": "#E8C28E", + "grupo": "ANORMAL", + "gravedad": 3 + }, + "ASC-H": { + "etiqueta": "ASC-H", + "color": "#D98E4A", + "grupo": "ANORMAL", + "gravedad": 4 + }, + "LIEAG": { + "etiqueta": "LIEAG", + "color": "#B55A1F", + "grupo": "ANORMAL", + "gravedad": 5 + }, + "CIS": { + "etiqueta": "Carcinoma in situ", + "color": "#7A2E0E", + "grupo": "ANORMAL", + "gravedad": 6 + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_ANORMAL": "Sin anomalía", + "ANORMAL": "Anormal", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así." + ], + "reportes": [ + { + "periodo": "2025-S2", + "report_id": 44, + "periodo_inicio": "2025-07-01", + "periodo_fin": "2026-01-01", + "fecha_corte": "2026-10-22", + "generado_en": "2026-10-22T20:26:40.633043+00:00", + "kit_version": "0.8.0", + "toml_sha": "94749f578a4d901edf038bca0427e9975bac72de1a1fdea382f4de1d5eb7402b", + "parametros_sha": "091ab456d7f51e865bf31e1fd4201d22a3acf9877f057d0473b4765c20095092", + "parametros": { + "sql": { + "_catalogo": [ + "NORMAL", + "ASC-US", + "LIEBG", + "ASC-H", + "LIEAG", + "CIS" + ], + "_grupos": [ + "TOTAL" + ], + "calidad_insatisfactoria": "INSATISFACTORIO", + "fecha_corte": "2026-10-22", + "periodo_fin": "2026-01-01", + "periodo_inicio": "2025-07-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "NORMAL", + "n": 50, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "ASC-US", + "n": null, + "orden": 1, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "LIEBG", + "n": null, + "orden": 2, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "ASC-H", + "n": null, + "orden": 3, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "LIEAG", + "n": null, + "orden": 4, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "SIN_DATO", + "n": null, + "orden": 6, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "NORMAL", + "n": 320, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "ASC-US", + "n": 32, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "LIEBG", + "n": 21, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "ASC-H", + "n": 7, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "LIEAG", + "n": 13, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "SIN_DATO", + "n": 15, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "NORMAL", + "n": 441, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "ASC-US", + "n": 25, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "LIEBG", + "n": 21, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "ASC-H", + "n": 7, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "LIEAG", + "n": 9, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "SIN_DATO", + "n": 16, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "NORMAL", + "n": 365, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "ASC-US", + "n": 36, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "LIEBG", + "n": 21, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "ASC-H", + "n": 7, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "LIEAG", + "n": 16, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "SIN_DATO", + "n": 23, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "NORMAL", + "n": 245, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "ASC-US", + "n": 23, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "LIEBG", + "n": 10, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "ASC-H", + "n": 5, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "LIEAG", + "n": 5, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "SIN_DATO", + "n": 11, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "NORMAL", + "n": 74, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "ASC-US", + "n": 6, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "LIEBG", + "n": null, + "orden": 2, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "ASC-H", + "n": null, + "orden": 3, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "LIEAG", + "n": null, + "orden": 4, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "65+", + "categoria": "SIN_DATO", + "n": null, + "orden": 6, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "NORMAL", + "n": 10, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "ASC-US", + "n": null, + "orden": 1, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "LIEBG", + "n": null, + "orden": 2, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "ASC-H", + "n": null, + "orden": 3, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "LIEAG", + "n": null, + "orden": 4, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "CIS", + "n": null, + "orden": 5, + "suprimido": 1 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "sin_dato", + "categoria": "SIN_DATO", + "n": null, + "orden": 6, + "suprimido": 1 + } + ] +} diff --git a/src/app/features/indicadores/fixtures/cacu_seguimiento.json b/src/app/features/indicadores/fixtures/cacu_seguimiento.json new file mode 100644 index 0000000..d53e969 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_seguimiento.json @@ -0,0 +1,256 @@ +{ + "simulado": true, + "corte": "2026-09-30", + "ventana": { + "meses": 3, + "desde": "2026-07-01", + "hasta": "2026-09-30" + }, + "filtros": { + "estatus": null + }, + "estatus_disponibles": [ + { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + { + "codigo": "POST_COLPOSCOPIA", + "etiqueta": "Post colposcopia" + }, + { + "codigo": "POST_TRATAMIENTO", + "etiqueta": "Post tratamiento" + }, + { + "codigo": "INFO_INSUFICIENTE", + "etiqueta": "Información insuficiente" + } + ], + "reglas": [ + { + "clave": "cacu.seguimiento.marco", + "valor": [ + "estatus" + ], + "estado": "provisional" + }, + { + "clave": "cacu.seguimiento.precedencia", + "valor": [ + "POST_TRATAMIENTO", + "POST_COLPOSCOPIA", + "INFO_INSUFICIENTE", + "VIGILANCIA" + ], + "estado": "provisional" + }, + { + "clave": "cacu.seguimiento.ventana_meses", + "valor": 3, + "estado": "provisional" + }, + { + "clave": "cacu.seguimiento.fecha_estudio", + "valor": "toma", + "estado": "provisional" + }, + { + "clave": "cacu.seguimiento.estudios", + "valor": [ + "citologia", + "vph" + ], + "estado": "provisional" + }, + { + "clave": "cacu.seguimiento.resultado_mostrado", + "valor": "ultimo", + "estado": "provisional" + } + ], + "paginacion": { + "page": 1, + "page_size": 10, + "total_items": 1284, + "total_pages": 129 + }, + "items": [ + { + "id_seudonimo": "P-4BC9B9E8F4", + "grupo_edad": "25-34", + "estatus": { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + "ultima_citologia": null, + "ultimo_vph": { + "fecha": "2026-09-28", + "resultado": "NEGATIVO", + "genotipo_16_18": null + }, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-2C9E494F5D", + "grupo_edad": "65+", + "estatus": { + "codigo": "POST_COLPOSCOPIA", + "etiqueta": "Post colposcopia" + }, + "ultima_citologia": null, + "ultimo_vph": { + "fecha": "2026-09-23", + "resultado": "POSITIVO", + "genotipo_16_18": true + }, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-E470F3442F", + "grupo_edad": "35-44", + "estatus": { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + "ultima_citologia": { + "fecha": "2026-09-18", + "bethesda": "NORMAL", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": { + "fecha": "2026-09-08", + "resultado": "NEGATIVO", + "genotipo_16_18": null + }, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-24A2B1D6B5", + "grupo_edad": "25-34", + "estatus": { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + "ultima_citologia": { + "fecha": "2026-09-13", + "bethesda": "LIEAG", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": null, + "dias_toma_diagnostico": 23, + "prioridad": null + }, + { + "id_seudonimo": "P-9E0E15AB5C", + "grupo_edad": "25-34", + "estatus": { + "codigo": "POST_COLPOSCOPIA", + "etiqueta": "Post colposcopia" + }, + "ultima_citologia": { + "fecha": "2026-08-22", + "bethesda": "NORMAL", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": { + "fecha": "2026-07-14", + "resultado": "NEGATIVO", + "genotipo_16_18": null + }, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-45A44DFE6F", + "grupo_edad": "<25", + "estatus": { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + "ultima_citologia": { + "fecha": "2026-08-04", + "bethesda": null, + "calidad": "INSATISFACTORIO" + }, + "ultimo_vph": { + "fecha": "2026-08-15", + "resultado": "POSITIVO", + "genotipo_16_18": false + }, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-367397F2CE", + "grupo_edad": "65+", + "estatus": { + "codigo": "POST_TRATAMIENTO", + "etiqueta": "Post tratamiento" + }, + "ultima_citologia": { + "fecha": "2026-08-05", + "bethesda": "ASC-H", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": null, + "dias_toma_diagnostico": 41, + "prioridad": null + }, + { + "id_seudonimo": "P-2FB7CB6653", + "grupo_edad": "45-54", + "estatus": { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + "ultima_citologia": { + "fecha": "2026-07-24", + "bethesda": "NORMAL", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": null, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-517CD5E39B", + "grupo_edad": "55-64", + "estatus": { + "codigo": "INFO_INSUFICIENTE", + "etiqueta": "Información insuficiente" + }, + "ultima_citologia": { + "fecha": "2026-07-17", + "bethesda": "ASC-US", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": null, + "dias_toma_diagnostico": null, + "prioridad": null + }, + { + "id_seudonimo": "P-E1157546FD", + "grupo_edad": "25-34", + "estatus": { + "codigo": "VIGILANCIA", + "etiqueta": "Vigilancia" + }, + "ultima_citologia": { + "fecha": "2026-07-01", + "bethesda": "NORMAL", + "calidad": "SATISFACTORIO" + }, + "ultimo_vph": { + "fecha": "2026-07-01", + "resultado": "INDETERMINADO", + "genotipo_16_18": null + }, + "dias_toma_diagnostico": null, + "prioridad": null + } + ] +} diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index 1427933..b221ae9 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -49,6 +49,7 @@ describe('UX-06E.D.2.1 selector de representación', () => { }); it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => { fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); + fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges(); expect(select().options.map(option => [option.value, option.viewValue])).toEqual([ ['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'], ['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index f35a152..2fcddda 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -1,4 +1,5 @@ -import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, output, ViewChild } from '@angular/core'; +import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChanges, OnDestroy, output, untracked, ViewChild } from '@angular/core'; +import { Subscription } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; @@ -10,9 +11,14 @@ import { indicatorIdentity, figureIdentity, identityElementId } from './indicado import { IndicadorFigurePanel } from './indicador-figure-panel'; import { figureDisplayName } from './indicadores-figure-labels'; import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; +import { dualFigures } from './indicadores-dual-figures'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { filterCompatibility } from './indicadores-memory'; +import { DonutSelection } from './indicadores-donut-drilldown'; @Component({ selector: 'app-indicador-catalog-card', + host: { '[class.dual-card]': 'isDual' }, imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel], template: ` @@ -29,16 +35,22 @@ import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visu
@if (selectedFigure) { + @if (!pair.length || otherFigures.length) { Representación gráfica - @for (figure of indicador.figuras; track figure) { {{ figureDisplayName(figure, indicador.figuras) }} } + @if (pair.length) { Dona y barras } + @for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { {{ figureDisplayName(figure, indicador.figuras) }} } -
- @for (figure of [selectedFigure]; track panelIdentity(figure)) { - + } +
+ @for (figure of displayFigures; track panelIdentity(figure)) { +
+ @if (isDual) {

{{ figureDisplayName(figure, indicador.figuras) }}

} + +
}
} @else {

El indicador no tiene figuras disponibles.

} @@ -51,6 +63,11 @@ import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visu color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); } .graphic-region { min-height: 620px; } + :host(.dual-card) { grid-column: 1 / -1; } + .dual-panels { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--issste-space-4); } + .representation-panel { min-width: 0; } + .representation-panel > h3 { margin-bottom: 0; } + @media (max-width: 900px) { .dual-panels { grid-template-columns: minmax(0, 1fr); } } .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; } @@ -64,7 +81,38 @@ import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visu @media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } } `, }) -export class IndicadorCatalogCard implements OnChanges { +export class IndicadorCatalogCard implements OnChanges, OnDestroy { + localSelection: DonutSelection = {}; + private selectionContext = ''; + private readonly snapshots = inject(IndicadoresSnapshots); + private numericSubscription?: Subscription; + private numericKey = ''; + private activatedKey = ''; + constructor() { + effect(() => { + this.snapshots.expanded(); this.snapshots.retries(); + if (this.indicador && this.applied) untracked(() => this.updateNumeric()); + }); + } + get pair() { return dualFigures(this.indicador); } + get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } + get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } + get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } + private updateNumeric() { + const key = snapshotKey(this.dominio, this.indicador, this.applied); + if (key !== this.activatedKey) { + this.numericSubscription?.unsubscribe(); this.numericKey = ''; + if (this.visible) this.activatedKey = key; + } + if (this.activatedKey !== key || !this.snapshots.expanded() + || !filterCompatibility(this.applied, this.indicador.tipos_periodo).compatible) return; + const attempt = JSON.stringify([key, this.snapshots.retries()]); + if (this.numericKey === attempt) return; + this.numericKey = attempt; + this.numericSubscription?.unsubscribe(); + this.numericSubscription = this.snapshots.read(this.dominio, this.indicador, this.applied).subscribe(); + } + ngOnDestroy() { this.numericSubscription?.unsubscribe(); } readonly figureDisplayName = figureDisplayName; @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; @@ -85,24 +133,29 @@ export class IndicadorCatalogCard implements OnChanges { selectedFigure?: string; selectFigure(figure: string) { if (!this.indicador.figuras.includes(figure) || figure === this.selectedFigure) return; - this.selectedFigure = figure; + this.selectedFigure = this.pair.includes(figure) ? this.pair[0] : figure; this.memory.rememberFigure(this.dominio, this.indicador.id, figure); this.changeDetector.markForCheck(); } ngOnChanges() { + const context = JSON.stringify([this.dominio, this.indicador.id, this.indicador.version, this.applied, this.tema]); + if (context !== this.selectionContext) { this.localSelection = {}; this.selectionContext = context; } const remembered = this.memory.figure(this.dominio, this.indicador.id); - this.selectedFigure = remembered && this.indicador.figuras.includes(remembered) ? remembered : this.indicador.figuras[0]; + const selected = remembered && this.indicador.figuras.includes(remembered) ? remembered : this.pair[0] ?? this.indicador.figuras[0]; + this.selectedFigure = this.pair.includes(selected) ? this.pair[0] : selected; const identity = indicatorIdentity(this.dominio, this.indicador.id); - if (identity === this.identity) return; + if (identity === this.identity) { this.updateNumeric(); return; } this.identity = identity; const id = identityElementId(identity); this.titleId = id + '-title'; this.contentId = id + '-content'; this.visible = false; + this.updateNumeric(); } setVisible(visible: boolean) { if (this.visible === visible) return; this.visible = visible; + this.updateNumeric(); this.changeDetector.markForCheck(); } } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index 7378b91..bf671f4 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -11,11 +11,11 @@
    @for (line of interpretation; track $index) {
  • {{ line }}
  • }
-

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+

{{ periodInterpretation }}

} - + @if (state.status === 'loading') {

Cargando figura…

@@ -28,7 +28,7 @@
} @else if (state.figure; as figure) { @if (hasNoVisibleValues(figure)) { -

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

+

{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}

}

Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}

@@ -37,7 +37,45 @@ } @if (chartFigure) {
- + @if (state.status === 'ready' && state.hierarchy; as hierarchy) { +
+

{{ activeParent ? 'Categorías de ' + activeParent + '. Anillo exterior: porcentajes dentro de este grupo. Anillo interior: todos los grupos.' : 'Selecciona un segmento para ver sus categorías. También puedes explorar los grupos con Tab y Enter o Espacio.' }}

+
+ {{ activeParent ? 'Categorías' : 'Grupos' }} + @if (activeParent) { + + } +
+
+
+ @for (parent of hierarchy.parents; track parent) { + + } +
+
+
+

Categorías

+
+ @for (child of visibleChildren; track child.label) { + + } +
+
+
+
+
+ } + @if (state.footnotes?.length) {
@for (note of state.footnotes; track $index) {

{{ note }}

} diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index c62cf22..cc5c6ae 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -14,7 +14,8 @@ .interpretation ul { margin: 0; padding-left: 1.25rem; } .interpretation li + li { margin-top: .25rem; } .period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); } -.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; } +.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; + --mat-button-outlined-label-text-color: var(--issste-text); --mat-button-outlined-outline-color: var(--issste-border); } .methodology-detail p { margin: 0; } .methodology-detail p + p { margin-top: var(--issste-space-2); } .methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } @@ -50,3 +51,40 @@ .figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } .skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } +.donut-navigation { + position: relative; + color: var(--issste-text); +} +.dark .donut-navigation { color: #eef1f7; } +.donut-status { + position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; + overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; +} +.donut-legend { padding: 0 .75rem; box-sizing: border-box; } +.donut-keyboard, .donut-children { display: flex; flex-wrap: wrap; align-content: start; gap: .25rem .75rem; } +.donut-children-region { + display: grid; grid-template-rows: 0fr; opacity: 0; transform: translateY(-.25rem); + transition: grid-template-rows 225ms ease, opacity 180ms ease, transform 225ms ease; +} +.donut-children-region.expanded { grid-template-rows: 1fr; opacity: 1; transform: translateY(0); } +.donut-children-content { min-height: 0; overflow: hidden; } +.donut-children-title { margin: .5rem 0 0; padding-top: .5rem; border-top: 1px solid var(--issste-border); + font: var(--mat-sys-body-small); font-weight: 600; } +.donut-children { padding-top: .25rem; } +.donut-legend button { display: flex; align-items: center; gap: .5rem; max-width: 100%; min-height: 44px; + padding: .25rem .5rem; border: 1px solid transparent; border-radius: 4px; background: transparent; color: inherit; + font: inherit; font-size: .875rem; text-align: start; overflow-wrap: anywhere; cursor: pointer; } +.donut-legend button[aria-pressed=true] { border-color: currentColor; font-weight: 600; } +.legend-swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; } +.donut-toolbar { + height: 48px; box-sizing: border-box; + display: flex; align-items: center; justify-content: space-between; gap: .5rem; padding: 0 .75rem; +} +.donut-context { min-width: 0; overflow-wrap: anywhere; font: var(--mat-sys-body-small); } +.donut-restore { flex-shrink: 0; color: inherit; } +.donut-legend button:focus-visible, .donut-restore:focus-visible { + outline: 2px solid currentColor; outline-offset: 3px; +} +@media (prefers-reduced-motion: reduce) { + .donut-children-region, .donut-children-region.expanded { transition: none; transform: none; } +} diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 8df5a30..a075e94 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -6,6 +6,8 @@ import { Indicador, PlotlyFigure } from './indicadores.models'; import { presentationFigure } from './indicadores.presentation'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; +import { donutFixture } from './indicadores-donut-drilldown.testing'; +import { donutHierarchy } from './indicadores-donut-drilldown'; describe('IndicadorFigureCard', () => { const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] }; @@ -46,6 +48,57 @@ describe('IndicadorFigureCard', () => { state({ status: 'ready', figure: original, presentationFigure: copy }); return copy; } + it('C2 expande por Plotly y teclado, vuelve con foco y conserva host; reinicia al cambiar resultado', async () => { + const { figure, data } = donutFixture(); + const hierarchy = donutHierarchy(figure, data)!; + state({ status: 'ready', figure, presentationFigure: figure, hierarchy }); await settle(); + const host = fixture.nativeElement.querySelector('.plot'); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.figure.data).toHaveLength(1); + expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain('Volver a grupos'); + expect(fixture.nativeElement.querySelectorAll('.donut-navigation > button')).toHaveLength(0); + const categories = fixture.nativeElement.querySelector('.donut-children-region') as HTMLElement; + expect(categories.classList.contains('expanded')).toBe(false); + expect(categories.getAttribute('aria-hidden')).toBe('true'); + expect(categories.hasAttribute('inert')).toBe(true); + expect(fixture.nativeElement.querySelector('.donut-children-title').textContent).toBe('Categorías'); + chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle(); + expect(fixture.componentInstance.activeParent).toBe('G2'); + expect(categories.classList.contains('expanded')).toBe(true); + expect(categories.hasAttribute('inert')).toBe(false); + expect(categories.getAttribute('aria-hidden')).toBeNull(); + expect(chart.figure.data[0]['labels']).toEqual(['B', 'C']); + chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G1' }] }); await settle(); + expect(fixture.componentInstance.activeParent).toBe('G1'); + expect(chart.figure.data[0]['labels']).toEqual(['A']); + chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle(); + expect(fixture.componentInstance.activeParent).toBe('G1'); + chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G2' }] }); await settle(); + state({ status: 'ready', figure, presentationFigure: structuredClone(figure), hierarchy }); await settle(); + expect(fixture.componentInstance.activeParent).toBe('G2'); + const back = fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement; + expect(back.getAttribute('aria-label')).toBe('Restaurar vista de la gráfica'); + expect(back.querySelector('svg')).not.toBeNull(); + back.focus(); back.click(); await settle(); + expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.donut-keyboard button')); + expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull(); + const group = fixture.nativeElement.querySelectorAll('.donut-keyboard button')[1] as HTMLButtonElement; + group.click(); await settle(); expect(group.getAttribute('aria-pressed')).toBe('true'); + expect(fixture.nativeElement.querySelector('.plot')).toBe(host); expect(purge).not.toHaveBeenCalled(); + state({ status: 'loading' }); expect(fixture.componentInstance.activeParent).toBeUndefined(); + expect(fixture.nativeElement.querySelector('.donut-navigation')).toBeNull(); + state({ status: 'ready', figure: structuredClone(figure), presentationFigure: figure, hierarchy }); await settle(); + expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.plot')).toBe(host); + }); + it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => { + const { figure, data } = donutFixture(); + state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data) }); + fixture.componentInstance.expandParent('G2'); + fixture.componentRef.setInput(input, input === 'dominio' ? 'cama' : input === 'figuraId' ? 'otra_dona' : { ...selected, id: 'nuevo' }); + fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined(); + expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1); + }); it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => { fixture.componentRef.setInput('dominio', dominio); const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} }; @@ -162,7 +215,7 @@ describe('IndicadorFigureCard', () => { it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => { fixture.componentRef.setInput('dominio', dominio); state({ status: 'loading' }); - expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('no entregan intervalos Wilson efectivos'); + expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %'); expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %'); }); it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => { @@ -216,7 +269,7 @@ describe('IndicadorFigureCard', () => { button.focus(); expect(document.activeElement).toBe(button); expect(detail.textContent).toContain('SIN_DATO'); - expect(detail.textContent).toContain('suprimidos no representan tasas'); + expect(detail.textContent).toContain('suprimidos no representan porcentajes observados de 0 %'); expect(detail.textContent).toContain('no permite determinar la disponibilidad'); expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation); button.click(); fixture.detectChanges(); @@ -232,7 +285,7 @@ describe('IndicadorFigureCard', () => { state({ status: 'idle' }); const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; button.click(); fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('composición porcentual'); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('conteos por categoría'); fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1'); @@ -263,7 +316,7 @@ describe('IndicadorFigureCard', () => { expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement; expect(detail.hidden).toBe(true); - expect(detail.textContent).toContain('Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.'); + expect(detail.textContent).toContain('Las barras muestran conteos por categoría; los porcentajes publicados pueden aparecer como etiquetas. Consulta la unidad y el denominador de cada representación.'); expect(detail.textContent).toContain('SIN_DATO'); expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); }); @@ -332,7 +385,7 @@ describe('IndicadorFigureCard', () => { expect(warnings.textContent).toContain('Wilson al 95 %'); expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan'); expect(warnings.textContent).toContain('denominadores pequeños'); - } else expect(warnings.textContent).toContain('no entregan intervalos Wilson efectivos'); + } else expect(warnings.textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %'); expect([...warnings.querySelectorAll('li')].map(p => p.textContent)) .toEqual(fixture.componentInstance.interpretation); button.focus(); button.click(); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index fbfdd16..ad44b60 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -1,14 +1,17 @@ -import { Component, Input, output, signal } from '@angular/core'; +import { Component, ElementRef, Input, OnChanges, output, signal, SimpleChanges, viewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatTooltipModule } from '@angular/material/tooltip'; import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; import { figureTitle } from './indicadores.presentation'; import { figureDisplayName } from './indicadores-figure-labels'; import { CategoryLabel } from './indicadores-axis-labels'; import { figureIdentity, identityElementId } from './indicadores-identities'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; +import { DonutHierarchy, DonutSelection, donutView } from './indicadores-donut-drilldown'; // The panel owns requests; the card receives the original and its presentation copy. export interface FigureState { @@ -18,51 +21,92 @@ export interface FigureState { footnotes?: readonly string[]; categoryLabels?: readonly CategoryLabel[]; minimumPlotWidth?: number; + plotWidth?: number; message?: string; + hierarchy?: DonutHierarchy; + source?: 'datos' | 'figuras'; + fallbackReason?: string; + emptyMessage?: string; } -// Presentation only: contract semantics documented in G3 and G5C. -const CONTRACT_INTERPRETATIONS: Readonly> = { - C1: [ - 'El punto representa la proporción observada.', - 'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.', - 'Los intervalos amplios pueden deberse a denominadores pequeños.', - 'Un porcentaje observado del 100 % no implica certeza poblacional.', - ], - C2: [ - 'Las barras muestran la composición porcentual de cada grupo y periodo.', - 'Las categorías corresponden a la distribución de cada grupo y periodo.', - 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', - ], - C3r: [ - 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', - 'Los límites de dibujo no representan necesariamente extremos observados.', - 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', - ], -}; -const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.']; - @Component({ selector: 'app-indicador-figure-card', standalone: true, - imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, PlotlyChart], + imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart], templateUrl: './indicador-figure-card.html', styleUrl: './indicador-figure-card.scss', }) -export class IndicadorFigureCard { +export class IndicadorFigureCard implements OnChanges { + private readonly donutNavigation = viewChild>('donutNavigation'); + private readonly donutKeyboard = viewChild>('donutKeyboard'); private currentState!: FigureState; // Keep the mounted host's last presentation only. The template hides it whenever // it is not the current result; this is neither applied state nor a results cache. chartFigure?: PlotlyFigure; chartMinimumWidth?: number; + activeParent?: string; + activeCategory?: string; + readonly hierarchySelected = output(); + selectCategory(category: string) { + if (!this.state.hierarchy?.children.some(c => c.parent === this.activeParent && c.label === category)) return; + this.activeCategory = this.activeCategory === category ? undefined : category; + this.hierarchySelected.emit({ parent: this.activeParent, category: this.activeCategory }); + } + get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; } + legendColor(label: string, parent: boolean): string { + const trace = this.chartFigure?.data[parent && this.activeParent ? 1 : 0]; + const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined; + const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined; + return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor'; + } @Input({ required: true }) set state(value: FigureState) { + if (value.status !== 'ready' || value.figure !== this.currentState?.figure + || JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; } this.currentState = value; if (value.status === 'ready') { - this.chartFigure = value.presentationFigure; + this.updateDonut(); this.chartMinimumWidth = value.minimumPlotWidth; } } get state() { return this.currentState; } + ngOnChanges(changes: SimpleChanges) { + if (changes['dominio'] || changes['figuraId'] + || (changes['selected'] && changes['selected'].previousValue?.id !== this.selected?.id)) { + this.activeParent = undefined; + if (this.state.status === 'ready') this.updateDonut(); + } + } + private updateDonut() { + const { presentationFigure, hierarchy } = this.state; + this.chartFigure = presentationFigure && hierarchy + ? donutView(presentationFigure, hierarchy, this.activeParent, this.state.plotWidth) : presentationFigure; + } + expandParent(parent: string) { + if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent) + || !this.state.hierarchy.children.some(c => c.parent === parent && c.value > 0)) return; + this.activeParent = parent; + this.activeCategory = undefined; + this.updateDonut(); + this.hierarchySelected.emit({ parent }); + } + returnToParents(event?: MouseEvent) { + if (!this.activeParent) return; + this.activeParent = undefined; this.activeCategory = undefined; this.updateDonut(); + this.hierarchySelected.emit({}); + // The restore button disappears. Transfer keyboard focus to the first + // persistent alternative; pointer users return to the graphic region. + if (event) { + const target = event.detail === 0 ? this.donutKeyboard()?.nativeElement.querySelector('button') + : this.donutNavigation()?.nativeElement; + target?.focus(); + } + } + plotClicked(event: unknown) { + if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return; + const point = event.points[0]; + if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label); + else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label); + } @Input() selected?: Indicador; @Input({ required: true }) figuraId!: string; @Input({ required: true }) dominio!: Dominio; @@ -98,23 +142,8 @@ export class IndicadorFigureCard { readonly figureTitle = figureTitle; readonly figureDisplayName = figureDisplayName; + readonly periodInterpretation = PERIOD_INTERPRETATION; get interpretation(): readonly string[] { - const contract = this.contract; - if (contract === 'C2' && this.dominio !== 'tea') return [ - this.state.figure?.data.some(trace => trace['type'] === 'pie') - ? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.' - : 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.', - 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', - 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.', - ]; - if (contract === 'C1' && this.dominio !== 'tea') return [ - 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.', - 'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.', - 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.', - 'Un porcentaje observado del 100 % no implica certeza poblacional.', - ]; - return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) - ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION; + return contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie')); } - } diff --git a/src/app/features/indicadores/indicador-figure-panel.spec.ts b/src/app/features/indicadores/indicador-figure-panel.spec.ts index 570d589..56297e9 100644 --- a/src/app/features/indicadores/indicador-figure-panel.spec.ts +++ b/src/app/features/indicadores/indicador-figure-panel.spec.ts @@ -11,6 +11,7 @@ import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; +import { donutFixture } from './indicadores-donut-drilldown.testing'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { figure?: PlotlyFigure; } @@ -47,6 +48,58 @@ describe('IndicadorFigurePanel', () => { function apply() { if (applyGlobal(state, ['semestre'])) { fixture.componentRef.setInput('applied', state.applied); fixture.detectChanges(); } } function load() { fixture.detectChanges(); } function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } + function candidate() { + // An unknown representation retains the legacy server-first hierarchy path. + fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: 'C2', figuras: ['future_donut', 'f2'] }); + fixture.componentRef.setInput('figuraId', 'future_donut'); + load(); + const sample = donutFixture(); figure().flush(sample.figure); + return sample; + } + it('C2 carga metadatos una vez; explorar, volver y adaptar ancho no consulta HTTP', () => { + const sample = candidate(); + const data = http.expectOne(r => r.url === '/tea/indicadores/i1/datos' && r.params.get('periodos') === '2025-S2'); + data.flush(sample.data); fixture.detectChanges(); + const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; + expect(page.result().hierarchy?.parents).toEqual(['G1', 'G2']); + card.expandParent('G2'); expect(card.chartFigure?.data[0]['labels']).toEqual(['B','C']); + page.updatePlotWidth(400); fixture.detectChanges(); expect(card.activeParent).toBe('G2'); + card.returnToParents(); http.expectNone(() => true); + fixture.componentRef.setInput('figuraId', 'f2'); fixture.detectChanges(); + expect(card.activeParent).toBeUndefined(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); + expect(page.result().hierarchy).toBeUndefined(); http.expectNone(() => true); + }); + it('descubre una representación futura de un anillo sin IDs codificados y restaura desde la UI sin HTTP', () => { + fixture.componentRef.setInput('indicador', { ...catalog[0], id: 'future_item', contrato: 'C2', figuras: ['future_donut'] }); + fixture.componentRef.setInput('figuraId', 'future_donut'); load(); + const sample = donutFixture(); sample.figure.data.pop(); sample.data.id = 'future_item'; + figure().flush(sample.figure); http.expectOne(r => r.url.endsWith('/future_item/datos')).flush(sample.data); + fixture.detectChanges(); + const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; + expect(card.state.hierarchy?.parents).toEqual(['G1','G2']); + const chart = fixture.debugElement.query(By.directive(ChartStub)); + chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 0, label: 'G2' }] }); fixture.detectChanges(); + expect(card.activeParent).toBe('G2'); + chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 1, label: 'G1' }] }); fixture.detectChanges(); + expect(card.activeParent).toBe('G1'); + (fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(card.activeParent).toBeUndefined(); http.expectNone(() => true); + expect(page.result().figure).toEqual(sample.figure); + }); + it.each(['http', 'suppression', 'mismatch'])('C2 conserva la figura publicada cuando %s impide la jerarquía', reason => { + const sample = candidate(), request = http.expectOne(r => r.url.endsWith('/datos')); + if (reason === 'http') request.flush({}, { status: 503, statusText: 'Unavailable' }); + else { if (reason === 'suppression') sample.data.filas[0]['suprimido'] = 1; + else sample.data.filas[0]['n'] = 999; request.flush(sample.data); } + fixture.detectChanges(); expect(page.result().status).toBe('ready'); + expect(page.result().hierarchy).toBeUndefined(); expect(page.result().figure).toEqual(sample.figure); + }); + it('C2 cancela metadatos pendientes al cambiar tema y no presenta resultados obsoletos', () => { + candidate(); const old = http.expectOne(r => r.url.endsWith('/datos')); + fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); + expect(old.cancelled).toBe(true); expect(page.result().status).toBe('loading'); + figure().flush({ data: [], layout: {} }); expect(page.result().hierarchy).toBeUndefined(); + }); it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => { fixture.componentRef.setInput('dominio', 'cama'); @@ -56,7 +109,8 @@ describe('IndicadorFigurePanel', () => { const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }], layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } }); - load(); request().flush(response('Nota vigente')); fixture.detectChanges(); + load(); http.expectOne(r => r.url.endsWith('/datos')).flush({ id: 'i1', contrato: 'C2', tipo_periodo: 'semestre', periodos: [], filas: [] }); + request().flush(response('Nota vigente')); fixture.detectChanges(); for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) { fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width); @@ -104,7 +158,7 @@ describe('IndicadorFigurePanel', () => { it.each([ ['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']], - ['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']], + ['C2', ['conteos por categoría', 'distribución de cada grupo y periodo', 'SIN_DATO']], ['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']], ['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']], ['toString', ['No hay una explicación específica']], diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index c1c3b6a..0219ae3 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -1,8 +1,8 @@ -import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal } from '@angular/core'; +import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal, output } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; -import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models'; +import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; import { figurePresentation } from './indicadores.presentation'; import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; @@ -10,6 +10,10 @@ import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory'; import { httpMessage } from './indicadores-http'; import { figureIdentity, identityElementId } from './indicadores-identities'; +import { DonutHierarchy, DonutSelection, donutHierarchy, donutPeriod } from './indicadores-donut-drilldown'; +import { IndicadoresSnapshots } from './indicadores-snapshots'; +import { c2Capability, c2Figure } from './indicadores-c2-adapter'; +import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; @Component({ selector: 'app-indicador-figure-panel', @@ -18,14 +22,35 @@ import { figureIdentity, identityElementId } from './indicadores-identities';

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

Filtro general aplicado: {{ appliedSummary }}

+ @if (figuraId === 'fig_c2_barras' && capabilities.length) { + + @if (!singlePeriod) {

Selecciona un periodo para consultar la distribución estratificada.

} + } + [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (hierarchySelected)="hierarchySelected.emit($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" /> + @if (dimension && result().status === 'ready') { + @if (hasSuppressedCells) {

Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

} + @if (hasMissingCells) {

Hay datos no disponibles; los espacios sin barra no representan un cero observado.

} +
Valores publicados y celdas suprimidas +
+ @for (cell of cells; track $index) { } +
CategoríaEstratoConteo
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}
+
+ @if (!cells.length) {

No hay categorías publicadas para esta selección.

} + }
`, styles: ` :host { display: block; min-width: 0; } section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); } .applied-summary { color: var(--issste-text-secondary); overflow-wrap: anywhere; } + select { margin: .5rem; padding: .75rem; max-width: 100%; background: var(--issste-surface); color: var(--issste-text); } + .cells { overflow: auto; max-height: 24rem; } th, td { text-align: start; padding: .5rem; } .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; @@ -40,9 +65,32 @@ export class IndicadorFigurePanel implements OnChanges { @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; + @Input() localSelection: DonutSelection = {}; + readonly hierarchySelected = output(); + dimension: DimensionEstrato | '' = ''; + cells: StratifiedCell[] = []; + get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } + get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); } + private stratifiedData?: IndicadorDatos; + get capabilities() { return stratifiedCapabilities(this.indicador); } + get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; } + changeDimension(value: DimensionEstrato | '') { + if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return; + if (this.dimension === value) return; + this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure(); + } + private presentStratified(data: IndicadorDatos): FigureState { + const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, this.localSelection); + this.cells = adapted.cells; + return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id, + tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }), + source: 'datos', footnotes: data.notas, + emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' }; + } private readySelection?: FigureSelection; private plotWidth?: number; private readonly service = inject(IndicadoresService); + private readonly snapshots = inject(IndicadoresSnapshots); private readonly destroyRef = inject(DestroyRef); private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>(); private generation = 0; @@ -52,8 +100,7 @@ export class IndicadorFigurePanel implements OnChanges { get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; } constructor() { this.figureRequests.pipe(switchMap(request => request - ? defer(() => this.service.figura(request.selection)).pipe( - map(figure => this.present(figure, request.selection)), + ? defer(() => this.loadFigure(request.selection)).pipe( catchError(error => of({ status: 'error', message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 @@ -70,31 +117,80 @@ export class IndicadorFigurePanel implements OnChanges { } }); } - private present(figure: NonNullable, selection: FigureSelection): FigureState { + private loadFigure(selection: FigureSelection) { + if (this.dimension && selection.periodos?.length === 1 && this.capabilities.includes(this.dimension)) { + return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo!, selection.periodos, this.indicador.version, { estrato: this.dimension }).pipe(map(data => { + if (data.periodos.length !== 1 || data.periodos[0] !== selection.periodos![0]) throw new Error('Periodo estratificado inválido'); + const state = this.presentStratified(data); this.stratifiedData = data; return state; + })); + } + if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) { + // Both panels, KPI and numeric table share the exact same transport key. + // Do not catch /datos errors here: a backend failure is a real error state. + return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe( + switchMap(data => { + if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.'); + const adapted = c2Figure(data, selection); + return adapted.status === 'supported' + ? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const, + footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage }) + : this.publishedFigure(selection, adapted.reason); + })); + } + return this.publishedFigure(selection); + } + private publishedFigure(selection: FigureSelection, fallbackReason?: string) { + return defer(() => this.service.figura(selection)).pipe( + switchMap(figure => { + const period = this.indicador.contrato === 'C2' + ? donutPeriod(figure) : undefined; + const present = (hierarchy?: DonutHierarchy) => ({ ...this.present(figure, selection, hierarchy), source: 'figuras' as const, fallbackReason }); + // A fallback has already read /datos; don't request a different subset. + return !fallbackReason && period && selection.tipoPeriodo + ? this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, [period], this.indicador.version).pipe( + map(data => present(donutHierarchy(figure, data))), + // The optional hierarchy must never prevent the published figure. + catchError(() => of(present()))) + : of(present()); + })); + } + private present(figure: NonNullable, selection: FigureSelection, hierarchy?: DonutHierarchy): FigureState { const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth); return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes, - categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth }; + categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth, hierarchy, + plotWidth: selection.figura === 'fig_c2_donas' && this.indicador.contrato === 'C2' && this.plotWidth !== undefined + ? (this.plotWidth < 480 ? 320 : 480) : undefined }; } updatePlotWidth(width: number) { if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return; this.plotWidth = Math.floor(width); + if (this.dimension) return; const state = this.result(); - if (this.visualProfile.axisLabels?.enabled && state.status === 'ready' && state.figure && this.readySelection) { - const next = this.present(state.figure, this.readySelection); + const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas'; + if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut) + && state.status === 'ready' && state.figure && this.readySelection) { + const presentation = this.present(state.figure, this.readySelection, state.hierarchy); + const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes }; // A width change within the same label budget must not hide/repaint an // equivalent graph (for example when only the scrollbar gutter changes). - if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth]) - !== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth])) this.result.set(next); + if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth, next.plotWidth]) + !== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth, state.plotWidth])) this.result.set(next); } } ngOnChanges(changes: SimpleChanges) { + if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = ''; const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); this.titleId = identityElementId(identity) + '-title'; const key = this.requestKey(); if (key === this.currentKey) { + if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') { + try { this.result.set(this.presentStratified(this.stratifiedData)); } + catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); } + } const state = this.result(); if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) { - this.result.set(this.present(state.figure, this.readySelection)); + const next = this.present(state.figure, this.readySelection, state.hierarchy); + this.result.set({ ...state, ...next, footnotes: state.source === 'datos' ? state.footnotes : next.footnotes }); } return; } @@ -112,12 +208,13 @@ export class IndicadorFigurePanel implements OnChanges { } private requestKey() { return JSON.stringify([figureIdentity(this.dominio, this.indicador.id, this.figuraId), - this.tema, this.applied?.revision, this.applied && selectionKey(this.applied), - this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId)]); + this.indicador.version, this.tema, this.applied?.revision, this.applied && selectionKey(this.applied), + this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId), this.dimension]); } requestFigure() { if (!this.visible) return; this.currentKey = this.requestKey(); + this.stratifiedData = undefined; this.cells = []; const applied = this.applied; const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo); this.generation++; diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 6c0efd1..81d9379 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -8,6 +8,7 @@ import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorDatos, Dominio } from './indicadores.models'; +import { IndicadoresMemory } from './indicadores-memory'; describe('KPI integración con autoridad global', () => { let fixture: ReturnType>; let http: HttpTestingController; @@ -17,7 +18,10 @@ describe('KPI integración con autoridad global', () => { http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); }); - function load(domain: Dominio, missing = false, periods = ['2025-S1']) { + 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 })) }); @@ -33,16 +37,19 @@ describe('KPI integración con autoridad global', () => { const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] }; fixture.componentInstance.applyFilters(); fixture.detectChanges(); } - it('TEA sin catálogo muestra sus tres destacados sin consultar datos', () => { - expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); - expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.tea.map(d => d.id)); + it('TEA sin catálogo no muestra destacados ni consulta datos', () => { + expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull(); + expect(panels().map(p => p.definition.id)).toEqual([]); expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); }); it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => { fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]); - load('tea'); const req = requests(); - expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.map(d => '/tea/indicadores/' + d.id + '/datos')); - req.forEach((r, i) => r.flush(response(i, 'tea'))); fixture.detectChanges(); + load('tea'); const initial = requests(); + expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']); + initial[0].flush(response(0, 'tea')); fixture.detectChanges(); + const req = requests(); + expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos')); + req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges(); expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]); expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.'); }); @@ -79,9 +86,9 @@ describe('KPI integración con autoridad global', () => { load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i))); }); - it('el catálogo gráfico no determina membresía de los KPI destacados', () => { - load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.map(d => d.id)); - expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3); + 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); const req = requests(); expect(req).toHaveLength(2); 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 => { @@ -106,25 +113,25 @@ describe('KPI integración con autoridad global', () => { expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot); } finally { page.kpisByDomain.cacu = definitions; } }); - it('retirar un ID del catálogo gráfico conserva todos los KPI configurados', () => { + it('retirar un ID del catálogo conserva los otros KPI y los filtros', () => { load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters); page.catalog.set(page.catalog().slice(1)); fixture.detectChanges(); - expect(panels()).toEqual(before); expect(page.filters).toEqual(filters); - expect(panels()).toHaveLength(3); http.expectNone(() => true); + expect(panels()).toEqual(before.slice(1)); expect(page.filters).toEqual(filters); + expect(panels()).toHaveLength(2); http.expectNone(() => true); }); it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => { const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges(); - expect(page.catalogLoading()).toBe(true); expect(panels()).toHaveLength(3); + expect(page.catalogLoading()).toBe(true); expect(panels()).toHaveLength(0); expect(fixture.nativeElement.textContent).toContain('Cargando catálogo'); http.expectOne('/cacu/indicadores').flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); expect(page.catalogError()).toBeTruthy(); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); - expect(fixture.nativeElement.querySelector('.kpi-section')).toBeTruthy(); expect(panels()).toHaveLength(3); + expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); expect(panels()).toHaveLength(0); expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles'); page.retryCatalog(); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges(); expect(page.catalogError()).toBe(''); expect(page.catalogLoading()).toBe(false); - expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(3); + expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(0); http.expectNone(() => true); }); it.each(['suprimido', 'nulo', 'sin filas'] as const)('KPI publicado con resultado %s conserva tarjeta y definición', scenario => { @@ -139,6 +146,7 @@ describe('KPI integración con autoridad global', () => { expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true); }); it('KPI publicado sin periodos con reporte mantiene sus tres tarjetas sin consultar datos', () => { + TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu'); fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] }))); http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges(); @@ -163,36 +171,40 @@ describe('KPI integración con autoridad global', () => { expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); } }); - it('Aplicar equivalente termina el modo inicial sin cambiar revisión, borrador o selección', () => { - load('cacu', false, ['2025-S2', '2025-S1']); - requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); - requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); - expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); - const page = fixture.componentInstance, applied = page.filters!.applied, snapshot = structuredClone(page.filters); - expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); - (fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click(); fixture.detectChanges(); - expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); expect(page.filters).toEqual(snapshot); + it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => { + load('cacu', false, ['2025-S2', '2025-S1'], true); + const latest = requests(); expect(latest).toHaveLength(1); + const hidden = response(0, 'cacu', '2025-S2'); hidden.filas[0]['suprimido'] = 1; latest[0].flush(hidden); + requests()[0].flush(response(0)); fixture.detectChanges(); + requests().forEach((r, i) => r.flush(response(i + 1))); fixture.detectChanges(); + expect(panels().every(p => p.temporalReference === '2025-S1')).toBe(true); + const page = fixture.componentInstance; page.filters!.editors.semestre!.draft = { mode: 'todos' }; + page.applyFilters(); fixture.detectChanges(); + requests().forEach((r, i) => { const data = response(i + 1, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); fixture.detectChanges(); + expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.temporalReference === '2025-S2')).toBe(true); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true); - load('cama'); requests().forEach((r, i) => r.flush(response(i, 'cama'))); expect(page.initialKpiPresentation).toBe(true); - load('cacu'); expect(page.initialKpiPresentation).toBe(false); expect(panels()).toHaveLength(3); - expect(panels().every(p => p.temporalReference === '2025-S2' && p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true); }); it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => { - load('cacu'); requests().forEach((r, i) => r.flush(response(i))); - load('cama'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); requests().forEach((r, i) => r.flush(response(i, 'cama'))); - load('cacu'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); + for (const domain of ['cacu', 'cama'] as const) { + load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges(); + requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges(); + expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false); + } + load('cacu', false, ['2025-S1'], true); + expect(fixture.componentInstance.initialPeriodBlocked).toBe(false); expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true); }); it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => { - load('cacu', false, ['2025-S2', '2025-S1']); - requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); - const old = requests(); expect(old).toHaveLength(3); + load('cacu', false, ['2025-S2', '2025-S1'], true); + const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data); + const old = requests(); expect(old).toHaveLength(1); load('cama'); expect(old.every(r => r.cancelled)).toBe(true); requests().forEach((r, i) => r.flush(response(i, 'cama'))); - load('cacu'); const resumed = requests(); expect(resumed).toHaveLength(3); - resumed.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i)); }); - expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); http.expectNone(() => true); + load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1); + resumed[0].flush(response(0)); fixture.detectChanges(); + requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); }); + expect(panels().every(p => p.temporalReference === '2025-S1')).toBe(true); http.expectNone(() => true); }); it('aplicado explícito y luego Todos nunca buscan periodos anteriores', () => { load('cacu', false, ['2025-S2', '2025-S1']); const outgoing = requests(); diff --git a/src/app/features/indicadores/indicador-kpi-panel.ts b/src/app/features/indicadores/indicador-kpi-panel.ts index dacc93e..8bbaf5e 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.ts @@ -10,8 +10,9 @@ import { IndicadorKpiCard } from './indicador-kpi-card'; import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi'; import { PeriodAvailability, sortedPeriods } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; +import { IndicadoresSnapshots } from './indicadores-snapshots'; -interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; } +interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; version?: string; } @Component({ selector: 'app-indicador-kpi-panel', @@ -32,6 +33,7 @@ export class IndicadorKpiPanel implements OnChanges { @Input() availability?: PeriodAvailability; @Input() initialPresentation = false; private readonly queries = inject(IndicadoresKpiQueries); + private readonly snapshots = inject(IndicadoresSnapshots); private readonly destroyRef = inject(DestroyRef); private readonly requests = new Subject(); private key = ''; @@ -68,8 +70,9 @@ export class IndicadorKpiPanel implements OnChanges { const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable => { const period = periods[index]; const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } }; - return this.queries.datos(domain, definition.id, applied.tipo, period).pipe( - map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period } as KpiDisplay)), + return this.queries.datos(domain, definition.id, applied.tipo, period, this.indicador?.version).pipe( + map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period, + version: typeof data['version'] === 'string' ? data['version'] : undefined } as KpiDisplay)), catchError(error => of({ period, state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta', info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })), @@ -88,10 +91,12 @@ export class IndicadorKpiPanel implements OnChanges { }), takeUntilDestroyed(this.destroyRef)).subscribe(result => { this.usedPeriod.set(result.period); this.result.set(result); + if (this.applied) this.snapshots.publishKpi(this.dominio, this.indicador ?? this.definition, this.applied, + { ...result, period: this.temporalReference, unit: this.definition.unit }, result.version); }); } ngOnChanges() { - const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied && selectionKey(this.applied), + const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied?.revision, this.applied && selectionKey(this.applied), this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]); if (key === this.key) return; this.key = key; diff --git a/src/app/features/indicadores/indicador-metadata.spec.ts b/src/app/features/indicadores/indicador-metadata.spec.ts new file mode 100644 index 0000000..3f42810 --- /dev/null +++ b/src/app/features/indicadores/indicador-metadata.spec.ts @@ -0,0 +1,17 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadorMetadata } from './indicador-metadata'; +describe('Metadatos opcionales verificados',()=>{ + it('muestra referencias y poblaciones como texto seguro y etiquetas legibles',()=>{ + TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); + const f=TestBed.createComponent(IndicadorMetadata), http=TestBed.inject(HttpTestingController); + f.componentRef.setInput('dominio','cacu');f.componentRef.setInput('indicador','future');f.detectChanges(); + http.expectOne('/cacu/indicadores/future/metadatos').flush({referencias:[{tipo:'citation',etiqueta:'Guía publicada ',ref:'Indicador 7'}],poblaciones:[{grupo:'TOTAL',codigo:'initial-population',descripcion:'Pacientes con estudio publicado.'}]});f.detectChanges(); + expect(f.nativeElement.textContent).toContain('Guía publicada ');expect(f.nativeElement.querySelector('img')).toBeNull();expect(f.nativeElement.textContent).toContain('Pacientes con estudio publicado.');expect(f.nativeElement.textContent).not.toMatch(/initial-population|citation|TOTAL/);http.verify();f.destroy(); + }); + it.each([{}, {referencias:[],poblaciones:[]},{referencias:'invalid'}])('conserva el estado actual sin campos opcionales válidos',data=>{ + TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); + const f=TestBed.createComponent(IndicadorMetadata), http=TestBed.inject(HttpTestingController);f.componentRef.setInput('dominio','tea');f.componentRef.setInput('indicador','i1');f.detectChanges();http.expectOne('/tea/indicadores/i1/metadatos').flush(data);f.detectChanges();expect(f.nativeElement.textContent).toContain('no está disponible');http.verify();f.destroy(); + }); +}); diff --git a/src/app/features/indicadores/indicador-metadata.ts b/src/app/features/indicadores/indicador-metadata.ts new file mode 100644 index 0000000..23d9e83 --- /dev/null +++ b/src/app/features/indicadores/indicador-metadata.ts @@ -0,0 +1,32 @@ +import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { catchError, of, Subject, switchMap } from 'rxjs'; +import { Dominio, IndicadorMetadatos } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; + +@Component({ + selector: 'app-indicador-metadata', + template: ` + @if (loading) {

Cargando información metodológica…

} + @if (metadata?.referencias?.length) { +

Referencias

    @for (ref of metadata!.referencias; track $index) {
  • {{ ref.etiqueta }}@if (ref.ref) { · {{ ref.ref }} }
  • }
+ } + @if (metadata?.poblaciones?.length) { +

Poblaciones del estudio

    @for (p of metadata!.poblaciones; track $index) {
  • {{ p.descripcion }}
  • }
+ } + @if (!loading && !metadata?.referencias?.length && !metadata?.poblaciones?.length) {

La información metodológica ampliada no está disponible para este indicador.

} + `, +}) +export class IndicadorMetadata implements OnChanges { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: string; + private readonly service = inject(IndicadoresService); + private readonly requests = new Subject(); + metadata?: IndicadorMetadatos; + loading = false; + private readonly changeDetector = inject(ChangeDetectorRef); + constructor() { + this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); }); + } + ngOnChanges() { this.metadata = undefined; this.loading = true; this.requests.next(); } +} diff --git a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts new file mode 100644 index 0000000..7ccdad0 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts @@ -0,0 +1,177 @@ +import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter'; +import { c2Color, C2_PALETTE } from './indicadores-c2-palette'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; +import { FigureSelection } from './indicadores.models'; +import { donutFixture } from './indicadores-donut-drilldown.testing'; +import { 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'] }; +function supported(data = c2Fixture(), s = selection) { + const result = c2Figure(data, s); + if (result.status !== 'supported') throw new Error(result.reason); + return result; +} +describe('C2: datos publicados a Plotly', () => { + it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => { + const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure; + expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']])); + expect(result.model.total).toBe(10); expect(result.model.unit).toBe('paciente'); expect(result.hierarchy?.parents).toEqual(['G1', 'G2']); + expect(result.model.notes).toEqual(data.notas); expect(data).toEqual(before); + }); + it('dona simple sin jerarquía y barras comparten categorías, conteos, unidades y orden', () => { + const data = c2Fixture(); data['grupos_de_categoria'] = {}; + Object.values(data['categorias'] as Record>).forEach(c => c['grupo'] = null); + 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' } }); + }); + 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' }); + const final = figurePresentation(bars.figure, { ...selection, figura: 'fig_c2_barras' }).figure; + expect(final.layout['xaxis']).toMatchObject({ showline: true, linewidth: 1, ticks: 'outside', automargin: true, zeroline: false }); + expect(final.layout['yaxis']).toMatchObject({ showline: true, linewidth: 1, ticks: 'outside', automargin: true, ticklabelstandoff: 12 }); + expect(final.layout['margin']).toMatchObject({ l: 76, r: 28, t: 112, b: 62 }); + expect(final.data[0]['hovertemplate']).toContain(''); + expect(final.data[0]['hovertemplate']).not.toContain('2025-S2'); + }); + it('el layout final de dona simple reserva el sector superior derecho para la leyenda', () => { + const data = c2Fixture(); data['grupos_de_categoria'] = {}; + Object.values(data['categorias'] as Record>).forEach(c => c['grupo'] = null); + const result = supported(data); + const final = figurePresentation(result.figure, selection).figure; + expect(final.layout['legend']).toMatchObject({ orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top' }); + expect(final.data[0]['domain']).toEqual({ x: [0, 0.72], y: [0, 1] }); + expect(final.data[0]['hovertemplate']).toContain(''); + }); + it('ordena por orden publicado aunque las filas lleguen desordenadas; conserva ceros explícitos', () => { + const data = c2Fixture(); data.filas[0]['n'] = 0; data.filas.reverse(); + const result = supported(data); expect(result.figure.data[0]['labels']).toEqual(['A','B','C']); expect(result.figure.data[0]['values']).toEqual([0,3,1]); + expect(result.figure.layout['meta']).toMatchObject({ denominator: 4 }); + }); + it.each(['null', 'suppressed', 'unknown-suppression', 'negative', 'nan', 'fraction', 'overflow', 'missing-category', 'duplicate', 'unknown-category', 'duplicate-order', 'wrong-period', 'stratum', 'overlapping-group', 'missing-unit', 'mixed-groups', 'bad-color', 'ambiguous-label', 'future-meta', 'denominator'])('usa respaldo sin reconstruir %s', kind => { + const data = c2Fixture(), row = data.filas[0], catalog = data['categorias'] as Record>; + if (kind === 'null') row['n'] = null; + if (kind === 'suppressed') { row['suprimido'] = 1; row['n'] = 100; } + if (kind === 'unknown-suppression') delete row['suprimido']; + if (kind === 'negative') row['n'] = -1; + if (kind === 'nan') row['n'] = NaN; + if (kind === 'fraction') row['n'] = 1.5; + if (kind === 'overflow') row['n'] = Number.MAX_SAFE_INTEGER; + if (kind === 'missing-category') data.filas.pop(); + if (kind === 'duplicate') data.filas.push({ ...row }); + if (kind === 'unknown-category') row['categoria'] = 'outside'; + if (kind === 'duplicate-order') data.filas[1]['orden'] = row['orden']; + if (kind === 'wrong-period') row['periodo'] = '2024-S1'; + if (kind === 'stratum') row['estrato'] = 'age'; + if (kind === 'overlapping-group') row['grupo'] = 'other'; + if (kind === 'missing-unit') delete data['unidad']; + if (kind === 'mixed-groups') catalog['A']['grupo'] = null; + if (kind === 'bad-color') catalog['A']['color'] = 'url(external)'; + if (kind === 'ambiguous-label') catalog['A']['etiqueta'] = 'B'; + if (kind === 'future-meta') data['meta'] = { future: true }; + if (kind === 'denominator') row['denominador'] = 100; + expect(c2Figure(data, selection).status).toBe('unsupported'); + }); + it('distingue ausencia de filas de una partición completa de ceros, sin inventar porcentajes', () => { + const empty = c2Fixture(); empty.filas = []; + expect(supported(empty).emptyMessage).toContain('No hay filas'); expect(supported(empty).figure.data).toEqual([]); + const zeros = c2Fixture(); zeros.filas.forEach(r => r['n'] = 0); + expect(supported(zeros).emptyMessage).toContain('son cero'); expect(supported(zeros).figure.data).toEqual([]); + expect(supported(zeros, { ...selection, figura: 'fig_c2_barras' }).figure.data[0]['x']).toEqual([0,0,0]); + }); + it('no combina unidades discordantes entre filas y metadatos', () => { + const data = c2Fixture(); data.filas[0]['unidad'] = 'examen'; + expect(c2Figure(data, selection).status).toBe('unsupported'); + }); + it('porcentajes sólo sobre suma completa verificable, incluye categorías sin dato', () => { + 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); + const bars = supported(data, { ...selection, figura: 'fig_c2_barras' }), before = structuredClone(bars); + expect(donutView(result.figure, result.hierarchy!).data[0]['values']).toEqual([6,4]); + const root = donutView(result.figure, result.hierarchy!); + const expanded = donutView(result.figure, result.hierarchy!, 'G2'); + const changed = donutView(result.figure, result.hierarchy!, 'G1'); + expect(root.layout['legend']).toMatchObject({ orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top' }); + expect(expanded.layout['legend']).toEqual(root.layout['legend']); + expect(changed.layout['legend']).toEqual(root.layout['legend']); + expect(expanded.data[0]['values']).toEqual([3,1]); + expect(expanded.data[0]['hovertemplate']).toContain('paciente'); + expect(expanded.data[1]['hovertemplate']).toContain('paciente'); + for (const trace of [...root.data, ...expanded.data, ...changed.data]) { + expect(trace['hovertemplate']).toContain(''); + expect(trace['hovertemplate']).not.toContain('2025-S2'); + } + const compact = donutView(result.figure, result.hierarchy!, 'G2', 360); + expect(compact.layout['showlegend']).toBe(false); + expect(compact.layout['margin']).toMatchObject({ b: 16, l: 16, r: 16 }); + expect(compact.data[0]['legendgrouptitle']).toEqual({ text: 'Categorías de G2' }); + expect(changed.data[0]['values']).toEqual([6]); + expect(root.data[0]['labels']).toEqual(['G1','G2']); + expect(result.figure).toEqual(original); expect(bars).toEqual(before); + }); + it('no asume IDs de indicador ni dominio; sólo capacidades publicadas', () => { + for (const dominio of ['tea','cacu','cama'] as const) { + const data = c2Fixture(); data.id = 'future_name'; + expect(supported(data, { ...selection, dominio, indicador: data.id }).model.total).toBe(10); + } + expect(c2Capability('C1', 'fig_c2_donas')).toBe(false); expect(c2Capability('C3r', 'fig_c2_barras')).toBe(false); + expect(c2Capability('C2', 'future_representation')).toBe(false); + }); + it('periodo mensual concordante; varios periodos, tipo incorrecto y periodo distinto usan respaldo', () => { + const data = c2Fixture(); data.tipo_periodo = 'mes'; data.periodos = ['2025-02']; data.filas.forEach(r => r['periodo'] = '2025-02'); + expect(supported(data, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-02'] }).model.period).toBe('2025-02'); + expect(c2Figure(data, selection).status).toBe('unsupported'); + const sample = c2Fixture(); sample.periodos.push('2026-S1'); expect(c2Figure(sample, selection).status).toBe('unsupported'); + expect(c2Figure(c2Fixture(), { ...selection, periodos: ['2026-S1'] }).status).toBe('unsupported'); + }); + it('árbol y ruta permiten descendientes de profundidad variable sin definir un JSON de nivel tres', () => { + const nodes = [...supported().model.nodes, { id: 'detail', label: 'Detalle sintético', parentId: 'category:B' }, { id: 'deeper', label: 'Más detalle', parentId: 'detail' }]; + expect(c2Descendants(nodes, { path: ['group:g2', 'category:B'] }).map(n => n.id)).toEqual(['detail','deeper']); + expect(c2Descendants(nodes, { path: ['group:g1', 'category:B'] })).toEqual([]); + expect(c2Descendants(nodes, { path: [] })).toBe(nodes); + }); +}); + +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>)['A']['color'] = '#D98E4A'; + const figure = supported(data, { ...selection, tema }).figure; + expect((figure.data[0]['marker'] as Record)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']); + 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(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined(); + }); + it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => { + const luminance = (hex: string) => { + const c = hex.slice(1).match(/../g)!.map(v => parseInt(v,16)/255).map(v => v <= .04045 ? v/12.92 : ((v+.055)/1.055)**2.4); + return c[0]*.2126+c[1]*.7152+c[2]*.0722; + }; + for (const theme of [C2_PALETTE.claro,C2_PALETTE.oscuro]) { + const text = luminance(theme.text), background = luminance(theme.background); + const outline = luminance(theme.outline); + expect((Math.max(text,background)+.05)/(Math.min(text,background)+.05)).toBeGreaterThan(4.5); + expect((Math.max(outline,background)+.05)/(Math.min(outline,background)+.05)).toBeGreaterThan(1.4); + } + }); + it('da aire a etiquetas y leyendas y conserva guías discretas en las barras', () => { + const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' }).figure; + expect(bars.layout['margin']).toMatchObject({ l: 76, t: 112, b: 62 }); + expect(bars.layout['legend']).toMatchObject({ orientation: 'h', x: 1, xanchor: 'right', y: 1.12, yanchor: 'bottom' }); + expect(bars.layout['xaxis']).toMatchObject({ showgrid: true, zeroline: false }); + expect(bars.layout['yaxis']).toMatchObject({ automargin: true, ticklabelstandoff: 12, showgrid: false }); + expect((bars.data[0]['marker'] as Record)['line']).toMatchObject({ color: C2_PALETTE.claro.outline, width: 0.7 }); + const donut = supported(c2Fixture(), selection).figure; + expect((donut.data[0]['marker'] as Record)['line']).toMatchObject({ color: C2_PALETTE.claro.outline, width: 0.7 }); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c2-adapter.testing.ts b/src/app/features/indicadores/indicadores-c2-adapter.testing.ts new file mode 100644 index 0000000..187b597 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-adapter.testing.ts @@ -0,0 +1,7 @@ +import { IndicadorDatos } from './indicadores.models'; +import { donutFixture } from './indicadores-donut-drilldown.testing'; + +export function c2Fixture(): IndicadorDatos { + return { ...donutFixture().data, titulo: 'Distribución sintética', unidad: 'paciente', + grupos: { TOTAL: 'Total' }, notas: ['Nota metodológica publicada.'], meta: null }; +} diff --git a/src/app/features/indicadores/indicadores-c2-adapter.ts b/src/app/features/indicadores/indicadores-c2-adapter.ts new file mode 100644 index 0000000..e19b826 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-adapter.ts @@ -0,0 +1,118 @@ +import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models'; +import { DonutHierarchy } from './indicadores-donut-drilldown'; +import { c2Color, c2Theme } from './indicadores-c2-palette'; + +export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; } +// Normalized presentation nodes and a selection path are independent of Plotly. +// No level-3 wire format is assumed. General bars keep the complete partition; +// stratified bars have their own decoder and consume the shared local selection. +export interface C2Node { id: string; label: string; parentId?: string; } +export interface C2Selection { path: readonly string[]; } +export function c2Descendants(nodes: readonly C2Node[], selection: C2Selection): readonly C2Node[] { + let parentId: string | undefined; + for (const id of selection.path) { + if (!nodes.some(n => n.id === id && n.parentId === parentId)) return []; + parentId = id; + } + const found = new Set(); + if (!parentId) return nodes; + const visit = (id: string) => { + for (const node of nodes.filter(n => n.parentId === id)) { + if (found.has(node.id)) continue; + found.add(node.id); visit(node.id); + } + }; + visit(parentId); + return nodes.filter(n => found.has(n.id)); +} +export interface C2Distribution { + period: string; unit: string; title: string; categories: readonly C2Category[]; + parents: readonly C2Node[]; nodes: readonly C2Node[]; total: number; notes: readonly string[]; +} +export type C2Result = { status: 'unsupported'; reason: string } + | { status: 'supported'; model: C2Distribution; figure: PlotlyFigure; hierarchy?: DonutHierarchy; emptyMessage?: string }; +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const label = (v: unknown): v is string => typeof v === 'string' && !!v.trim() && !/[<>&]/.test(v); +const color = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v); +export function c2Capability(contract: string, representation: string): boolean { + return contract === 'C2' && ['fig_c2_donas', 'fig_c2_barras'].includes(representation); +} + +export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Result { + const unsupported = (reason: string): C2Result => ({ status: 'unsupported', reason }); + if (!c2Capability(data.contrato, selection.figura)) return unsupported('Representación no soportada'); + if (data.id !== selection.indicador || data.tipo_periodo !== selection.tipoPeriodo + || data.periodos.length !== 1 || parsePeriodos(data.periodos[0], data.tipo_periodo)?.length !== 1 + || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0]))) return unsupported('Se requiere un periodo único concordante'); + if (!label(data['unidad']) || !label(data['titulo']) || !record(data['categorias']) + || !record(data['grupos_de_categoria']) || !record(data['grupos']) + || Object.keys(data['grupos']).length !== 1 || !Object.hasOwn(data['grupos'], 'TOTAL') + || data['estrato'] != null || data['meta'] != null + || !Array.isArray(data.notas) || !data.notas.every(label)) return unsupported('Metadatos insuficientes o no soportados'); + const period = data.periodos[0], catalog = data['categorias'], groups = data['grupos_de_categoria']; + if (!Object.keys(catalog).length) return unsupported('Catálogo de categorías vacío'); + const categories: C2Category[] = [], orders = new Set(), ids = new Set(); + const rows = [...data.filas].sort((a, b) => Number(a['orden']) - Number(b['orden'])); + for (const row of rows) { + const id = row['categoria'], n = row['n'], order = row['orden']; + if (row['periodo'] !== period || row['grupo'] !== 'TOTAL' || row['estrato'] != null + || (row['unidad'] !== undefined && row['unidad'] !== data['unidad']) + || (row['suprimido'] !== 0 && row['suprimido'] !== false) || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0 + || typeof order !== 'number' || !Number.isFinite(order) || orders.has(order) + || typeof id !== 'string' || ids.has(id) || !Object.hasOwn(catalog, id)) return unsupported('Partición incompleta, suprimida o no verificable'); + const entry = catalog[id]; + if (!record(entry) || !label(entry['etiqueta']) + || (entry['color'] != null && !color(entry['color'])) + || (entry['grupo'] != null && (typeof entry['grupo'] !== 'string' || !Object.hasOwn(groups, entry['grupo']) || !label(groups[entry['grupo']])))) return unsupported('Categoría sin metadatos verificables'); + orders.add(order); ids.add(id); + categories.push({ id, label: entry['etiqueta'], value: n, color: entry['color'] as string | undefined, + parentId: typeof entry['grupo'] === 'string' ? entry['grupo'] : undefined }); + } + if (categories.length && categories.length !== Object.keys(catalog).length) return unsupported('Faltan categorías explícitas'); + if (new Set(categories.map(c => c.label)).size !== categories.length) return unsupported('Etiquetas ambiguas'); + const total = categories.reduce((sum, c) => sum + c.value, 0); + if (!Number.isSafeInteger(total) || rows.some(r => Object.hasOwn(r, 'denominador') && r['denominador'] !== total) + || (Object.hasOwn(data, 'denominador') && data['denominador'] !== total)) return unsupported('Denominador no verificable'); + const parentIds = [...new Set(categories.flatMap(c => c.parentId ? [c.parentId] : []))]; + if ((parentIds.length && categories.some(c => !c.parentId)) + || (categories.length && Object.keys(groups).length !== parentIds.length)) return unsupported('Relación de grupos incompleta'); + const parents = parentIds.map(id => ({ id: 'group:' + id, label: groups[id] as string })); + if (new Set(parents.map(p => p.label)).size !== parents.length) return unsupported('Grupos ambiguos'); + const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))]; + const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] }; + const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label); + const colors = 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 = { 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' + ? { orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top', itemclick: false, itemdoubleclick: false } + : { orientation: 'h', x: 1, xanchor: 'right', y: 1.12, yanchor: 'bottom', itemclick: false, itemdoubleclick: false }, + meta: { period, unit: model.unit, denominator: total, denominatorScope: 'Suma de conteos publicados de la partición TOTAL, incluyendo categorías sin dato' } }; + const figure: PlotlyFigure = { data: [], layout }; + if (selection.figura === 'fig_c2_barras') { + 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}
%{x} ' + model.unit + '' }]; + 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, + ticklabelstandoff: 12, showgrid: false, showline: true, linecolor: '#AEB7C2', linewidth: 1, + ticks: 'outside', tickcolor: '#AEB7C2' }; + } else if (total > 0) { + layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false, + text: '' + total + '', font: { color: theme.text, size: 18 } }]; + figure.data = [{ type: 'pie', labels, values, marker: { colors, line: { color: theme.outline, width: 0.7 } }, + hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] }, + hovertemplate: '%{label}
%{value} ' + model.unit + '
%{percent} de los ' + total + ' ' + model.unit + ' publicados' }]; + if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label), + values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)), + marker: { colors: parents.map((_, i) => c2Color(undefined, i)), line: { color: theme.outline, width: 0.7 } }, + hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } }); + } + const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0 + ? { parents: parents.map(p => p.label), children: categories.map(c => ({ label: c.label, value: c.value, parent: groups[c.parentId!] as string })), categoryTrace: 0, parentTrace: 1 } : undefined; + return { status: 'supported', model, figure, hierarchy, emptyMessage }; +} diff --git a/src/app/features/indicadores/indicadores-c2-palette.ts b/src/app/features/indicadores/indicadores-c2-palette.ts new file mode 100644 index 0000000..5042997 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-palette.ts @@ -0,0 +1,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']), + 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' }), +}); +export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; } +export function c2Color(published: string | undefined, index: number): string { + return published ?? C2_PALETTE.series[index % C2_PALETTE.series.length]; +} diff --git a/src/app/features/indicadores/indicadores-c2-panel.spec.ts b/src/app/features/indicadores/indicadores-c2-panel.spec.ts new file mode 100644 index 0000000..9a0218d --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-panel.spec.ts @@ -0,0 +1,82 @@ +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 { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { GlobalApplied } from './indicadores-memory'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; +import { IndicadoresSnapshots } from './indicadores-snapshots'; +import { READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure','label','showNotes'], template: '' }) +class ChartStub {} +const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; +const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas','fig_c2_barras'], tipos_periodo: ['semestre'] }; +describe('estrategia C2 /datos y respaldo /figuras', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel); + for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied })) fixture.componentRef.setInput(name,value); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos')); + it('reutiliza payload del KPI y conserva notas al adaptar perfil y ancho, sin /figuras', () => { + TestBed.inject(IndicadoresSnapshots).datos('tea','i1','semestre',['2025-S2']).subscribe(); dataRequest().flush(c2Fixture()); + fixture.detectChanges(); expect(fixture.componentInstance.result().source).toBe('datos'); http.expectNone(() => true); + for (const profile of [BASE_VISUAL_PROFILE,READABLE_VISUAL_PROFILE]) { + fixture.componentRef.setInput('visualProfile',profile); fixture.detectChanges(); fixture.componentInstance.updatePlotWidth(320); + expect(fixture.componentInstance.result().footnotes).toEqual(c2Fixture().notas); + expect(fixture.nativeElement.textContent).toContain('Nota metodológica publicada.'); http.expectNone(() => true); + } + }); + it.each([404,500,503])('HTTP %s en datos es error visible, no figura de respaldo', status => { + fixture.detectChanges(); dataRequest().flush({}, { status, statusText: 'Failure' }); fixture.detectChanges(); + expect(fixture.componentInstance.result().status).toBe('error'); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); http.expectNone(() => true); + fixture.componentInstance.requestFigure(); dataRequest().flush(c2Fixture()); expect(fixture.componentInstance.result().source).toBe('datos'); + }); + it('respuesta malformada/contrato incorrecto no oculta error mediante respaldo', () => { + fixture.detectChanges(); dataRequest().flush({ ...c2Fixture(), contrato: 'C1' }); + expect(fixture.componentInstance.result().status).toBe('error'); http.expectNone(() => true); + }); + it.each(['suppressed','null','metadata','multiple-periods'])('caso %s usa figura publicada y conserva JSON completo', kind => { + fixture.detectChanges(); const data = c2Fixture(); + if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; + if (kind === 'null') data.filas[0]['n'] = null; + if (kind === 'metadata') delete data['unidad']; + if (kind === 'multiple-periods') { data.periodos = []; data.filas = []; } + dataRequest().flush(data); + const original = { data: [{type:'bar',x:[null],y:['Oculto']}],layout: {}, frames: [], unknown: { retained:true } }; + http.expectOne(r => r.url.includes('/figuras/')).flush(original); + expect(fixture.componentInstance.result()).toMatchObject({ source:'figuras',figure:original }); + expect(fixture.componentInstance.result().fallbackReason).toBeTruthy(); http.expectNone(() => true); + }); + it('un error de /figuras durante respaldo también queda visible', () => { + fixture.detectChanges(); dataRequest().flush({ ...c2Fixture(), unidad: null }); + http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'}); + expect(fixture.componentInstance.result().status).toBe('error'); + }); + it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => { + 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'); + const data = c2Fixture(); data.periodos = ['2026-S1']; data.filas.forEach(r => r['periodo'] = '2026-S1'); current.flush(data); + expect(fixture.componentInstance.result().figure?.layout['meta']).toMatchObject({period:'2026-S1'}); + }); + it('dominio y tema renuevan contexto sin mezclar transportes; tema reutiliza mismos datos', () => { + fixture.detectChanges(); dataRequest().flush(c2Fixture()); + fixture.componentRef.setInput('tema','oscuro'); fixture.detectChanges(); + expect(fixture.componentInstance.result().figure?.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); + fixture.componentRef.setInput('dominio','cama'); fixture.detectChanges(); const next = dataRequest(); + expect(next.request.url).toBe('/cama/indicadores/i1/datos'); next.flush(c2Fixture()); + }); + it('carga diferida no consulta datos ni figuras antes de activación', () => { + fixture.componentRef.setInput('visible',false); fixture.detectChanges(); http.expectNone(() => true); + expect(fixture.componentInstance.result().status).toBe('deferred'); + fixture.componentRef.setInput('visible',true); fixture.detectChanges(); dataRequest().flush(c2Fixture()); + expect(fixture.componentInstance.result().source).toBe('datos'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-definitions.html b/src/app/features/indicadores/indicadores-definitions.html new file mode 100644 index 0000000..b90da37 --- /dev/null +++ b/src/app/features/indicadores/indicadores-definitions.html @@ -0,0 +1,56 @@ +

Datos y definiciones · {{ domainNames[dominio] }}

+
+

Información del dominio

+

Dominio: {{ domainNames[dominio] }}.

+ @if (!loading && !error && periodTypes.length) { +

Periodicidad disponible: + @for (tipo of periodTypes; track tipo; let last = $last) { {{ periodNames[tipo] }}{{ last ? '.' : ', ' }} } +

+ } @else {

Periodicidad: pendiente de información.

} +
+
+

Catálogo de indicadores

+

Consulta las gráficas disponibles y la periodicidad de cada indicador.

+ @if (loading) {

Cargando catálogo de indicadores…

} + @else if (error) { +

No se pudo cargar la información del catálogo. {{ error }}

+ + } @else if (!catalog.length) {

No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de información.

} + @else { + @for (item of catalog; track dominio + ':' + item.id) { +
+ {{ item.titulo || 'Nombre pendiente de publicación' }} +
+

Representaciones disponibles

+ @if (item.figuras.length) { +
    @for (figure of item.figuras; track figure) {
  • {{ figureDisplayName(figure, item.figuras) }}
  • }
+ } @else {

No hay representaciones publicadas.

} +

Tipos de periodo admitidos

+ @if (item.tipos_periodo.length) { +
    @for (tipo of item.tipos_periodo; track tipo) {
  • {{ periodNames[tipo] }}
  • }
+ } @else {

Pendiente de información.

} +

Cómo interpretar este indicador

+ @if (interpretation(item).length) { +
    @for (line of interpretation(item); track $index) {
  • {{ line }}
  • }
+ } + @if (opened.has(dominio + ':' + item.id)) { + + } @else { +

{{ item.contrato ? 'La información metodológica ampliada no está disponible para este indicador.' : 'La definición metodológica está pendiente de información.' }}

+ } +
+
+ } + } +
+
+

Interpretación y metodología

+

Ten en cuenta estas limitaciones al consultar las gráficas.

+
    +
  • Un valor nulo significa que no hay un valor disponible; un cero es un valor observado. Los datos suprimidos tampoco representan un cero.
  • +
  • {{ periodInterpretation }}
  • +
  • Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.
  • +
  • Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por denominadores pequeños.
  • +
+

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.

+
diff --git a/src/app/features/indicadores/indicadores-definitions.scss b/src/app/features/indicadores/indicadores-definitions.scss new file mode 100644 index 0000000..8342d69 --- /dev/null +++ b/src/app/features/indicadores/indicadores-definitions.scss @@ -0,0 +1,13 @@ +:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere; + background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +h2 { font-size: 1.5rem; margin-top: 0; } +h3 { font-size: 1.25rem; } +h4 { font-size: 1rem; margin-bottom: .5rem; } +section + section { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); } +.source { color: var(--issste-text-secondary); } +details { border: 1px solid var(--issste-border); border-radius: var(--issste-radius); margin-block: var(--issste-space-2); background: var(--issste-surface); } +summary { cursor: pointer; padding: var(--issste-space-4); font-weight: 600; } +summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; } +.indicator-detail { padding: 0 var(--issste-space-4) var(--issste-space-4); } +li + li { margin-top: var(--issste-space-2); } +ul { padding-inline-start: 1.5rem; } diff --git a/src/app/features/indicadores/indicadores-definitions.ts b/src/app/features/indicadores/indicadores-definitions.ts new file mode 100644 index 0000000..011cae5 --- /dev/null +++ b/src/app/features/indicadores/indicadores-definitions.ts @@ -0,0 +1,38 @@ +import { Component, Input, output } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { Dominio, Indicador, TipoPeriodo } from './indicadores.models'; +import { figureDisplayName } from './indicadores-figure-labels'; +import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; +import { IndicadorMetadata } from './indicador-metadata'; + +@Component({ + selector: 'app-indicadores-definitions', + imports: [MatButtonModule, IndicadorMetadata], + templateUrl: './indicadores-definitions.html', + styleUrl: './indicadores-definitions.scss', +}) +export class IndicadoresDefinitions { + readonly opened = new Set(); + open(id: string, event: Event) { if ((event.target as HTMLDetailsElement).open) this.opened.add(this.dominio + ':' + id); } + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) catalog: readonly Indicador[] = []; + @Input() loading = false; + @Input() error = ''; + readonly retry = output(); + readonly domainNames: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; + readonly periodNames: Record = { semestre: 'Semestral', mes: 'Mensual' }; + readonly figureDisplayName = figureDisplayName; + readonly periodInterpretation = PERIOD_INTERPRETATION; + get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; } + interpretation(item: Indicador) { + if (!item.contrato) return []; + const lines = contractInterpretation(item.contrato, this.dominio); + // Catalog metadata does not describe the traces. Keep the shared C2 guidance + // independent of bars/sectors; the actual figure retains its full explanation. + return lines.filter(line => + !line.includes('Los valores nulos o suprimidos') && + !line.includes('Los puntos suprimidos') && + !line.includes('No hay una explicación específica disponible'), + ).slice(item.contrato === 'C2' ? 1 : 0); + } +} diff --git a/src/app/features/indicadores/indicadores-donut-drilldown.spec.ts b/src/app/features/indicadores/indicadores-donut-drilldown.spec.ts new file mode 100644 index 0000000..5ecd7a5 --- /dev/null +++ b/src/app/features/indicadores/indicadores-donut-drilldown.spec.ts @@ -0,0 +1,120 @@ +import { donutHierarchy, donutPeriod, donutView } from './indicadores-donut-drilldown'; +import { donutFixture } from './indicadores-donut-drilldown.testing'; + +describe('C2 dona jerárquica', () => { + it('mantiene el host, los márgenes y el centro al expandir y restaurar en todos los anchos', () => { + const { figure, data } = donutFixture(), hierarchy = donutHierarchy(figure, data)!; + for (const width of [320,390,768,1440]) { + const initial = donutView(figure,hierarchy,undefined,width); + const expanded = donutView(figure,hierarchy,'G2',width); + const restored = donutView(figure,hierarchy,undefined,width); + expect(initial.data[0]['domain']).toEqual({ x:[0,1],y:[0,1] }); + expect(expanded.data[0]['domain']).toEqual(initial.data[0]['domain']); + expect(expanded.data[1]['domain']).toEqual({ x:[.17,.83],y:[.17,.83] }); + expect(expanded.layout['margin']).toEqual(initial.layout['margin']); + expect(expanded.layout['height']).toBe(440); expect(initial.layout['height']).toBe(440); + expect(expanded.layout['showlegend']).toBe(false); + expect(expanded.layout['annotations']).toEqual([expect.objectContaining({ x:.5,y:.5,text:'4',xanchor:'center',yanchor:'middle' })]); + expect(restored).toEqual(initial); + } + }); it('verifica metadatos contra filas y ambos anillos; enfoca y regresa sin mutar JSON', () => { + const { figure, data } = donutFixture(), snapshot = JSON.stringify({ figure, data }); + const hierarchy = donutHierarchy(figure, data)!; + expect(hierarchy.parents).toEqual(['G1', 'G2']); + const root = donutView(figure, hierarchy); + expect(root.data).toHaveLength(1); expect(root.data[0]['labels']).toEqual(['G1', 'G2']); + const child = donutView(figure, hierarchy, 'G2'); + expect(child.data[0]['labels']).toEqual(['B', 'C']); expect(child.data[0]['values']).toEqual([3, 1]); + expect(child.data[0]['marker']).toEqual({ colors: ['blue', 'green'] }); + expect(child.data[1]['labels']).toEqual(['G1', 'G2']); expect(child.data[1]['values']).toEqual([6, 4]); + expect(child.data[1]['showlegend']).toBe(false); + expect(child.data[0]['showlegend']).toBe(false); + expect(child.data[0]['hovertemplate']).toContain('del grupo'); + expect(child.data[1]['hovertemplate']).toContain('del total de esta dona'); + expect(child.layout['annotations']).toEqual([expect.objectContaining({ text: '4' })]); + expect(donutView(figure, hierarchy)).toEqual(root); + expect(JSON.stringify({ figure, data })).toBe(snapshot); + }); + it.each(['suppressed', 'null', 'nan', 'negative', 'duplicate', 'missing', 'sum', 'period', 'stratum', 'metadata', 'order'])('fallback seguro: %s', kind => { + const { figure, data } = donutFixture(); + if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; + if (kind === 'null') data.filas[0]['n'] = null; + if (kind === 'nan') data.filas[0]['n'] = NaN; + if (kind === 'negative') data.filas[0]['n'] = -1; + if (kind === 'duplicate') data.filas.push({ ...data.filas[0] }); + if (kind === 'missing') data.filas.pop(); + if (kind === 'sum') figure.data[1]['values'] = [6, 5]; + if (kind === 'period') data.periodos = ['2026-S1']; + if (kind === 'stratum') data.filas[0]['estrato'] = 'otro'; + if (kind === 'metadata') data['categorias'] = {}; + if (kind === 'order') data.filas[0]['orden'] = null; + expect(donutHierarchy(figure, data)).toBeUndefined(); + }); + it.each(['frames', 'hidden', 'multi', 'static', 'unknown-array', 'mixed-periods', 'invisible', 'colors'])('no solicita datos para %s', kind => { + const { figure } = donutFixture(); + if (kind === 'unknown-array') figure.data[0]['customdata'] = [1, 2, 3]; + if (kind === 'mixed-periods') figure.data[1]['name'] = '2026-S1, grupos'; + if (kind === 'invisible') figure.data[1]['visible'] = 'legendonly'; + if (kind === 'colors') figure.data[0]['marker'] = { colors: ['red'] }; + if (kind === 'frames') figure.frames = [{ data: [] }]; + if (kind === 'hidden') figure.layout['hiddenlabels'] = ['A']; + if (kind === 'multi') figure.data.push({ ...figure.data[0] }); + if (kind === 'static') figure.config = { staticPlot: true }; + expect(donutPeriod(figure)).toBeUndefined(); + }); + it('descubre un ID futuro, siete categorías y cinco padres sin límites de presentación', () => { + const { figure, data } = donutFixture(); + data.id = 'future_catalog_item'; + const names = ['A', 'B', 'C', 'D', 'E', 'F', 'G']; + const parents = ['P1', 'P1', 'P2', 'P2', 'P3', 'P4', 'P5']; + data['categorias'] = Object.fromEntries(names.map((etiqueta, i) => [etiqueta, { etiqueta, grupo: parents[i] }])); + data['grupos_de_categoria'] = Object.fromEntries(parents.map(p => [p, p])); + data.filas = names.map((categoria, orden) => ({ ...data.filas[0], categoria, orden, n: orden + 1 })); + figure.data[0] = { ...figure.data[0], labels: names, values: [1,2,3,4,5,6,7], marker: { colors: names } }; + figure.data[1] = { ...figure.data[1], labels: ['P1','P2','P3','P4','P5'], values: [3,7,5,6,7], marker: {} }; + figure.layout['annotations'] = []; + const hierarchy = donutHierarchy(figure, data)!; + expect(hierarchy.parents).toHaveLength(5); + expect(donutView(figure, hierarchy, 'P2').data[0]['values']).toEqual([3, 4]); + }); + it('construye padres desde un solo anillo con una partición TOTAL explícita y conserva notas/ceros', () => { + const { figure, data } = donutFixture(); figure.data.pop(); + data.filas[2]['n'] = 0; figure.data[0]['values'] = [6, 3, 0]; + (figure.layout['annotations'] as Record[])[0]['text'] = '9'; + figure['notas'] = ['Nota recibida']; + const original = structuredClone(figure), hierarchy = donutHierarchy(figure, data)!; + expect(hierarchy.parentTrace).toBeUndefined(); + const root = donutView(figure, hierarchy); + expect(root.data[0]['values']).toEqual([6, 3]); + expect(root.data[0]['marker']).toEqual({ colors: ['red', 'blue'] }); + const expanded = donutView(figure, hierarchy, 'G2'); + expect(expanded.data[0]['values']).toEqual([3, 0]); + expect(expanded['notas']).toEqual(figure['notas']); expect(figure).toEqual(original); + }); + it('no reinterpreta un centro numérico que podría representar otro denominador', () => { + const { figure, data } = donutFixture(); + (figure.layout['annotations'] as Record[])[0]['text'] = '100'; + expect(donutHierarchy(figure, data)).toBeUndefined(); + }); + it('permite un solo padre y roles invertidos sin legendgroup/domino fijo ni sort obligatorio', () => { + const { figure, data } = donutFixture(); + data['categorias'] = { A: { etiqueta: 'A', grupo: 'g' }, B: { etiqueta: 'B', grupo: 'g' }, C: { etiqueta: 'C', grupo: 'g' } }; + data['grupos_de_categoria'] = { g: 'Un grupo' }; + figure.data[1] = { ...figure.data[1], labels: ['Un grupo'], values: [10], marker: {} }; + figure.data.reverse(); + for (const trace of figure.data) { delete trace['legendgroup']; delete trace['domain']; delete trace['sort']; } + const hierarchy = donutHierarchy(figure, data)!; + expect(hierarchy.parents).toEqual(['Un grupo']); expect(hierarchy.categoryTrace).toBe(1); + expect(donutView(figure, hierarchy, 'Un grupo').data[0]['values']).toEqual([6,3,1]); + }); + it.each(['no-hierarchy', 'overlap', 'partial', 'duplicate-parent-label', 'unsafe-total', 'independent'])('preserva la dona publicada sin inferencias: %s', reason => { + const { figure, data } = donutFixture(); figure.data.pop(); + if (reason === 'no-hierarchy') { data['categorias'] = { A: { etiqueta: 'A', grupo: null } }; data['grupos_de_categoria'] = {}; } + if (reason === 'overlap') data.filas.push({ ...data.filas[0], grupo: 'OTRA_POBLACION' }); + if (reason === 'partial') data.filas.pop(); + if (reason === 'duplicate-parent-label') data['grupos_de_categoria'] = { g1: 'Igual', g2: 'Igual' }; + if (reason === 'unsafe-total') { data.filas[0]['n'] = Number.MAX_SAFE_INTEGER; figure.data[0]['values'] = [Number.MAX_SAFE_INTEGER,3,1]; } + if (reason === 'independent') figure.data.push({ ...figure.data[0], labels: ['X','Y'], values: [6,4], marker: {} }); + expect(donutHierarchy(figure, data)).toBeUndefined(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-donut-drilldown.testing.ts b/src/app/features/indicadores/indicadores-donut-drilldown.testing.ts new file mode 100644 index 0000000..2efe154 --- /dev/null +++ b/src/app/features/indicadores/indicadores-donut-drilldown.testing.ts @@ -0,0 +1,18 @@ +import { IndicadorDatos, PlotlyFigure } from './indicadores.models'; + +// Synthetic counts and names; the shape mirrors the published two-ring contract. +export function donutFixture(): { figure: PlotlyFigure; data: IndicadorDatos } { + return { + figure: { data: [ + { type: 'pie', legendgroup: 'categorias', name: '2025-S2', labels: ['A', 'B', 'C'], values: [6, 3, 1], + hole: 0.62, sort: false, domain: { x: [0, 1], y: [0, 1] }, marker: { colors: ['red', 'blue', 'green'] } }, + { type: 'pie', legendgroup: 'grupos', name: '2025-S2, grupos', labels: ['G1', 'G2'], values: [6, 4], + hole: 0.55, sort: false, domain: { x: [0.19, 0.81], y: [0.19, 0.81] }, marker: { colors: ['gray', 'black'] } }, + ], layout: { annotations: [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false, text: '10' }] } }, + data: { id: 'i1', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'], + categorias: { A: { etiqueta: 'A', grupo: 'g1' }, B: { etiqueta: 'B', grupo: 'g2' }, C: { etiqueta: 'C', grupo: 'g2' } }, + grupos_de_categoria: { g1: 'G1', g2: 'G2' }, + filas: ['A', 'B', 'C'].map((categoria, orden) => ({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, + categoria, orden, n: [6, 3, 1][orden], suprimido: 0 })) }, + }; +} diff --git a/src/app/features/indicadores/indicadores-donut-drilldown.ts b/src/app/features/indicadores/indicadores-donut-drilldown.ts new file mode 100644 index 0000000..794208e --- /dev/null +++ b/src/app/features/indicadores/indicadores-donut-drilldown.ts @@ -0,0 +1,170 @@ +import { IndicadorDatos, PlotlyFigure } from './indicadores.models'; + +export interface DonutHierarchy { + parents: readonly string[]; + children: readonly { label: string; parent: string; value: number }[]; + categoryTrace: number; + parentTrace?: number; +} +export interface DonutSelection { parent?: string; category?: string; } +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function plainLabel(value: unknown): value is string { + return typeof value === 'string' && !!value.trim() && !/[<>]/.test(value); +} +function labels(trace: Record): trace is Record & { labels: string[]; values: number[] } { + return Array.isArray(trace['labels']) && trace['labels'].length > 0 + && trace['labels'].every(plainLabel) && new Set(trace['labels']).size === trace['labels'].length + && Array.isArray(trace['values']) && trace['values'].length === trace['labels'].length + && trace['values'].every(v => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0); +} +// Reject point-wise attributes whose correspondence cannot be preserved on a +// subset. Scalars and unknown scalar attributes survive on the derived copy. +function safeArrays(value: Record, path = ''): boolean { + return Object.entries(value).every(([key, item]) => { + const field = path + key; + return Array.isArray(item) ? ['labels', 'values', 'marker.colors', 'domain.x', 'domain.y'].includes(field) + : !record(item) || safeArrays(item, field + '.'); + }); +} +function centerCount(value: unknown): value is Record & { text: string } { + return centerCountAt(value, 0.5, 0.5); +} +function centerCountAt(value: unknown, x: number, y: number): value is Record & { text: string } { + return record(value) && value['x'] === x && value['y'] === y + && value['xref'] === 'paper' && value['yref'] === 'paper' && value['showarrow'] === false + && typeof value['text'] === 'string' && /^\d+<\/b>$/.test(value['text']); +} + +// Only a structural candidate: /datos supplies the semantics. No indicator ID, +// category count, legendgroup, trace order or exact domain decides eligibility. +// C2 metadata describes category -> parent, not further levels or facets. +export function donutPeriod(figure: PlotlyFigure): string | undefined { + if (figure.frames?.length || !figure.data.length || figure.data.length > 2 || figure.config?.['staticPlot'] === true + || ['updatemenus', 'sliders'].some(k => figure.layout[k] !== undefined) + || (Array.isArray(figure.layout['hiddenlabels']) && figure.layout['hiddenlabels'].length)) return; + const periods = new Set(); + for (const trace of figure.data) { + if (trace['type'] !== 'pie' || !labels(trace) || trace['visible'] === false || trace['visible'] === 'legendonly' + || typeof trace['hole'] !== 'number' || trace['hole'] <= 0 || trace['hole'] >= 1 || !safeArrays(trace) + || (record(trace['marker']) && Array.isArray(trace['marker']['colors']) + && trace['marker']['colors'].length !== trace.labels.length)) return; + const match = typeof trace['name'] === 'string' && /^(\d{4}-(?:S[12]|0[1-9]|1[0-2]))(?:$|, )/.exec(trace['name']); + if (!match) return; + periods.add(match[1]); + } + return periods.size === 1 ? [...periods][0] : undefined; +} + +export function donutHierarchy(figure: PlotlyFigure, data: IndicadorDatos): DonutHierarchy | undefined { + const period = donutPeriod(figure); + if (!period || data.contrato !== 'C2' || data.periodos.length !== 1 || data.periodos[0] !== period + || data.tipo_periodo !== (period.includes('-S') ? 'semestre' : 'mes') + || !record(data['categorias']) || !record(data['grupos_de_categoria']) + || !data.filas.length || data.filas.some(r => r['periodo'] !== period || r['grupo'] !== 'TOTAL' + || r['estrato'] != null || r['suprimido'] !== 0 || typeof r['n'] !== 'number' + || !Number.isSafeInteger(r['n']) || r['n'] < 0 || typeof r['orden'] !== 'number' || !Number.isFinite(r['orden']))) return; + const categories = data['categorias'], groups = data['grupos_de_categoria']; + const children: { label: string; parent: string; value: number }[] = []; + const ids = new Set(); + for (const row of data.filas) { + const id = row['categoria']; + if (typeof id !== 'string' || ids.has(id) || !Object.hasOwn(categories, id)) return; + ids.add(id); + const category = categories[id]; + if (!record(category) || !plainLabel(category['etiqueta']) || typeof category['grupo'] !== 'string' + || !Object.hasOwn(groups, category['grupo'])) return; + const parent = groups[category['grupo']]; + if (!plainLabel(parent)) return; + children.push({ label: category['etiqueta'], parent, value: row['n'] as number }); + } + // Every category must be explicit, including published zeros. A complete + // TOTAL partition is required; never aggregate overlapping row populations. + if (Object.keys(categories).length !== children.length + || new Set(children.map(c => c.label)).size !== children.length + || !Number.isSafeInteger(children.reduce((sum, c) => sum + c.value, 0)) + || children.every(c => c.value === 0)) return; + // A numeric center may be another denominator. Only adapt it when it also + // agrees with the verified partition; otherwise retain the published figure. + const annotations = figure.layout['annotations']; + const total = children.reduce((sum, c) => sum + c.value, 0); + if (Array.isArray(annotations) && annotations.some(a => centerCount(a) + && Number(a.text.slice(3, -4)) !== total)) return; + const groupIds = new Set(Object.values(categories).map(c => record(c) ? c['grupo'] : undefined)); + const groupNames = [...groupIds].map(id => groups[id as string]); + if (new Set(groupNames).size !== groupNames.length) return; + // Verify labels AND counts; never infer hierarchy from colors or equal sums. + const matches = figure.data.flatMap((t, index) => labels(t) && t.labels.length === children.length + && children.every(c => t.values[t.labels.indexOf(c.label)] === c.value) ? [index] : []); + if (matches.length !== 1) return; + const categoryTrace = matches[0], outer = figure.data[categoryTrace]; + if (!labels(outer)) return; + const ordered = outer.labels.map(label => children.find(c => c.label === label)!); + const parents = [...new Set(ordered.map(c => c.parent))]; + const parentTrace = figure.data.length === 2 ? 1 - categoryTrace : undefined; + if (parentTrace !== undefined) { + const inner = figure.data[parentTrace]; + if (!labels(inner) || inner.labels.length !== parents.length + || inner.labels.some((p, i) => !parents.includes(p) + || children.filter(c => c.parent === p).reduce((n, c) => n + c.value, 0) !== inner.values[i])) return; + return { parents: [...inner.labels], children: ordered, categoryTrace, parentTrace }; + } + return { parents, children: ordered, categoryTrace }; +} + +// Each view starts from the current presentation of the original HTTP figure. +// The inner ring retains ALL parents so another can be selected directly. Its +// denominator is the full verified partition; the outer ring is within-parent. +export function donutView(source: PlotlyFigure, hierarchy: DonutHierarchy, parent?: string, _availableWidth?: number): PlotlyFigure { + const figure = structuredClone(source); + const meta = figure.layout['meta']; + const unit = record(meta) && typeof meta['unit'] === 'string' && !/[<>&]/.test(meta['unit']) ? ' ' + meta['unit'] : ''; + const outer = figure.data[hierarchy.categoryTrace]; + if (!outer || !labels(outer)) return figure; + const marker = record(outer['marker']) ? outer['marker'] : {}; + const colors = marker['colors']; + const publishedParent = hierarchy.parentTrace === undefined ? undefined : figure.data[hierarchy.parentTrace]; + const inner: Record = publishedParent ?? { + ...outer, labels: [...hierarchy.parents], + values: hierarchy.parents.map(p => hierarchy.children.filter(c => c.parent === p).reduce((sum, c) => sum + c.value, 0)), + // Reuse received category colors; no new institutional palette. + marker: { ...marker, ...(Array.isArray(colors) + ? { colors: hierarchy.parents.map(p => colors[hierarchy.children.findIndex(c => c.parent === p)]) } : {}) }, + }; + // HTML owns the independent, bounded legend. Plotly gets the same full area + // in every state, including on narrow cards; it cannot move the circle. + const plotDomain = { x: [0, 1], y: [0, 1] }; + const center = { + x: (plotDomain.x[0] + plotDomain.x[1]) / 2, + y: (plotDomain.y[0] + plotDomain.y[1]) / 2, + }; + figure.layout['showlegend'] = false; + figure.layout['height'] = 440; + figure.layout['margin'] = { ...(record(figure.layout['margin']) ? figure.layout['margin'] : {}), + l: 16, r: 16, t: 16, b: 16, pad: 0, autoexpand: false }; + const annotations = figure.layout['annotations']; + if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a) + ? { ...a, x: center.x, y: center.y, xanchor: 'center', yanchor: 'middle' } : a); + const parentView = { ...inner, domain: plotDomain, hole: 0.55, sort: false, textinfo: 'none', showlegend: false, + legendgroup: 'grupos', legendgrouptitle: { text: 'Grupos' }, + hovertemplate: '%{label}
%{value}' + unit + ' (%{percent} del total de esta dona)' }; + if (!parent || !hierarchy.parents.includes(parent)) { + figure.data = [parentView]; + return figure; + } + const indices = outer.labels.flatMap((label, i) => hierarchy.children.some(c => c.label === label && c.parent === parent) ? [i] : []); + const value = indices.reduce((sum, i) => sum + outer.values[i], 0); + figure.data = [ + { ...outer, labels: indices.map(i => outer.labels[i]), values: indices.map(i => outer.values[i]), + domain: plotDomain, hole: 0.70, sort: false, showlegend: false, textinfo: 'none', legendgroup: 'categorias', + legendgrouptitle: { text: 'Categorías de ' + parent }, + marker: { ...marker, ...(Array.isArray(colors) ? { colors: indices.map(i => colors[i]) } : {}) }, + hovertemplate: '%{label}
%{value}' + unit + ' (%{percent} del grupo)' }, + { ...parentView, domain: { x: [0.17, 0.83], y: [0.17, 0.83] } }, + ]; + const finalAnnotations = figure.layout['annotations']; + if (Array.isArray(finalAnnotations)) figure.layout['annotations'] = finalAnnotations.map(a => centerCountAt(a, center.x, center.y) + ? { ...a, x: center.x, y: center.y, xanchor: 'center', yanchor: 'middle', text: '' + value + '' } : a); + return figure; +} diff --git a/src/app/features/indicadores/indicadores-dual-figures.ts b/src/app/features/indicadores/indicadores-dual-figures.ts new file mode 100644 index 0000000..1a2a0fe --- /dev/null +++ b/src/app/features/indicadores/indicadores-dual-figures.ts @@ -0,0 +1,7 @@ +import { Indicador } from './indicadores.models'; + +// Representation IDs are the published capability contract, never indicator IDs. +export function dualFigures(item: Indicador): readonly string[] { + return item.contrato === 'C2' && ['fig_c2_donas', 'fig_c2_barras'].every(id => item.figuras.includes(id)) + ? ['fig_c2_donas', 'fig_c2_barras'] : []; +} diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts index ff3e0bf..9750138 100644 --- a/src/app/features/indicadores/indicadores-global-filters.spec.ts +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -47,9 +47,9 @@ describe('D.2 integración de autoridad global y consumidores', () => { http.expectOne('/tea/indicadores').flush([]); page.changeDominio('cacu'); load(undefined, 'cacu'); open(); respond(); const applied = page.filters!.applied, before = panels()[0].result(); - expect(page.initialKpiPresentation).toBe(true); + expect(page.initialPeriodState()).toBe('ready'); apply(); - expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); + expect(page.initialPeriodBlocked).toBe(false); expect(page.filters!.applied).toBe(applied); expect(applied.revision).toBe(0); expect(panels()[0].result()).toBe(before); http.expectNone(() => true); }); @@ -57,12 +57,12 @@ describe('D.2 integración de autoridad global y consumidores', () => { if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } load(undefined, domain); expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); - const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; + const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf; expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]); - expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(3); - expect(sections[2].getAttribute('aria-labelledby')).toBe('graphic-section-title'); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0); + expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title'); expect(page.filters!.applied.selection.mode).toBe('todos'); - expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); + expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true); }); it('edición y vacío no consultan ni cambian el resultado vigente', () => { diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts new file mode 100644 index 0000000..7652d05 --- /dev/null +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -0,0 +1,223 @@ +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 { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { pending } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => { + let fixture: ReturnType>, http: HttpTestingController, page: IndicadoresPage; + const periods = ['2026-S2', '2026-S1', '2025-S2']; + const definitions = KPI_BY_DOMAIN[domain]; + const otherDomain = domain === 'cacu' ? 'cama' : 'cacu'; + const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })), + { id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }]; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + http = TestBed.inject(HttpTestingController); + if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } + http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); + const inventory = http.match(r => r.url.endsWith('/periodos')); + expect(inventory).toHaveLength(4); // The anchor search shares the catalog inventory request. + inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) })); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + function data(index: number, period: string, value = 7) { + const d = definitions[index]; + return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: [period], categorias: { A: {} }, filas: [{ + periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0, + valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] }; + } + function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } + function flushPanels(period: string, expected = 2) { + const requests = http.match(r => r.url.endsWith('/datos')); + expect(requests).toHaveLength(expected); + requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); + const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); }); + fixture.detectChanges(); + } + function choose() { + request(periods[0]).flush(data(0, periods[0], 0)); request(periods[1]).flush(data(0, periods[1])); + fixture.detectChanges(); flushPanels(periods[1]); + } + function flushFigures(period: string, expected: number) { + const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(expected); + requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); r.flush({ data: [], layout: {} }); }); fixture.detectChanges(); + } + it('alternar secciones conserva búsqueda inicial en curso y aplica una sola autoridad temporal', () => { + const ongoing = request(periods[0]); + for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { + page.changeSection(section); fixture.detectChanges(); + for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); + expect(page.initialPeriodState()).toBe('loading'); + expect(ongoing.cancelled).toBe(false); + http.expectNone(() => true); + } + ongoing.flush(data(0, periods[0])); fixture.detectChanges(); flushPanels(periods[0]); + expect(page.activeSection()).toBe('datos'); + const applied = page.filters!.applied; + page.changeSection('resumen'); fixture.detectChanges(); + expect(page.filters!.applied).toBe(applied); + expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); + http.expectNone(() => true); + }); + it('pestañas conservan periodo inicial resuelto, borrador, fijación y representación sin solicitudes', () => { + choose(); const applied = page.filters!.applied, state = page.filters; + const before = cards(); page.togglePinned(items[1] as Indicador); fixture.detectChanges(); + const card = before[0]; card.selectFigure('g'); fixture.detectChanges(); + editor().select([periods[2]]); fixture.detectChanges(); + for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { + page.changeSection(section); fixture.detectChanges(); + for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); + expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); + expect(editor().selectedPeriods).toEqual([periods[2]]); + expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g'); + expect(page.isPinned(items[1] as Indicador)).toBe(true); + expect(page.initialPeriodState()).toBe('ready'); http.expectNone(() => true); + } + }); + it('espera sin KPI/figuras de Todos y sincroniza los tres KPI, borrador y aplicado', () => { + expect(page.initialPeriodBlocked).toBe(true); expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0); + http.expectNone(r => r.url.includes('/figuras/')); choose(); + expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[1]] }); + expect(page.filters!.editors.semestre!.draft).toEqual(page.filters!.applied.selection); + expect(pending(page.filters!)).toBe(false); expect(editor().selectedPeriods).toEqual([periods[1]]); + expect(panels()).toHaveLength(3); + expect(panels().every(p => p.applied === page.filters!.applied && !p.initialPresentation && p.temporalReference === periods[1])).toBe(true); + expect(panels()[0].result().value).toBe(7); http.expectNone(() => true); + }); + it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => { + choose(); http.expectNone(r => r.url.includes('/figuras/')); + cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); }); + fixture.detectChanges(); flushFigures(periods[1], items.length); http.expectNone(() => true); + }); + it('KPI secundarios sin datos no retroceden a otro periodo', () => { + request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); + const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(2); + requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); }); + fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true); + }); + it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => { + choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true); + page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3); + expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] }); + editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]); + expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true); + }); + it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => { + choose(); const applied = page.filters!.applied; + page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true); + cards()[0].setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1); + cards()[0].selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1); + expect(cards()[0].selectedFigure).toBe('g'); http.expectNone(() => true); + expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready'); + }); + it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => { + choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3); + page.changeDominio(otherDomain); http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges(); + page.changeDominio('tea'); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } + http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); + expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] }); + expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true); + }); + it('cambio de dominio durante búsqueda cancela y no aplica respuestas viejas', () => { + const old = request(periods[0]); page.changeDominio(otherDomain); fixture.detectChanges(); expect(old.cancelled).toBe(true); + http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges(); expect(page.filters).toBeUndefined(); http.expectNone(() => true); + }); + it('Aplicar Todos durante búsqueda cancela y respeta la decisión manual', () => { + const old = request(periods[0]); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); + page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], 3); + expect(page.filters!.applied.selection.mode).toBe('todos'); expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true); + }); + it('error HTTP queda visible, sin datos mezclados, con reintento funcional', () => { + request(periods[0]).flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(page.initialPeriodState()).toBe('error'); expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); + expect(fixture.nativeElement.textContent).not.toContain('private'); page.retryInitialPeriod(); + request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); flushPanels(periods[0]); + expect(page.initialPeriodState()).toBe('ready'); http.expectNone(() => true); + }); + it('sin positivo comunica ausencia y espera selección manual sin aplicar un periodo incorrecto', () => { + periods.forEach(p => request(p).flush(data(0, p, 0))); fixture.detectChanges(); + expect(page.initialPeriodState()).toBe('empty'); expect(page.filters!.applied.selection.mode).toBe('todos'); + expect(fixture.nativeElement.textContent).toContain('No se encontró un periodo'); + expect(page.initialPeriodBlocked).toBe(true); expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); + http.expectNone(() => true); + page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]); + expect(panels()[0].result().value).toBe(0); expect(panels().every(p => !p.initialPresentation)).toBe(true); + expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true); + }); + it('editar interrumpe la búsqueda sin consultar ni sobrescribir el borrador antes de Aplicar', () => { + const old = request(periods[0]); editor().select([periods[2]]); fixture.detectChanges(); + expect(old.cancelled).toBe(true); expect(page.initialPeriodState()).toBe('manual'); + expect(page.filters!.applied.selection.mode).toBe('todos'); + expect(editor().selectedPeriods).toEqual([periods[2]]); expect(panels()).toHaveLength(0); http.expectNone(() => true); + page.retryCatalog(); http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); + expect(editor().selectedPeriods).toEqual([periods[2]]); expect(page.initialPeriodState()).toBe('manual'); http.expectNone(() => true); + page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3); + expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true); + }); + it('un ancla retirada del catálogo requiere selección manual y no consulta datos retirados', () => { + const old = request(periods[0]); page.retryCatalog(); expect(old.cancelled).toBe(true); + http.expectOne('/' + domain + '/indicadores').flush(items.filter(item => item.id !== definitions[0].id)); fixture.detectChanges(); + expect(page.initialPeriodState()).toBe('unavailable'); + expect(page.kpiIndicator(definitions[0].id)).toBeUndefined(); + expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); + editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges(); + http.match(r => r.url.endsWith('/datos')).forEach(r => { + const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); + expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0])); + }); fixture.detectChanges(); + expect(panels()).toHaveLength(2); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true); + }); + it('inicializa y restaura los tres dominios con periodos propios sin repetir datos resueltos', () => { + choose(); + const own = new Map([[domain, periods[1]]]); + const catalogs = new Map([[domain, items]]); + for (const target of ['tea', 'cacu', 'cama'] as const) { + if (target === domain) continue; + const definitions = KPI_BY_DOMAIN[target]; + const period = own.size === 1 ? '2024-S2' : '2025-S1'; + own.set(target, period); + const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] })); + catalogs.set(target, catalog); + page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges(); + http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] })); + const payload = (index: number) => { + const value = data(index, period); value.id = definitions[index].id; + value.filas[0].grupo = index === 1 && target !== 'tea' ? 'total' : 'TOTAL'; return value; + }; + http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges(); + http.match(r => r.url.endsWith('/datos')).forEach(r => { + const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index)); + }); fixture.detectChanges(); + expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] }); + } + for (const target of ['tea', 'cacu', 'cama'] as const) { + if (page.dominio !== target) { + page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalogs.get(target)!); fixture.detectChanges(); + } + expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [own.get(target)] }); + expect(panels().every(p => p.temporalReference === own.get(target))).toBe(true); + http.expectNone(() => true); + } + }); +}); diff --git a/src/app/features/indicadores/indicadores-initial-period.spec.ts b/src/app/features/indicadores/indicadores-initial-period.spec.ts new file mode 100644 index 0000000..d27810c --- /dev/null +++ b/src/app/features/indicadores/indicadores-initial-period.spec.ts @@ -0,0 +1,98 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresInitialPeriod } from './indicadores-initial-period'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { AvailablePeriod } from './indicadores-periodos'; +import { TipoPeriodo } from './indicadores.models'; + +describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', domain => { + let service: IndicadoresInitialPeriod, http: HttpTestingController; + const anchor = KPI_BY_DOMAIN[domain][0]; + const periods = ['2026-S2', '2026-S1', '2025-S2']; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresInitialPeriod); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + function data(period: string, kind = 'positive') { + const categories = domain === 'cama' ? ['B4A', 'B4B', 'B4C', 'B5', 'B6', 'SIN_DATO'] : ['A']; + return { id: anchor.id, contrato: 'C2', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], + categorias: Object.fromEntries([...categories, ...(kind === 'incomplete' ? ['MISSING'] : [])].map(c => [c, {}])), + filas: kind === 'empty' ? [] : categories.map((categoria, i) => ({ periodo: period, + grupo: kind === 'group' ? 'OTHER' : 'TOTAL', categoria, estrato: kind === 'stratum' ? 'sintetico' : null, + suprimido: kind === 'suppressed' ? 1 : 0, n: kind === 'null' ? null : kind === 'zero' || i > 0 ? 0 : 9 })) }; + } + function inventory(values = [...periods].reverse()) { + http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush({ id: anchor.id, + periodos: values.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) }); + } + function request(period: string) { return http.expectOne(r => r.url === `/${domain}/indicadores/${anchor.id}/datos` && r.params.get('periodos') === period); } + function start(tipo: TipoPeriodo = 'semestre') { + let selected: AvailablePeriod | undefined, completed = false, failed = false; + const subscription = service.find(domain, anchor, tipo).subscribe({ next: result => { selected = result; completed = true; }, error: () => { failed = true; } }); + return { selected: () => selected, completed: () => completed, failed: () => failed, subscription }; + } + it('elige el positivo más reciente, reutiliza la respuesta y no consulta periodos anteriores', () => { + const run = start(); inventory(); request(periods[0]).flush(data(periods[0])); + expect(run.selected()).toEqual({ periodo: periods[0], tipo: 'semestre' }); http.expectNone(() => true); + const cached = start(); expect(cached.selected()).toEqual(run.selected()); http.expectNone(() => true); + }); + it.each(['zero', 'null', 'suppressed', 'incomplete', 'empty', 'group', 'stratum'])('omite %s sin convertirlo en cero y se detiene en el primer positivo', kind => { + const run = start(); inventory(); const first = request(periods[0]); http.expectNone(() => true); + first.flush(data(periods[0], kind)); expect(run.completed()).toBe(false); + request(periods[1]).flush(data(periods[1], 'zero')); request(periods[2]).flush(data(periods[2])); + expect(run.selected()?.periodo).toBe(periods[2]); http.expectNone(() => true); + }); + it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => { + if (domain === 'cama') { + expect(anchor.id).toBe('cama_birads_456_paciente'); + expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6'); + expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico']); + } else expect(anchor.id).toBe('cacu_eu7'); + const run = start(); inventory(); request(periods[0]).flush(data(periods[0])); + expect(run.selected()?.periodo).toBe(periods[0]); + http.expectNone(r => r.url.includes('/cama_birads/')); + }); + it('ningún positivo termina sin seleccionar un periodo arbitrario', () => { + const run = start(); inventory(); + [periods[0], periods[1], periods[2]].forEach((p, i) => request(p).flush(data(p, ['suppressed', 'null', 'incomplete'][i]))); + expect(run.completed()).toBe(true); expect(run.selected()).toBeUndefined(); http.expectNone(() => true); + }); + it('inventario vacío es ausencia conocida sin consultas de datos', () => { + const run = start(); inventory([]); expect(run.completed()).toBe(true); + expect(run.selected()).toBeUndefined(); expect(run.failed()).toBe(false); http.expectNone(() => true); + }); + it.each([404, 503])('HTTP %s durante datos interrumpe, no salta al pasado y puede reintentarse', status => { + const run = start(); inventory(); request(periods[0]).flush(data(periods[0], 'zero')); + request(periods[1]).flush({ error: 'private' }, { status, statusText: 'Failure' }); + expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true); + const retry = start(); request(periods[1]).flush(data(periods[1])); + expect(retry.selected()?.periodo).toBe(periods[1]); http.expectNone(() => true); + }); + it('HTTP 404 del inventario es indeterminado, no ausencia conocida ni cero', () => { + const run = start(); http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush('', { status: 404, statusText: 'Missing' }); + expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true); + }); + it.each(['semestre', 'mes'] as const)('busca únicamente la granularidad activa %s, sin mezclar tipos ni usar un mes más reciente', tipo => { + const run = start(tipo); inventory(['2026-12', '2025-10', '2026-S1', '2025-S2']); + const expected = tipo === 'mes' ? '2026-12' : '2026-S1'; request(expected).flush(data(expected)); + expect(run.selected()).toEqual({ periodo: expected, tipo }); http.expectNone(() => true); + }); + it('si solo hay meses no los usa para inicializar semestre', () => { + const run = start(); inventory(['2026-12']); expect(run.completed()).toBe(true); + expect(run.selected()).toBeUndefined(); http.expectNone(() => true); + }); + it('cancelación descarta el recorrido y no retiene datos no resueltos', () => { + const run = start(); inventory(); const old = request(periods[0]); run.subscription.unsubscribe(); + expect(old.cancelled).toBe(true); expect(() => old.flush(data(periods[0]))).toThrow(); + const retry = start(); request(periods[0]).flush(data(periods[0])); expect(retry.selected()?.periodo).toBe(periods[0]); + }); +}); + +it('el mecanismo rechaza como ancla una definición ajena a C2', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + let failed = false; + TestBed.inject(IndicadoresInitialPeriod).find('cacu', KPI_BY_DOMAIN.cacu[1], 'semestre').subscribe({ error: () => { failed = true; } }); + expect(failed).toBe(true); TestBed.inject(HttpTestingController).expectNone(() => true); +}); diff --git a/src/app/features/indicadores/indicadores-initial-period.ts b/src/app/features/indicadores/indicadores-initial-period.ts new file mode 100644 index 0000000..83eaf16 --- /dev/null +++ b/src/app/features/indicadores/indicadores-initial-period.ts @@ -0,0 +1,32 @@ +import { inject, Injectable } from '@angular/core'; +import { Observable, of, switchMap, throwError } from 'rxjs'; +import { KpiDefinition, kpiResult } from './indicadores-kpi'; +import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; +import { AvailablePeriod, IndicadoresPeriodos } from './indicadores-periodos'; +import { Dominio, TipoPeriodo } from './indicadores.models'; + +@Injectable({ providedIn: 'root' }) +export class IndicadoresInitialPeriod { + private readonly periods = inject(IndicadoresPeriodos); + private readonly queries = inject(IndicadoresKpiQueries); + + find(domain: Dominio, definition: KpiDefinition, tipo: TipoPeriodo, version?: string): Observable { + if (definition.contrato !== 'C2') return throwError(() => new Error('El indicador ancla debe publicar C2')); + return this.periods.periodos(domain, definition.id).pipe(switchMap(available => { + // Inventories are already validated, deduplicated and sorted newest first. + const candidates = available.filter(period => period.tipo === tipo); + const search = (index: number): Observable => { + const candidate = candidates[index]; + if (!candidate) return of(undefined); + return this.queries.datos(domain, definition.id, candidate.tipo, candidate.periodo, version).pipe(switchMap(data => { + const result = kpiResult(data, definition, domain, { tipo: candidate.tipo, + selection: { mode: 'explicit', periodos: [candidate.periodo] }, revision: 0 }); + return result.state === 'Disponible' && typeof result.value === 'number' && result.value > 0 + ? of(candidate) : search(index + 1); + })); + }; + // HTTP failures propagate; neither they nor invalid/suppressed C2 imply zero. + return search(0); + })); + } +} diff --git a/src/app/features/indicadores/indicadores-initial-search.spec.ts b/src/app/features/indicadores/indicadores-initial-search.spec.ts new file mode 100644 index 0000000..e501c0a --- /dev/null +++ b/src/app/features/indicadores/indicadores-initial-search.spec.ts @@ -0,0 +1,76 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresInitialPeriod } from './indicadores-initial-period'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { AvailablePeriod } from './indicadores-periodos'; + +const id = KPI_BY_DOMAIN.tea[0].id; +const periods = ['2026-S2', '2026-S1', '2025-S2']; +function teaData(period: string, kind = 'positive', value = 7) { + return { id, contrato: 'C2', tipo_periodo: 'semestre', periodos: [period], + categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} }, + filas: [{ periodo: period, grupo: kind === 'group' ? 'OTHER' : 'TOTAL', estrato: null, + categoria: 'A', n: kind === 'null' ? null : kind === 'zero' ? 0 : value, + suprimido: kind === 'suppressed' ? 1 : 0 }] }; +} +describe('TEA-P0 búsqueda compartida con pacientes', () => { + let http: HttpTestingController; + let service: IndicadoresInitialPeriod; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresInitialPeriod); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + function start() { + let selected: AvailablePeriod | undefined; + let completed = false, failed = false; + const subscription = service.find('tea', KPI_BY_DOMAIN.tea[0], 'semestre').subscribe({ next: value => { selected = value; completed = true; }, error: () => { failed = true; } }); + http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, + periodos: [periods[2], periods[0], periods[1]].map(periodo => ({ periodo, tipo: 'semestre' })) }); + return { subscription, selected: () => selected, completed: () => completed, failed: () => failed }; + } + function request(period: string) { return http.expectOne(r => r.url.endsWith('/datos') && r.params.get('periodos') === period); } + it('elige el más reciente positivo y detiene la búsqueda', () => { + const run = start(); request(periods[0]).flush(teaData(periods[0])); + expect(run.selected()).toEqual({ periodo: periods[0], tipo: 'semestre' }); http.expectNone(() => true); + }); + it.each(['zero', 'null', 'suppressed', 'incomplete', 'group'])('omite %s sin convertirlo en un total válido', kind => { + const run = start(); request(periods[0]).flush(teaData(periods[0], kind)); + expect(run.completed()).toBe(false); request(periods[1]).flush(teaData(periods[1])); + expect(run.selected()?.periodo).toBe(periods[1]); http.expectNone(() => true); + }); + it('recorre varios ceros secuencialmente sin consultas paralelas', () => { + const run = start(); const first = request(periods[0]); http.expectNone(() => true); + first.flush(teaData(periods[0], 'zero')); const second = request(periods[1]); http.expectNone(() => true); + second.flush(teaData(periods[1], 'zero')); request(periods[2]).flush(teaData(periods[2])); + expect(run.selected()?.periodo).toBe(periods[2]); + }); + it('ningún candidato termina sin periodo ni valor inventado', () => { + const run = start(); periods.forEach(p => request(p).flush(teaData(p, 'zero'))); + expect(run.completed()).toBe(true); expect(run.selected()).toBeUndefined(); http.expectNone(() => true); + }); + it.each([404, 503])('HTTP %s detiene como error y permite reintento usando éxitos en caché', status => { + const run = start(); request(periods[0]).flush(teaData(periods[0], 'zero')); + request(periods[1]).flush('private', { status, statusText: 'Failure' }); + expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true); + let selected: AvailablePeriod | undefined; + service.find('tea', KPI_BY_DOMAIN.tea[0], 'semestre').subscribe(value => { selected = value; }); + request(periods[1]).flush(teaData(periods[1])); expect(selected?.periodo).toBe(periods[1]); http.expectNone(() => true); + }); + it('error de inventario se propaga y reintenta sin fabricar cero', () => { + let failed = false; + service.find('tea', KPI_BY_DOMAIN.tea[0], 'semestre').subscribe({ error: () => { failed = true; } }); + http.expectOne(`/tea/indicadores/${id}/periodos`).flush('', { status: 503, statusText: 'Failure' }); + expect(failed).toBe(true); + let completed = false; + service.find('tea', KPI_BY_DOMAIN.tea[0], 'semestre').subscribe(() => { completed = true; }); + http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [] }); + expect(completed).toBe(true); http.expectNone(() => true); + }); + it('cancelar retira el HTTP en curso e impide respuestas obsoletas', () => { + const run = start(); const old = request(periods[0]); run.subscription.unsubscribe(); + expect(old.cancelled).toBe(true); expect(run.completed()).toBe(false); + expect(() => old.flush(teaData(periods[0]))).toThrow(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-kpi-queries.ts b/src/app/features/indicadores/indicadores-kpi-queries.ts index e173597..2d84ef7 100644 --- a/src/app/features/indicadores/indicadores-kpi-queries.ts +++ b/src/app/features/indicadores/indicadores-kpi-queries.ts @@ -1,23 +1,11 @@ import { inject, Injectable } from '@angular/core'; -import { Observable, shareReplay } from 'rxjs'; -import { Dominio, IndicadorDatos, TipoPeriodo } from './indicadores.models'; -import { IndicadoresService } from './indicadores.service'; -import { IndicadoresRequests } from './indicadores-requests'; +import { Dominio, TipoPeriodo } from './indicadores.models'; +import { IndicadoresSnapshots } from './indicadores-snapshots'; @Injectable({ providedIn: 'root' }) export class IndicadoresKpiQueries { - private readonly service = inject(IndicadoresService); - private readonly requests = inject(IndicadoresRequests); - // Only resolved KPI payloads survive navigation. Errors and cancelled requests reset. - private readonly cache = new Map>(); - datos(domain: Dominio, id: string, tipo: TipoPeriodo, period: string) { - const key = JSON.stringify([domain, id, tipo, period]); - let request = this.cache.get(key); - if (!request) { - request = this.requests.run(() => this.service.datos(domain, id, tipo, [period])).pipe( - shareReplay({ bufferSize: 1, refCount: true })); - this.cache.set(key, request); - } - return request; + private readonly snapshots = inject(IndicadoresSnapshots); + datos(domain: Dominio, id: string, tipo: TipoPeriodo, period: string, version?: string) { + return this.snapshots.datos(domain, id, tipo, [period], version); } } diff --git a/src/app/features/indicadores/indicadores-methodology.ts b/src/app/features/indicadores/indicadores-methodology.ts new file mode 100644 index 0000000..98651e9 --- /dev/null +++ b/src/app/features/indicadores/indicadores-methodology.ts @@ -0,0 +1,38 @@ +import { Dominio } from './indicadores.models'; + +// Existing WebApp explanations, shared by figures and the definitions section. +// These are editorial guidance, not additional metadata supplied by WebApi. +const CONTRACT_INTERPRETATIONS: Readonly> = { + C1: [ + 'El punto representa la proporción observada.', + 'Cuando la figura publica intervalos Wilson al 95 %, la línea vertical representa ese intervalo. No se infieren intervalos cuando faltan.', + 'Los intervalos amplios pueden deberse a denominadores pequeños.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ], + C3r: [ + 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', + 'Los límites de dibujo no representan necesariamente extremos observados.', + 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', + ], +}; +export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.'; + +export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] { + if (contract === 'C2') return [ + pie + ? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.' + : 'Las barras muestran conteos por categoría; los porcentajes publicados pueden aparecer como etiquetas. Consulta la unidad y el denominador de cada representación.', + 'Las categorías corresponden a la distribución de cada grupo y periodo.', + 'SIN_DATO, cuando aparece, es una categoría legítima de la representación.', + 'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.', + ]; + if (contract === 'C1' && domain !== 'tea') return [ + 'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.', + 'Cuando la figura publica intervalos Wilson al 95 %, la línea vertical representa ese intervalo. No se infieren intervalos cuando faltan.', + 'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.', + 'Un porcentaje observado del 100 % no implica certeza poblacional.', + ]; + return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) + ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] + : ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.']; +} diff --git a/src/app/features/indicadores/indicadores-numeric-rows.ts b/src/app/features/indicadores/indicadores-numeric-rows.ts new file mode 100644 index 0000000..94cfd39 --- /dev/null +++ b/src/app/features/indicadores/indicadores-numeric-rows.ts @@ -0,0 +1,50 @@ +import { IndicadorDatos } from './indicadores.models'; + +export interface NumericRow { period: string; group: string; category: string; value: string; detail: string; state: string; } +const record = (value: unknown): value is Record => value !== null && typeof value === 'object' && !Array.isArray(value); +function number(value: unknown, suffix = ''): string { + if (value === null) return 'Sin valor (nulo)'; + return typeof value === 'number' && Number.isFinite(value) ? `${value}${suffix}` : 'No disponible'; +} +function label(dictionary: unknown, key: unknown, fallback: string): string { + const entry = record(dictionary) && typeof key === 'string' ? dictionary[key] : undefined; + return typeof entry === 'string' ? entry : record(entry) && typeof entry['etiqueta'] === 'string' ? entry['etiqueta'] : fallback; +} +// Read published cells individually. No totals, reconstruction, statistical +// computation or conversion of missing/suppressed values into zero. +export function numericRows(data: IndicadorDatos): NumericRow[] { + return data.filas.map(row => { + const group = row['grupo']; + const groupName = group === 'TOTAL' || group === 'total' ? 'Total' + : label(data['grupos'], group, 'Grupo sin etiqueta publicada'); + const stratum = row['estrato']; + const base = { period: typeof row['periodo'] === 'string' ? row['periodo'] : 'Periodo no disponible', + group: stratum == null ? groupName : `${groupName} · ${label(data['valores_estrato'], stratum, 'Estrato sin etiqueta publicada')}`, + category: label(data['categorias'], row['categoria'], row['categoria'] == null ? '—' : 'Categoría sin etiqueta publicada'), + value: 'No disponible', detail: '', state: 'Disponible' }; + if (row['suprimido'] === 1 || row['suprimido'] === true) return { ...base, value: 'Dato suprimido', state: 'Dato suprimido' }; + if (row['suprimido'] !== 0 && row['suprimido'] !== false) return { ...base, state: 'Estado de supresión no disponible' }; + let primary: unknown; + if (data.contrato === 'C1') { + primary = row['valor']; + return { ...base, value: number(primary, ' %'), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', + detail: `Intervalo publicado: ${number(row['ic_bajo'])} a ${number(row['ic_alto'])} %. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` }; + } + if (data.contrato === 'C2') { + primary = row['n']; + const category = record(data['categorias']) ? data['categorias'][String(row['categoria'])] : undefined; + const parent = record(category) ? label(data['grupos_de_categoria'], category['grupo'], '') : ''; + const unit = typeof row['unidad'] === 'string' ? row['unidad'] : typeof data['unidad'] === 'string' ? data['unidad'] : ''; + return { ...base, category: [parent, base.category].filter(Boolean).join(' · '), value: number(primary), + state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', + detail: [unit && `Unidad: ${unit}.`, Object.hasOwn(row, 'denominador') && `Denominador publicado: ${number(row['denominador'])}.`].filter(Boolean).join(' ') }; + } + if (data.contrato === 'C3r') { + primary = row['mediana']; + const unit = row['unidad'] === 'dias' ? 'días' : typeof row['unidad'] === 'string' ? row['unidad'] : 'Unidad no disponible'; + return { ...base, value: `Mediana: ${number(primary)} · ${unit}`, state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', + detail: `Q1: ${number(row['q1'])}; Q3: ${number(row['q3'])}; n: ${number(row['n'])}.` }; + } + return { ...base, state: 'Resumen no disponible para este indicador' }; + }); +} diff --git a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts new file mode 100644 index 0000000..a4323b5 --- /dev/null +++ b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts @@ -0,0 +1,218 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; +import { IndicadoresNumericSummary } from './indicadores-numeric-summary'; +import { Indicador, IndicadorDatos } from './indicadores.models'; +import { numericRows } from './indicadores-numeric-rows'; +import { dualFigures } from './indicadores-dual-figures'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; + +const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; +const item: Indicador = { id: 'future_indicator', titulo: 'Distribución publicada', contrato: 'C2', + figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre'], version: '2.0' }; +// Representative MD-19 wire shapes: published C1 interval, C2 counts/category +// metadata and C3r quartiles. Only test data; never served as dashboard indicators. +function data(contract = 'C2'): IndicadorDatos { + return { id: item.id, contrato: contract, tipo_periodo: 'semestre', periodos: ['2025-S2'], version: '2.0', + categorias: { A: { etiqueta: 'Categoría publicada', grupo: 'g' } }, grupos_de_categoria: { g: 'Grupo de categorías' }, + filas: [{ periodo: '2025-S2', grupo: 'TOTAL', categoria: 'A', suprimido: 0, n: 0, + valor: 0, numerador: 0, denominador: 20, ic_bajo: 0, ic_alto: 16.1, mediana: 4, q1: 2, q3: 7, unidad: 'dias' }] }; +} + +describe('MD-19 lecturas y celdas numéricas', () => { + it.each(['new_name', 'any_future_id'])('descubre doble representación de %s sin IDs de indicador', id => { + expect(dualFigures({ ...item, id })).toEqual(['fig_c2_donas', 'fig_c2_barras']); + expect(dualFigures({ ...item, id, contrato: 'C1' })).toEqual([]); + expect(dualFigures({ ...item, id, figuras: ['fig_c2_donas'] })).toEqual([]); + expect(dualFigures({ ...item, id, figuras: ['future_donut', 'future_bar'] })).toEqual([]); + }); + it('C1 conserva cero, intervalo publicado y poblaciones sin recalcular Wilson', () => { + const row = numericRows(data('C1'))[0]; + expect(row.value).toBe('0 %'); expect(row.state).toBe('Disponible'); + expect(row.detail).toBe('Intervalo publicado: 0 a 16.1 %. Numerador: 0; denominador: 20.'); + }); + it('C2 conserva categorías, grupos y conteos; no suma poblaciones superpuestas', () => { + const sample = data(); sample['grupos'] = { other: 'Otra población' }; sample.filas.push({ ...sample.filas[0], grupo: 'other', n: 11 }); + const rows = numericRows(sample); + expect(rows).toHaveLength(2); expect(rows.map(r => r.value)).toEqual(['0', '11']); + expect(rows[0].category).toBe('Grupo de categorías · Categoría publicada'); + expect(rows[1].group).toBe('Otra población'); + }); + it('C3r sólo muestra mediana, Q1, Q3, n y unidad publicados', () => { + const row = numericRows(data('C3r'))[0]; + expect(row.value).toBe('Mediana: 4 · días'); expect(row.detail).toBe('Q1: 2; Q3: 7; n: 0.'); + expect(JSON.stringify(row)).not.toMatch(/bigote|extremo|min|max/); + }); + it.each(['C1', 'C2', 'C3r'])('%s nunca revela valores de una fila suprimida ni reconstruye totales', contract => { + const sample = data(contract); sample.filas[0]['suprimido'] = 1; + const row = numericRows(sample)[0]; expect(row.value).toBe('Dato suprimido'); expect(row.detail).toBe(''); + expect(row.state).toBe('Dato suprimido'); + }); + it('distingue null, ausencia, NaN, cero y supresión desconocida', () => { + const sample = data(); + sample.filas = [null, undefined, NaN, 0].map(n => ({ periodo: '2025-S2', grupo: 'TOTAL', n, suprimido: 0 })); + expect(numericRows(sample).map(r => r.value)).toEqual(['Sin valor (nulo)', 'No disponible', 'No disponible', '0']); + delete sample.filas[0]['suprimido']; expect(numericRows(sample)[0].value).toBe('No disponible'); + expect(numericRows(sample)[0].state).toContain('supresión no disponible'); + }); +}); + +describe('snapshots compartidos y resumen accesible', () => { + let http: HttpTestingController, snapshots: IndicadoresSnapshots; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots); + }); + afterEach(() => http.verify()); + const request = () => http.expectOne(r => r.url.endsWith('/datos')); + it('deduplica datos simultáneos de KPI, panel y tabla, y reutiliza payload terminado', () => { + const queries = TestBed.inject(IndicadoresKpiQueries); + const values: IndicadorDatos[] = []; + queries.datos('tea', item.id, applied.tipo, '2025-S2', item.version).subscribe(value => values.push(value)); + snapshots.read('tea', item, applied).subscribe(); + snapshots.datos('tea', item.id, applied.tipo, ['2025-S2'], item.version).subscribe(value => values.push(value)); + request().flush(data()); expect(values).toHaveLength(2); expect(values[0]).toBe(values[1]); + snapshots.read('tea', item, { ...applied, revision: 2 }).subscribe(); http.expectNone(() => true); + expect(snapshots.numeric().get(snapshotKey('tea', item, { ...applied, revision: 2 }))?.status).toBe('ready'); + }); + it('incluye dominio, versión, tipo, selección y revisión en identidad', () => { + const keys = [snapshotKey('tea', item, applied), snapshotKey('cama', item, applied), + snapshotKey('tea', { ...item, version: '3.0' }, applied), snapshotKey('tea', item, { ...applied, revision: 2 }), + snapshotKey('tea', item, { ...applied, tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01'] } }), + snapshotKey('tea', item, { ...applied, selection: { mode: 'todos' } })]; + expect(new Set(keys).size).toBe(keys.length); + }); + it('registra la identidad de versión publicada aunque el catálogo no la exponga', () => { + const unversioned = { ...item, version: undefined }; + snapshots.read('tea', unversioned, applied).subscribe(); request().flush(data()); + const alias = snapshots.numeric().get(snapshotKey('tea', unversioned, applied)); + expect(alias?.sourceKey).toBe(snapshotKey('tea', item, applied)); + expect(snapshots.numeric().get(alias!.sourceKey!)).toBe(alias); + }); + it('reutiliza en la tabla los detalles de datos consultados por un KPI, sin activar figuras', () => { + TestBed.inject(IndicadoresKpiQueries).datos('tea', item.id, 'semestre', '2025-S2', item.version).subscribe(); + request().flush(data()); + expect(snapshots.reading('tea', item, applied)?.data).toEqual(data()); http.expectNone(() => true); + }); + it('cancelar una lectura compartida conserva al otro consumidor; cancelar todos aborta HTTP', () => { + const a = snapshots.read('tea', item, applied).subscribe(), b = snapshots.read('tea', item, applied).subscribe(); + const pending = request(); a.unsubscribe(); expect(pending.cancelled).toBe(false); + b.unsubscribe(); expect(pending.cancelled).toBe(true); + snapshots.read('tea', item, applied).subscribe(); request().flush(data()); + }); + it.each([404, 503])('conserva error HTTP %s y permite reintento sin cachear el error', status => { + snapshots.read('tea', item, applied).subscribe(); request().flush({}, { status, statusText: 'Failure' }); + expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error'); + snapshots.read('tea', item, applied).subscribe(); request().flush(data()); + expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready'); + }); + it.each(['period', 'contract', 'version', 'row'])('rechaza respuesta incompatible por %s', kind => { + snapshots.read('tea', item, applied).subscribe(); const sample = data(); + if (kind === 'period') sample.periodos = ['2024-S1']; + if (kind === 'contract') sample.contrato = 'C1'; + if (kind === 'version') sample['version'] = '1.0'; + if (kind === 'row') sample.filas[0]['periodo'] = '2024-S1'; + request().flush(sample); expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error'); + }); + it('tabla reutiliza exactamente KPI, cambia periodo/dominio sin mostrar valores anteriores y respeta catálogo retirado', () => { + const fixture = TestBed.createComponent(IndicadoresNumericSummary); + fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied); + fixture.componentRef.setInput('kpis', [{ id: item.id, title: 'Destacado publicado', unit: '%', contrato: 'C1' }]); + snapshots.publishKpi('tea', item, applied, { value: '42.0', unit: '%', state: 'Disponible', period: '2025-S2', info: 'Nota publicada' }); + fixture.detectChanges(); let element = fixture.nativeElement as HTMLElement; + expect(element.querySelector('.kpi-reading')?.textContent?.replace(/\s+/g, ' ')).toContain('42.0 %'); + expect(element.querySelector('.kpi-reading')?.textContent).toContain('2025-S2'); + expect(element.querySelector('.kpi-reading')?.textContent).toContain('Nota publicada'); + expect(element.querySelector('caption')).toBeTruthy(); expect(element.querySelectorAll('thead th[scope="col"]')).toHaveLength(5); + expect(element.querySelector('.table-scroll')?.getAttribute('tabindex')).toBe('0'); http.expectNone(() => true); + fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); + fixture.detectChanges(); expect(element.textContent).not.toContain('42.0'); expect(element.textContent).toContain('2026-S1'); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); + expect(element.textContent).not.toContain('42.0'); + fixture.componentRef.setInput('catalog', []); fixture.detectChanges(); expect(element.querySelectorAll('tbody tr')).toHaveLength(0); + fixture.destroy(); + }); + it('tabla distingue carga, error y vacío publicado sin volver a consultar', () => { + const fixture = TestBed.createComponent(IndicadoresNumericSummary); + fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied); + snapshots.read('tea', item, applied).subscribe(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando…'); + request().flush({}, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Error de consulta'); + snapshots.read('tea', item, applied).subscribe(); request().flush({ ...data(), filas: [] }); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Sin filas publicadas'); http.expectNone(() => true); fixture.destroy(); + }); +}); + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +describe('card doble, jerarquía y carga numérica diferida', () => { + let fixture: ReturnType>, http: HttpTestingController, snapshots: IndicadoresSnapshots; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots); + fixture = TestBed.createComponent(IndicadorCatalogCard); + fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', item); + fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const panels = () => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(el => el.componentInstance as IndicadorFigurePanel); + function activate() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } + const figure = (id: string) => http.expectOne(r => r.url.endsWith('/figuras/' + id)); + it('dos paneles sin selector redundante, diferidos hasta activación y con mismo periodo aplicado', () => { + expect(panels()).toHaveLength(2); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); http.expectNone(() => true); + activate(); + const pending = http.expectOne(r => r.url.endsWith('/datos')); + expect(pending.request.params.get('periodos')).toBe('2025-S2'); pending.flush({ ...c2Fixture(), id: item.id }); + expect(panels().every(p => p.result().source === 'datos')).toBe(true); + expect(fixture.nativeElement.classList.contains('dual-card')).toBe(true); + expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']); + http.expectNone(() => true); + }); + it('drill-down y restauración de dona no alteran barras, JSON original ni generan consultas', () => { + activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges(); + const bars = structuredClone(panels()[1].result().figure); + const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard); + const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result(); + const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf].find(button => button.textContent?.trim() === 'G2')!; + parentButton.click(); fixture.detectChanges(); expect(cards[0].activeParent).toBe('G2'); + expect(panels()[1].result()).toBe(barState); expect(panels()[1].result().figure).toEqual(bars); + (fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); http.expectNone(() => true); + }); + it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => { + snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true); + activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges(); + expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready'); + snapshots.expanded.set(false); fixture.detectChanges(); snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true); + }); + it('cambio de periodo cancela ambas figuras y números; fuera de vista difiere el siguiente aplicado', () => { + snapshots.expanded.set(true); activate(); const old = [http.expectOne(r => r.url.endsWith('/datos'))]; + fixture.componentInstance.setVisible(false); fixture.detectChanges(); + fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges(); + expect(old.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().status === 'deferred')).toBe(true); + http.expectNone(() => true); + activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...data(), periodos: ['2026-S1'], filas: [] }); + for (const id of ['fig_c2_donas', 'fig_c2_barras']) { + const pending = figure(id); expect(pending.request.params.get('periodos')).toBe('2026-S1'); pending.flush({ data: [], layout: {} }); + } + }); + it('conserva preferencias y opciones adicionales; desaparece representación retirada y hace fallback', () => { + const memory = TestBed.inject(IndicadoresMemory); memory.rememberFigure('tea', item.id, 'fig_c2_barras'); + fixture.componentRef.setInput('indicador', { ...item, figuras: [...item.figuras, 'future_representation'] }); fixture.detectChanges(); + expect(fixture.componentInstance.isDual).toBe(true); expect(memory.figure('tea', item.id)).toBe('fig_c2_barras'); + fixture.componentInstance.selectFigure('future_representation'); fixture.detectChanges(); + expect(fixture.componentInstance.displayFigures).toEqual(['future_representation']); + fixture.componentRef.setInput('indicador', { ...item, figuras: ['fig_c2_donas'] }); fixture.detectChanges(); + expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas']); expect(fixture.nativeElement.querySelector('mat-select')).toBeTruthy(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-numeric-summary.ts b/src/app/features/indicadores/indicadores-numeric-summary.ts new file mode 100644 index 0000000..ffc0566 --- /dev/null +++ b/src/app/features/indicadores/indicadores-numeric-summary.ts @@ -0,0 +1,81 @@ +import { Component, inject, Input, OnDestroy } from '@angular/core'; +import { Dominio, Indicador } from './indicadores.models'; +import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { KpiDefinition } from './indicadores-kpi'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { numericRows } from './indicadores-numeric-rows'; + +@Component({ + selector: 'app-indicadores-numeric-summary', + template: ` +
+

Resumen de indicadores

+

Valores publicados para {{ period }}. Los detalles se cargan al consultar las gráficas correspondientes. Cada fila conserva su periodo y población; no se suman grupos ni periodos.

+
+ + + + + @for (definition of kpis; track definition.id) { + @let item = find(definition.id); + @if (item) { + @let kpi = snapshots.kpis().get(key(item)); + + + + + } + } + @for (item of catalog; track item.id) { + @let reading = snapshots.reading(dominio, item, applied); + @let compatible = compatibility(item); + @if (compatible.compatible && reading?.status === 'ready' && reading?.data; as data) { + @for (row of rows(data); track $index) { + + + } @empty { + + } + } @else { + + + } + } + +
Resultados de indicadores destacados y gráficas consultadas
IndicadorPeriodoGrupo / categoríaResultadoEstado y notas
{{ definition.title }} Destacado{{ kpi?.period ?? period }}—{{ kpi?.value ?? 'No disponible' }} @if (kpi?.value !== undefined) { {{ kpi?.unit }} }{{ kpi?.state ?? 'Pendiente de lectura' }} {{ kpi?.info }} {{ kpi?.notes?.join(' ') }}
{{ item.titulo }}{{ row.period }}{{ row.group }} · {{ row.category }}{{ row.value }} {{ row.detail }}{{ row.state }} {{ data.notas?.join(' ') }}
{{ item.titulo }}{{ period }}—Sin filas publicadas{{ data.notas?.join(' ') }}
{{ item.titulo }}{{ period }}—No disponible{{ !compatible.compatible ? compatible.reason : reading?.status === 'loading' ? 'Cargando…' : reading?.status === 'error' ? 'Error de consulta: ' + reading?.message : 'Pendiente: consulta la gráfica para cargar sus números.' }} + @if (reading?.status === 'error') { }
+
+
`, + styles: ` + :host { display: block; min-width: 0; margin-top: var(--issste-space-6); } + details { border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); padding: 1rem; } + summary { cursor: pointer; min-height: 44px; align-content: center; } + h2 { display: inline; font-family: var(--issste-font-heading); font-size: 1.5rem; } + p, td, th { overflow-wrap: anywhere; } + p, .kind, .detail { color: var(--issste-text-secondary); } + .kind, .detail { display: block; font-weight: normal; } + .table-scroll { overflow-x: auto; max-height: 32rem; } + table { width: 100%; border-collapse: collapse; font-size: .9rem; } + caption { text-align: left; padding: .5rem; } + th, td { padding: .65rem; border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; min-width: 6rem; } + thead { background: var(--issste-surface); position: sticky; top: 0; } + button { min-height: 44px; font: inherit; color: var(--issste-text); background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + :focus-visible { outline: 2px solid var(--issste-text); outline-offset: -2px; } + @media (max-width: 550px) { details { padding: .5rem; } th, td { padding: .5rem; } } + `, +}) +export class IndicadoresNumericSummary implements OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) catalog: readonly Indicador[] = []; + @Input({ required: true }) applied!: GlobalApplied; + @Input() kpis: readonly KpiDefinition[] = []; + readonly snapshots = inject(IndicadoresSnapshots); + readonly rows = numericRows; + readonly increment = (value: number) => value + 1; + get period() { return describePeriods(this.applied.tipo, this.applied.selection); } + key(item: Indicador) { return snapshotKey(this.dominio, item, this.applied); } + find(id: string) { return this.catalog.find(item => item.id === id); } + compatibility(item: Indicador) { return filterCompatibility(this.applied, item.tipos_periodo); } + toggle(event: Event) { this.snapshots.expanded.set((event.target as HTMLDetailsElement).open); } + ngOnDestroy() { this.snapshots.expanded.set(false); } +} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 73e9689..db3cb6b 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -10,24 +10,47 @@ } +
+ @for (section of sections; track section.id) { + + } +
+ +
@if (!catalogLoading() && filters; as state) {

Filtros generales de {{ domainLabels[dominio] }}

La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.

- + (edited)="editFilters()" (apply)="applyFilters()" />
} + @if (initialPeriodState() === 'loading') { + +

Buscando el periodo más reciente con un conteo válido y positivo en «{{ initialPeriodAnchorTitle }}»…

+ } @else if (initialPeriodState() === 'error') { +

No se pudo determinar el periodo inicial de {{ domainLabels[dominio] }}. {{ initialPeriodError() }}

+ +

También puedes seleccionar un periodo y pulsar Aplicar.

+ } @else if (initialPeriodState() === 'empty') { +

No se encontró un periodo con un conteo válido mayor que cero en «{{ initialPeriodAnchorTitle }}». Los ceros, valores ausentes y datos ocultos no establecen un periodo inicial. Selecciona un periodo y pulsa Aplicar para consultar.

+ + } @else if (initialPeriodState() === 'unavailable') { +

El indicador de referencia para el periodo inicial ya no está publicado. Selecciona un periodo y pulsa Aplicar para consultar los indicadores vigentes.

+ } @else if (initialPeriodState() === 'manual') { +

La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.

+ } @let kpis = availableKpis; - @if (kpis.length) { + @if (kpis.length && !initialPeriodBlocked) {

Indicadores destacados

-

La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.

@for (definition of kpis; track dominio + ':' + definition.id) { + [applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" /> }
@@ -49,7 +72,7 @@ } @else if (!catalog().length) {

No hay indicadores disponibles en el catálogo.

- } @else { + } @else if (!initialPeriodBlocked) { @if (searchVisible()) { }
+ @if (!initialPeriodBlocked && filters && !catalogLoading() && !catalogError() && catalog().length) { + + } +
+ +
+ +
+ +
+ +
diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index fe52754..912c621 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -55,3 +55,21 @@ nav a[aria-current='page'] { .global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; } @container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } + +.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1); + border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border); + background: var(--issste-surface); padding: var(--issste-space-2) var(--issste-space-2) 0; + border-radius: var(--issste-radius) var(--issste-radius) 0 0; } +.section-tabs button { min-width: min-content; min-height: 48px; padding: .5rem 1rem; font: inherit; + color: var(--issste-text-secondary); background: transparent; border: 0; border-bottom: 3px solid transparent; + cursor: pointer; } +.section-tabs button[aria-selected='true'] { color: var(--issste-text); border-bottom-color: var(--issste-accent); font-weight: 700; } +.section-tabs button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; } +.section-tabs.dark-theme, .section-panel.dark-theme { + --issste-surface: #151b28; --issste-background: #202838; --issste-text: #eef1f7; + --issste-text-secondary: #a1aabd; --issste-border: #596477; + color: var(--issste-text); color-scheme: dark; +} +.section-panel { padding-block: var(--issste-space-6); } +.section-panel[hidden] { display: none; } +@media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 65f04e7..737562a 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -44,11 +44,11 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { function kpiMissing() { http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); fixture.detectChanges(); } function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; } - it('KPI-DYNAMIC TEA muestra sus tres destacados sin consultar datos fuera del catálogo', () => { + it('no presenta destacados retirados del catálogo ni consulta sus datos', () => { load(); - expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores destacados'); + expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull(); expect(Array.from(fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card h3')).map(h => (h as HTMLElement).textContent)) - .toEqual(['Total de pacientes evaluados', 'Porcentaje de confirmación diagnóstica', 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo']); + .toEqual([]); http.expectNone(r => r.url.endsWith('/datos')); }); it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { @@ -63,7 +63,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { page.retryCatalog(); fixture.detectChanges(); load([]); expect(page.catalogLoading()).toBe(false); expect(page.catalogError()).toBe(''); expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); - expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(3); + expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0); http.expectNone(() => true); }); it('D.1 separa secciones y conserva tarjetas, orden, identidades y figuras dentro del grid', () => { @@ -72,8 +72,11 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(getComputedStyle(grid).display).toBe('grid'); expect(grid.children).toHaveLength(2); expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true); - const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf; - expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']); + const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf; + expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']); + const summary = fixture.nativeElement.querySelector('app-indicadores-numeric-summary') as HTMLElement; + expect(sections[1].compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(summary.textContent).toContain('Resumen de indicadores'); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right'); toggle(0); toggle(1); flushAll(); @@ -282,7 +285,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { const c = control(); c.changeTipo('mes'); c.year = '2025'; c.unit = '01'; c.add(); http.expectNone(() => true); page.applyFilters(); fixture.detectChanges(); const r = http.expectOne(r => r.url.includes('/figuras/')); expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges(); - expect(fixture.nativeElement.textContent).toContain('no entregan intervalos Wilson efectivos'); + expect(fixture.nativeElement.textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %'); expect(fixture.nativeElement.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); }); it('catálogo error, reintento y vacío no dejan paneles', () => { diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 90fbfdc..dd302d2 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -10,10 +10,10 @@ import { MatInputModule } from '@angular/material/input'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs'; +import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs'; import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory'; +import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { KPI_BY_DOMAIN } from './indicadores-kpi'; @@ -21,14 +21,44 @@ import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; +import { IndicadoresInitialPeriod } from './indicadores-initial-period'; +import { IndicadoresDefinitions } from './indicadores-definitions'; +import { IndicadoresTracking } from './indicadores-tracking'; +import { IndicadoresNumericSummary } from './indicadores-numeric-summary'; + +type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { + readonly sections: readonly { id: DashboardSection; label: string }[] = [ + { id: 'resumen', label: 'Resumen' }, + { id: 'seguimiento', label: 'Seguimiento' }, + { id: 'datos', label: 'Datos y definiciones' }, + ]; + readonly activeSection = signal('resumen'); + changeSection(section: DashboardSection) { + if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return; + this.activeSection.set(section); + // Retain views, filters and Plotly hosts; only visible regions authorize loading. + if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false); + this.visibilityChanged(); + } + sectionKeydown(event: KeyboardEvent) { + if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; + const tabs = Array.from(this.element.nativeElement.querySelectorAll('[role="tab"]')); + const index = tabs.indexOf(event.target as HTMLButtonElement); + if (index < 0) return; + event.preventDefault(); + const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 + : (index + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length; + // Manual activation: arrows move focus; Enter/Space activate the native button. + tabs[next].focus(); + } private readonly document = inject(DOCUMENT); private readonly element = inject>(ElementRef); private readonly injector = inject(Injector); @@ -66,6 +96,10 @@ export class IndicadoresPage { private syncVisibility() { if (this.visibilityDestroyed || !this.document.defaultView) return; const cards = this.graphicCards(); + if (this.activeSection() !== 'resumen') { + for (const card of cards) card.setVisible(false); + return; + } if (typeof IntersectionObserver === 'undefined') { for (const card of cards) card.setVisible(true); return; @@ -118,6 +152,7 @@ export class IndicadoresPage { private evaluateVisibility() { const browser = this.document.defaultView; if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; + if (this.activeSection() !== 'resumen') return; this.refreshVisibilityObserver(); const width = browser.innerWidth, height = browser.innerHeight; // Reread connected graphic regions after scroll/reorder; old observer rectangles @@ -160,6 +195,43 @@ export class IndicadoresPage { private readonly changeDetector = inject(ChangeDetectorRef); private readonly service = inject(IndicadoresService); private readonly periodService = inject(IndicadoresPeriodos); + private readonly initialPeriod = inject(IndicadoresInitialPeriod); + private readonly cancelInitialPeriod = new Subject(); + readonly initialPeriodState = signal<'ready' | 'loading' | 'error' | 'empty' | 'manual' | 'unavailable'>('ready'); + readonly initialPeriodError = signal(''); + get initialPeriodBlocked() { return this.initialPeriodState() !== 'ready'; } + get initialPeriodAnchorTitle() { return this.availableKpis[0]?.title ?? ''; } + retryInitialPeriod() { this.initializePeriod(); } + private initializePeriod() { + this.cancelInitialPeriod.next(); + this.initialPeriodState.set('ready'); + this.initialPeriodError.set(''); + const domain = this.dominio, state = this.filters, anchor = this.kpisByDomain[domain][0]; + if (!state || !anchor || !this.availableKpis.length || !this.memory.initialKpiPresentation(domain)) return; + if (!this.kpiIndicator(anchor.id)) { this.initialPeriodState.set('unavailable'); return; } + // A saved manual draft must survive navigation and a catalog retry. + if (pending(state)) { this.initialPeriodState.set('manual'); return; } + this.initialPeriodState.set('loading'); + this.initialPeriod.find(domain, anchor, state.tipo, this.kpiIndicator(anchor.id)?.version).pipe( + map(period => ({ period, error: '' })), + catchError(error => of({ period: undefined, error: httpMessage(error) })), + takeUntil(this.cancelInitialPeriod), takeUntilDestroyed(this.destroyRef), + ).subscribe(({ period, error }) => { + if (error) { + this.initialPeriodError.set(error); + this.initialPeriodState.set('error'); + return; + } + if (!period) { this.initialPeriodState.set('empty'); return; } + state.tipo = period.tipo; + state.editors[period.tipo] = { added: state.editors[period.tipo]?.added ?? [], + draft: { mode: 'explicit', periodos: [period.periodo] } }; + applyGlobal(state, this.filterTypes()); + this.memory.finishInitialKpiPresentation(domain); + this.filtersEdited(); + this.initialPeriodState.set('ready'); + }); + } private readonly availabilityRequests = new Subject(); readonly availability = signal(emptyAvailability()); private readonly memory = inject(IndicadoresMemory); @@ -170,8 +242,7 @@ export class IndicadoresPage { readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly kpisByDomain = KPI_BY_DOMAIN; kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } - get availableKpis() { return this.kpisByDomain[this.dominio]; } - get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); } + get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } private readonly catalogRequests = new Subject(); readonly catalog = signal([]); readonly searchQuery = signal(''); @@ -202,12 +273,21 @@ export class IndicadoresPage { readonly filterTypes = computed(() => domainTypes(this.catalog())); retryAvailability() { this.availabilityRequests.next(); } filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); } + editFilters() { + if (this.memory.initialKpiPresentation(this.dominio)) { + this.cancelInitialPeriod.next(); + this.initialPeriodState.set('manual'); + } + this.filtersEdited(); + } applyFilters() { this.evaluateVisibility(); if (!this.filters) return; const draft = this.filters.editors[this.filters.tipo]?.draft; if (!draft || !validDraft(draft, this.filters.tipo, this.filterTypes())) return; - const initial = this.initialKpiPresentation; + const initial = this.memory.initialKpiPresentation(this.dominio); + this.cancelInitialPeriod.next(); + this.initialPeriodState.set('ready'); this.memory.finishInitialKpiPresentation(this.dominio); if (!applyGlobal(this.filters, this.filterTypes()) && !initial) return; this.filtersEdited(); @@ -238,6 +318,8 @@ export class IndicadoresPage { return this.periodService.dominio(this.dominio, this.catalog()); }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { + this.cancelInitialPeriod.next(); + this.initialPeriodState.set('ready'); this.clearVisibility(); this.catalogLoading.set(true); this.catalogError.set(''); @@ -252,10 +334,12 @@ export class IndicadoresPage { this.filtersEdited(); this.catalogError.set(error); this.availabilityRequests.next(); + this.initializePeriod(); }); } changeDominio(dominio: Dominio) { if (!isDominio(dominio) || dominio === this.dominio) return; + this.activeSection.set('resumen'); this.searchQuery.set(''); this.filtersEdited(); this.filters = undefined; diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts index a02b251..d68ff6e 100644 --- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -39,21 +39,28 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { }] }; } function flushDatos(domain: Dominio, suppressed = false) { - const requests = http.match(r => r.url.endsWith('/datos')); - requests.forEach(r => { - const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); - r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed)); - }); - fixture.detectChanges(); return requests; + const resolved = []; + for (;;) { + const requests = http.match(r => r.url.endsWith('/datos')); + if (!requests.length) return resolved; + resolved.push(...requests); + requests.forEach(r => { + const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); + r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed)); + }); + fixture.detectChanges(); + } } - it.each(['cacu', 'cama'] as const)('%s usa últimos periodos propios, conserva ceros y no altera Todos aplicado', domain => { + it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => { load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); + const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos')); + const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges(); const requests = flushDatos(domain); - expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S2', '2025-S2']); - expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S2', '2025-S2']); - expect(panels().map(p => p.result().value)).toEqual([0, '0.0', 0]); - expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'todos' }); - expect(fixture.componentInstance.filters!.applied.revision).toBe(0); + expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S1']); + expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S1', '2026-S1']); + expect(panels().map(p => p.result().value)).toEqual([4, '0.0', 0]); + expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] }); + expect(fixture.componentInstance.filters!.applied.revision).toBe(1); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); }); it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => { @@ -67,7 +74,10 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true); }); it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => { - load('cama', [[], ['2025-S2'], ['2025-S1']]); const requests = flushDatos('cama'); + load('cama', [[], ['2025-S2'], ['2025-S1']]); + expect(fixture.componentInstance.initialPeriodState()).toBe('empty'); expect(panels()).toHaveLength(0); + http.expectNone(r => r.url.endsWith('/datos')); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); const requests = flushDatos('cama'); expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); expect(panels()[0].result().value).toBeUndefined(); }); @@ -94,12 +104,13 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { requests[0].flush('private', { status: 503, statusText: 'Unavailable' }); requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2']))); fixture.detectChanges(); flushDatos('cacu'); - expect(panels()[0].result().state).toBe('Error de disponibilidad'); - expect(fixture.nativeElement.textContent).toContain('No se pudo completar la consulta'); + expect(fixture.componentInstance.initialPeriodState()).toBe('error'); + expect(panels()).toHaveLength(0); + expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de CaCu'); expect(fixture.nativeElement.textContent).not.toContain('private'); const control = editor(); control.changeMode('manual'); control.select(['2025-S2']); expect(control.canApply).toBe(false); - fixture.componentInstance.retryAvailability(); fixture.detectChanges(); + fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges(); const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos'); http.expectNone(r => r.url.endsWith('/periodos')); retry.flush(payload('cacu_eu7', ['2025-S2'])); fixture.detectChanges(); flushDatos('cacu'); diff --git a/src/app/features/indicadores/indicadores-periodos.testing.ts b/src/app/features/indicadores/indicadores-periodos.testing.ts index 5cee482..278cb44 100644 --- a/src/app/features/indicadores/indicadores-periodos.testing.ts +++ b/src/app/features/indicadores/indicadores-periodos.testing.ts @@ -1,13 +1,18 @@ import { NEVER, of } from 'rxjs'; +import { inject } from '@angular/core'; +import { IndicadoresMemory } from './indicadores-memory'; import { Indicador } from './indicadores.models'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; -// Existing figure/search/visibility suites isolate their HTTP from availability. -// The new P0.1 suites exercise the real availability HTTP separately. +// Consumer suites start after initialization and isolate availability HTTP. +// Initial-period suites exercise the real shared search and domain memory. export const periodAvailabilityProvider = { provide: IndicadoresPeriodos, - useValue: { dominio: (_domain: unknown, catalog: Indicador[]) => { + useFactory: () => { + const memory = inject(IndicadoresMemory); + for (const domain of ['tea', 'cacu', 'cama'] as const) memory.finishInitialKpiPresentation(domain); + return { dominio: (_domain: unknown, catalog: Indicador[]) => { const state = emptyAvailability('ready'); for (const tipo of ['semestre', 'mes'] as const) { state.options[tipo] = [2024, 2025, 2026].flatMap(year => @@ -15,7 +20,8 @@ export const periodAvailabilityProvider = { } for (const item of catalog) state.byIndicator[item.id] = item.tipos_periodo.flatMap(tipo => state.options[tipo].map(periodo => ({ tipo, periodo }))); return of(state); - } }, + } }; + }, }; // Figure/search/visibility suites also isolate their HTTP from the KPI panels, diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts new file mode 100644 index 0000000..4587f02 --- /dev/null +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -0,0 +1,146 @@ +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 { RouterTestingHarness } from '@angular/router/testing'; +import { By } from '@angular/platform-browser'; +import { routes } from '../../app.routes'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresDefinitions } from './indicadores-definitions'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { Indicador, DOMINIOS } from './indicadores.models'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +const catalog: Indicador[] = [ + { id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras', 'fig_c2_donas', 'future'], tipos_periodo: ['mes'] }, + { id: 'incomplete', titulo: '', contrato: '', figuras: [], tipos_periodo: ['semestre'] }, +]; + +describe('Secciones compartidas por dominio', () => { + let http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + + it.each(DOMINIOS)('entrada directa en %s presenta tres pestañas y Resumen seleccionado', async domain => { + const harness = await RouterTestingHarness.create(); + const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); + http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); + const root = harness.routeNativeElement!; + const tabs = Array.from(root.querySelectorAll('[role="tab"]')); + expect(tabs.map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']); + expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(['true', 'false', 'false']); + expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]); + expect(root.querySelector('a[aria-current="page"]')?.textContent?.trim()).toBe(page.domainLabels[domain]); + for (const tab of tabs) { + const panel = root.querySelector('#' + tab.getAttribute('aria-controls'))!; + expect(panel.getAttribute('aria-labelledby')).toBe(tab.id); + expect(panel.hidden).toBe(tab.id !== 'tab-resumen'); + } + const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance); + tabs[1].click(); harness.detectChanges(); + if (domain === 'cacu') { + http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); + harness.detectChanges(); + } + const tracking = root.querySelector('#panel-seguimiento')!; + expect(tracking.hidden).toBe(false); + expect(tracking.textContent).toContain('El seguimiento aún no está disponible'); + if (domain === 'cacu') { + expect(tracking.querySelector('tbody')).toBeNull(); + expect(tracking.querySelector('input[type=date]')).not.toBeNull(); + } else { + expect(tracking.querySelectorAll('thead th')).toHaveLength(6); + expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1); + expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6'); + expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0); + } + tabs[2].click(); harness.detectChanges(); + expect(root.querySelector('#panel-datos')!.hidden).toBe(false); + tabs[0].click(); harness.detectChanges(); + expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards); + http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes. + }); + + it('cambiar de dominio reinicia Resumen tanto por router como por coordinación de página', async () => { + const harness = await RouterTestingHarness.create(); + for (const domain of DOMINIOS) { + const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); + http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); + expect(page.activeSection()).toBe('resumen'); page.changeSection('datos'); harness.detectChanges(); + } + const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; + page.changeDominio('tea'); http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges(); + expect(page.activeSection()).toBe('resumen'); http.expectNone(() => true); + }); + + it('teclado mueve foco con flechas, Home y End sin activar una sección ni consultar', async () => { + const harness = await RouterTestingHarness.create(); + const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges(); + const tabs = Array.from(harness.routeNativeElement!.querySelectorAll('[role="tab"]')); + expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1]); + const focus = tabs.map(tab => vi.spyOn(tab, 'focus')); + function key(index: number, key: string, target: number) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true); + expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen'); + } + key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 2); key(1, 'Home', 0); key(0, 'End', 2); + tabs[2].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, 0]); + http.expectNone(() => true); + }); + + it.each(['loading', 'empty', 'error'] as const)('Datos y definiciones comunica catálogo %s sin inventar contenido', async state => { + const harness = await RouterTestingHarness.create(); + const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage); + const request = http.expectOne('/tea/indicadores'); + if (state === 'empty') request.flush([]); + if (state === 'error') request.flush('private', { status: 503, statusText: 'Unavailable' }); + page.changeSection('datos'); harness.detectChanges(); + const root = harness.routeNativeElement!.querySelector('#panel-datos')!; + expect(root.textContent).toContain(state === 'loading' ? 'Cargando catálogo' : state === 'empty' ? 'No hay indicadores' : 'No se pudo cargar'); + expect(root.querySelectorAll('details')).toHaveLength(0); + expect(root.textContent).not.toContain('private'); + if (state === 'loading') request.flush([]); + if (state === 'error') { + root.querySelector('button')!.click(); + http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges(); + expect(page.activeSection()).toBe('datos'); + expect(root.querySelectorAll('details')).toHaveLength(2); + } + http.expectNone(() => true); + }); +}); + +describe('Datos y definiciones reutiliza metadatos sin servicios', () => { + it.each(DOMINIOS)('publica sólo información disponible y nombres amigables para %s', domain => { + const fixture = TestBed.createComponent(IndicadoresDefinitions); + fixture.componentRef.setInput('dominio', domain); + fixture.componentRef.setInput('catalog', catalog); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + expect(root.querySelectorAll('details')).toHaveLength(catalog.length); + expect(root.querySelector('summary')?.textContent).toBe('Nombre publicado'); + expect(root.textContent).toContain('Barras'); expect(root.textContent).toContain('Donas'); + expect(root.textContent).toContain('Representación 3'); expect(root.textContent).not.toContain('fig_c2'); + expect(root.textContent).toContain('Mensual'); expect(root.textContent).toContain('Semestral'); + expect(root.textContent).toContain('Nombre pendiente de publicación'); + expect(root.textContent).toContain('No hay representaciones publicadas'); + expect(root.textContent).toContain('La definición metodológica está pendiente de información'); + expect(root.textContent).not.toMatch(/WebApp|WebApi|C1|C2|C3r|Origen de la información/); + expect(root.textContent).toContain('La información metodológica ampliada no está disponible'); + expect(root.querySelectorAll('details[open]')).toHaveLength(0); + expect(root.textContent).toContain('Un valor nulo significa que no hay un valor disponible'); + expect(root.textContent).toContain('Los datos suprimidos tampoco representan un cero'); + fixture.destroy(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-snapshots.ts b/src/app/features/indicadores/indicadores-snapshots.ts new file mode 100644 index 0000000..a3bc9a3 --- /dev/null +++ b/src/app/features/indicadores/indicadores-snapshots.ts @@ -0,0 +1,86 @@ +import { inject, Injectable, signal } from '@angular/core'; +import { catchError, defer, map, Observable, of, shareReplay, startWith, tap } from 'rxjs'; +import { DatosScope, Dominio, Indicador, IndicadorDatos, TipoPeriodo } from './indicadores.models'; +import { GlobalApplied, selectionKey } from './indicadores-memory'; +import { IndicadoresRequests } from './indicadores-requests'; +import { IndicadoresService } from './indicadores.service'; +import { KpiResult } from './indicadores-kpi'; +import { httpMessage } from './indicadores-http'; + +export type NumericSnapshot = { status: 'loading' | 'error' | 'ready'; data?: IndicadorDatos; message?: string; sourceKey?: string }; +export interface KpiSnapshot extends KpiResult { period: string; unit: string; sourceKey?: string; } + +// Dimension and filters are explicit scopes; stratified payloads cannot replace +// the general KPI/summary reading. Applied revision belongs to the +// reading snapshot; identical immutable HTTP payloads can be reused across revisions. +export function snapshotKey(domain: Dominio, item: Pick, applied: GlobalApplied, scope: DatosScope = {}) { + return JSON.stringify([domain, item.id, item.version ?? null, selectionKey(applied), scope.estrato ?? null, applied.revision, [...(scope.filtros ?? [])].sort()]); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresSnapshots { + private readonly service = inject(IndicadoresService); + private readonly queue = inject(IndicadoresRequests); + private readonly cache = new Map>(); + private readonly payloads = signal>(new Map()); + readonly numeric = signal>(new Map()); + readonly kpis = signal>(new Map()); + readonly expanded = signal(false); + readonly retries = signal(0); + + private transportKey(domain: Dominio, id: string, tipo: TipoPeriodo, periods?: readonly string[], version?: string, scope: DatosScope = {}) { + return JSON.stringify([domain, id, version ?? null, tipo, periods ? [...new Set(periods)].sort() : null, scope.estrato ?? null, [...(scope.filtros ?? [])].sort()]); + } + reading(domain: Dominio, item: Indicador, applied: GlobalApplied): NumericSnapshot | undefined { + const existing = this.numeric().get(snapshotKey(domain, item, applied)); + if (existing) return existing; + const data = this.payloads().get(this.transportKey(domain, item.id, applied.tipo, + applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined, item.version)); + return data && data.contrato === item.contrato && data.tipo_periodo === applied.tipo + ? { status: 'ready', data, sourceKey: this.sourceKey(domain, item, applied, data['version']) } : undefined; + } + private sourceKey(domain: Dominio, item: Pick, applied: GlobalApplied, version: unknown) { + return snapshotKey(domain, { ...item, version: item.version ?? (typeof version === 'string' ? version : undefined) }, applied); + } + + datos(domain: Dominio, id: string, tipo: TipoPeriodo, periods?: string[], version?: string, scope: DatosScope = {}) { + const key = this.transportKey(domain, id, tipo, periods, version, scope); + let request = this.cache.get(key); + if (!request) { + request = this.queue.run(() => this.service.datos(domain, id, tipo, periods, scope)).pipe( + map(data => { + if (version && data['version'] !== undefined && data['version'] !== version) throw new Error('La versión recibida no corresponde al indicador.'); + return data; + }), + tap(data => this.payloads.update(current => new Map(current).set(key, data))), + // Ref counting cancels unfinished transport; errors never become cached values. + shareReplay({ bufferSize: 1, refCount: true })); + this.cache.set(key, request); + } + return request; + } + read(domain: Dominio, item: Indicador, applied: GlobalApplied) { + const key = snapshotKey(domain, item, applied); + const periods = applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined; + return defer(() => this.datos(domain, item.id, applied.tipo, + applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined, item.version)).pipe( + map(data => { + if (data.contrato !== item.contrato || data.tipo_periodo !== applied.tipo + || (item.version && data['version'] !== undefined && data['version'] !== item.version) + || (periods && data.periodos.some(p => !periods.includes(p))) + || data.filas.some(row => typeof row['periodo'] !== 'string' || !data.periodos.includes(row['periodo']))) { + throw new Error('Los datos recibidos no corresponden a la selección aplicada.'); + } + return { status: 'ready', data, sourceKey: this.sourceKey(domain, item, applied, data['version']) } as NumericSnapshot; + }), + catchError(error => of({ status: 'error', message: httpMessage(error) })), + startWith({ status: 'loading' } as NumericSnapshot), + // The request key is an alias when the catalog omits version. A ready + // snapshot also has its canonical identity using the published data version. + tap(value => this.numeric.update(current => new Map(current).set(key, value).set(value.sourceKey ?? key, value)))); + } + publishKpi(domain: Dominio, item: Pick, applied: GlobalApplied, value: KpiSnapshot, version?: string) { + const key = snapshotKey(domain, item, applied), sourceKey = this.sourceKey(domain, item, applied, version); + const snapshot = { ...value, sourceKey }; + this.kpis.update(current => new Map(current).set(key, snapshot).set(sourceKey, snapshot)); + } +} diff --git a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts new file mode 100644 index 0000000..54505c7 --- /dev/null +++ b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts @@ -0,0 +1,60 @@ +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 { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; +import { Indicador, IndicadorDatos } from './indicadores.models'; +import { GlobalApplied } from './indicadores-memory'; +import age from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json'; +import status from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; +@Component({selector:'app-plotly-chart',inputs:['figure','label','showNotes'],template:''}) class ChartStub {} +const applied:GlobalApplied={tipo:'semestre',selection:{mode:'explicit',periodos:['2025-S2']},revision:1}; +const item:Indicador={id:'cacu_eu7',version:'0.2.0',titulo:'Distribución',contrato:'C2',figuras:['fig_c2_barras'],tipos_periodo:['semestre'],filtros:[age,status].map(d=>({estrato:d.estrato,etiqueta:d.estrato,valores:d.valores_estrato.map(valor=>({valor,etiqueta:valor}))}))}; +describe('Barras estratificadas: activación y caché',()=>{ + let fixture:ReturnType>, http:HttpTestingController; + const general=()=>({...c2Fixture(),id:item.id,version:item.version}); + beforeEach(()=>{ + TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); + TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}}); + fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController); + for(const [k,v] of Object.entries({dominio:'cacu',indicador:item,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v); + }); + afterEach(()=>{fixture.destroy();http.verify();}); + const request=()=>http.expectOne(r=>r.url.endsWith('/datos')); + it('carga solo general; consulta dimensión elegida, filtra localmente y restaura sin GET',()=>{ + fixture.detectChanges(); const base=request(); expect(base.request.params.has('estrato')).toBe(false); base.flush(general()); + fixture.componentInstance.changeDimension('grupo_edad'); const q=request(); expect(q.request.params.get('estrato')).toBe('grupo_edad'); expect(q.request.params.get('periodos')).toBe('2025-S2'); q.flush(age); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Suprimido'); + for(const selection of [{parent:'Anormal'},{parent:'Anormal',category:'LIEAG'},{}]) {fixture.componentRef.setInput('localSelection',selection);fixture.detectChanges();http.expectNone(()=>true);} + fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status); + fixture.componentInstance.changeDimension('grupo_edad'); http.expectNone(()=>true); + fixture.componentInstance.changeDimension(''); http.expectNone(()=>true); + expect(fixture.componentInstance.result().figure?.data[0]['x']).toEqual(general().filas.map(r=>r['n'])); + }); + it('no declara ni consulta capacidades ausentes; no acepta ronda',()=>{ + fixture.componentRef.setInput('indicador',{...item,filtros:undefined});fixture.detectChanges();request().flush(general());fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('select')).toBeNull();fixture.componentInstance.changeDimension('grupo_edad');http.expectNone(()=>true); + }); + it('cambio de periodo cancela transporte y consulta dimensión con el nuevo periodo',()=>{ + fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');const old=request(); + fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'explicit',periodos:['2026-S1']}});fixture.detectChanges();expect(old.cancelled).toBe(true); + const q=request();expect(q.request.params.get('periodos')).toBe('2026-S1');const data=structuredClone(age);data.periodos=['2026-S1'];data.filas.forEach(r=>r.periodo='2026-S1');q.flush(data); + expect(fixture.componentInstance.result().status).toBe('ready'); + }); + it('identidades separan dimensión, filtros, versión, revisión, dominio y general',()=>{ + const keys=[snapshotKey('cacu',item,applied),snapshotKey('cacu',item,applied,{estrato:'grupo_edad'}),snapshotKey('cacu',item,applied,{estrato:'estatus_seguimiento'}),snapshotKey('cacu',item,{...applied,revision:2}),snapshotKey('cama',item,applied),snapshotKey('cacu',{...item,version:'next'},applied),snapshotKey('cacu',item,applied,{filtros:['grupo_edad:25-34']})];expect(new Set(keys).size).toBe(keys.length); + const snapshots=TestBed.inject(IndicadoresSnapshots); + snapshots.datos('cacu',item.id,'semestre',['2025-S2'],item.version,{estrato:'grupo_edad',filtros:['grupo_edad:25-34']}).subscribe(); + const q=request();expect(q.request.params.get('filtro')).toBe('grupo_edad:25-34');expect(q.request.params.get('estrato')).toBe('grupo_edad');q.flush(age); + expect(snapshots.reading('cacu',item,applied)).toBeUndefined(); + }); + it('error de estrato no sustituye valores del Resumen y permite reintentar',()=>{ + fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');request().flush({}, {status:400,statusText:'Pending'}); + expect(fixture.componentInstance.result().status).toBe('error');fixture.componentInstance.requestFigure();request().flush(age);expect(fixture.componentInstance.result().status).toBe('ready'); + expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general()); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.spec.ts b/src/app/features/indicadores/indicadores-stratified.spec.ts new file mode 100644 index 0000000..9a1b389 --- /dev/null +++ b/src/app/features/indicadores/indicadores-stratified.spec.ts @@ -0,0 +1,63 @@ +import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json'; +import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; +import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified'; +import { DimensionEstrato, Indicador } from './indicadores.models'; + +const age = { ...ageJson, tipo_periodo: 'semestre' as const }; +const status = { ...statusJson, tipo_periodo: 'semestre' as const }; +const item: Indicador = { id: 'future', titulo: '', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] }; +describe('Contratos simulados de estratificación de los analistas', () => { + it('se habilita por capacidades, sin registrar IDs ni consultar dimensiones ausentes', () => { + expect(stratifiedCapabilities(item)).toEqual([]); + expect(stratifiedCapabilities({ ...item, filtros: [{ estrato:'grupo_edad',etiqueta:'Edad',valores:[{valor:'25-34',etiqueta:'25-34'}] },{estrato:'ronda',etiqueta:'Ronda',valores:[]}]})).toEqual(['grupo_edad']); + expect(stratifiedCapabilities({ ...item, contrato:'C1',filtros:[{estrato:'grupo_edad',etiqueta:'Edad',valores:[]}]})).toEqual([]); + }); + it.each([age,status])('conserva filas, orden y supresión de $estrato, sin totales inferidos', fixture => { + const original = structuredClone(fixture); + const { figure,cells } = stratifiedBars(fixture,fixture.estrato as DimensionEstrato,'2025-S2','claro'); + expect(figure.data.map(t => t['name'])).toEqual(fixture.valores_estrato.map(s => (fixture.etiquetas_estrato as Record)[s].replace('<','<'))); + expect(figure.data[0]['y']).toEqual(['Normal','ASC-US','LIEBG','ASC-H','LIEAG','Carcinoma in situ','Sin dato']); + expect(cells.filter(c => c.status === 'Suprimido').length).toBe(fixture.filas.filter(r => r.suprimido === 1).length); + expect(cells.filter(c => c.status === 'Suprimido').every(c => c.value === null)).toBe(true); + expect(fixture).toEqual(original); expect(figure.layout['meta']).toBeUndefined(); + }); + it('distingue cero explícito, nulo, fila ausente y supresión; nunca suma estratos', () => { + const data = structuredClone(age); data.filas[0].n=0; data.filas[0].suprimido=0; + data.filas[7].n=null; data.filas[7].suprimido=0; data.filas.splice(14,1); + const { cells,figure } = stratifiedBars(data,'grupo_edad','2025-S2','oscuro'); + expect(cells[0]).toMatchObject({ value:0,status:'Publicado' }); + expect(cells.some(c => c.status === 'No disponible')).toBe(true); + expect((figure.data[0]['x'] as unknown[])[1]).toBeNull(); + }); + it('pone categorías desconocidas al final con clave literal, sin asignarles padre', () => { + const data=structuredClone(age); data.filas.unshift({ ...data.filas[0],categoria:'NEGATIVO',orden:-1,n:7,suprimido:0 }); + expect((stratifiedBars(data,'grupo_edad','2025-S2','claro').figure.data[0]['y'] as string[]).at(-1)).toBe('NEGATIVO'); + expect(stratifiedBars(data,'grupo_edad','2025-S2','claro',{parent:'Anormal'}).cells.some(c=>c.category==='NEGATIVO')).toBe(false); + }); + it('filtra padre e hijo usando relaciones explícitas; restaurar conserva todos los valores', () => { + const all=stratifiedBars(age,'grupo_edad','2025-S2','claro'); + const parent=stratifiedBars(age,'grupo_edad','2025-S2','claro',{parent:'Anormal'}); + expect([...new Set(parent.cells.map(c=>c.category))]).toEqual(['LIEBG','ASC-H','LIEAG','Carcinoma in situ']); + const child=stratifiedBars(age,'grupo_edad','2025-S2','claro',{parent:'Anormal',category:'LIEAG'}); + expect(child.cells).toHaveLength(7); expect(child.cells.every(c=>c.category==='LIEAG')).toBe(true); + expect(child.cells).toEqual(all.cells.filter(c=>c.category==='LIEAG')); + expect(stratifiedBars(age,'grupo_edad','2025-S2','claro')).toEqual(all); + }); + it('el grupo estadístico se toma del reporte y no del padre visual ni de un ID fijo', () => { + const data = { ...structuredClone(age), grupos: { COHORTE: 'Cohorte publicada' } }; + data.filas.forEach(row => row.grupo = 'COHORTE'); + const cells = stratifiedBars(data,'grupo_edad','2025-S2','claro',{parent:'Anormal'}).cells; + expect([...new Set(cells.map(c => c.category))]).toEqual(['LIEBG','ASC-H','LIEAG','Carcinoma in situ']); + }); + it.each(['duplicate','negative','nan','bad-suppression','period','dimension','group'])('rechaza %s sin representar un cero', kind => { + const data=structuredClone(age); + if(kind==='duplicate') data.filas.push(data.filas[0]); + if(kind==='negative') data.filas[0].n=-1; + if(kind==='nan') data.filas[0].n=NaN; + if(kind==='bad-suppression') data.filas[1].n=2; + if(kind==='group') data.filas[0].grupo='ANORMAL'; + if(kind==='period') data.periodos=['2026-S1']; + if(kind==='dimension') data.estrato='ronda'; + expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.ts b/src/app/features/indicadores/indicadores-stratified.ts new file mode 100644 index 0000000..8321155 --- /dev/null +++ b/src/app/features/indicadores/indicadores-stratified.ts @@ -0,0 +1,64 @@ +import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { DonutSelection } from './indicadores-donut-drilldown'; +import { c2Color, c2Theme } from './indicadores-c2-palette'; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] { + return item.contrato === 'C2' && Array.isArray(item.filtros) + ? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d + && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 + && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; +} +export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } +export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } { + if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period + || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos']) + || Object.keys(data['grupos']).length !== 1 + || !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length + || !data['valores_estrato'].every(v => typeof v === 'string') + || new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida'); + const strata = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; + const statisticalGroup = Object.keys(data['grupos'])[0]; + if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); + const catalog = data['categorias'], groups = data['grupos_de_categoria']; + const entries = new Map(); + const rows = new Map>(); + for (const row of data.filas) { + const id = row['categoria'], stratum = row['estrato'], n = row['n']; + if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id + || typeof stratum !== 'string' || !strata.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) + || ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida'); + const key = JSON.stringify([id, stratum]); + if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas'); + rows.set(key, row); + const meta = record(catalog[id]) ? catalog[id] : {}; + entries.set(id, { order: row['orden'], label: typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id, + color: typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined, + parent: typeof meta['grupo'] === 'string' && typeof groups[meta['grupo']] === 'string' ? groups[meta['grupo']] as string : undefined }); + } + // Unknown categories are appended, retaining their published relative order. + const categories = [...entries].sort(([a, x], [b, y]) => Number(!Object.hasOwn(catalog, a)) - Number(!Object.hasOwn(catalog, b)) || x.order - y.order) + .filter(([, c]) => (!selection.parent || c.parent === selection.parent) && (!selection.category || c.label === selection.category)); + if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas'); + const cells: StratifiedCell[] = []; + const theme = c2Theme(tema); + const figure: PlotlyFigure = { data: strata.map((s, series) => { + const selected = categories.map(([id, c]) => { + const row = rows.get(JSON.stringify([id, s])); + const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible'; + const value = status === 'Publicado' ? row!['n'] as number : null; + cells.push({ category: c.label, stratum: labels[s] as string, value, status }); + return value; + }); + return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)), + marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, + hovertemplate: '%{y}
%{x}%{fullData.name}' }; + }), layout: { title: { text: 'Distribución estratificada · ' + period }, barmode: 'group', autosize: true, + height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background, + font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 }, + xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, + yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true }, + legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } }; + return { figure, cells }; +} diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html new file mode 100644 index 0000000..920ac80 --- /dev/null +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -0,0 +1,53 @@ +

Seguimiento · {{ domainLabel }}

+@if (dominio !== 'cacu') { +

El seguimiento aún no está disponible.

+
+ + + +
Columnas propuestas para revisión.
Paciente / identificaciónProceso o etapaEstadoFecha de referenciaResponsableAcciones
No hay registros de seguimiento disponibles.
+
+} @else { +
+ + + + + +
+ @if (status === 'loading') {

Cargando seguimiento…

} + @if (status === 'pending') {

El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.

} + @if (message && status !== 'pending') {

{{ message }}

} + @if (status === 'error' || status === 'pending') { } + @if (data; as response) { + @if (response.simulado) {

Datos simulados — uso de demostración

} +

Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.

+ @if (provisional) {

Las reglas de selección son provisionales.

} +
+ + + + + @for (item of response.items; track item.id_seudonimo) { + + + + + + + } @empty { } + +
Resultados disponibles por paciente
Identificador seudónimoGrupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ item.id_seudonimo }}{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }}@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad }} } @else { No disponible }@if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible }{{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
No hay registros para los filtros aplicados.
+
+ + } +} diff --git a/src/app/features/indicadores/indicadores-tracking.scss b/src/app/features/indicadores/indicadores-tracking.scss new file mode 100644 index 0000000..d11eaeb --- /dev/null +++ b/src/app/features/indicadores/indicadores-tracking.scss @@ -0,0 +1,18 @@ +:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere; + background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +h2 { font-size: 1.5rem; margin-top: 0; } +p { color: var(--issste-text-secondary); } +form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; } +label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; } +input, select, button { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; + padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; } +button { cursor: pointer; } button:disabled { opacity: .5; cursor: default; } +input:focus-visible, select:focus-visible, button:focus-visible, .tracking-table:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } +.simulation { padding: 1rem; border: 2px solid var(--issste-accent); font-weight: 700; color: var(--issste-text); } +.tracking-table { overflow-x: auto; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +table { width: 100%; min-width: 65rem; border-collapse: collapse; background: var(--issste-surface); } +caption { text-align: start; padding: 1rem; } +th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px solid var(--issste-border); } +th { background: var(--issste-background); font-weight: 600; } +small { display: block; margin-top: .35rem; } +nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; } diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts new file mode 100644 index 0000000..b0dba78 --- /dev/null +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -0,0 +1,81 @@ +import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; +import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; +import { latestStudy, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { Dominio } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; + +@Component({ + selector: 'app-indicadores-tracking', + imports: [FormsModule], + templateUrl: './indicadores-tracking.html', + styleUrl: './indicadores-tracking.scss', +}) +export class IndicadoresTracking implements OnChanges { + @Input({ required: true }) domainLabel = ''; + @Input() dominio: Dominio = 'tea'; + @Input() active = false; + private readonly service = inject(CacuSeguimientoService); + private readonly indicators = inject(IndicadoresService); + private readonly destroy = inject(DestroyRef); + private readonly changeDetector = inject(ChangeDetectorRef); + private readonly requests = new Subject(); + private initialized = false; + private previousDomain?: Dominio; + status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle'; + message = ''; + data?: SeguimientoResponse; + statuses: SeguimientoStatus[] = []; + private metadataLoaded = false; + categories: Record = {}; + draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 }; + private applied: SeguimientoQuery = { ...this.draft }; + readonly latestStudy = latestStudy; + get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); } + constructor() { + this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe( + map(data => ({ data, message: '', status: 'ready' as const })), + catchError(error => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const, + message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.' + : error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' }))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => { + if (!result) return; + this.changeDetector.markForCheck(); + this.status = result.status; this.data = result.data; this.message = result.message; + if (result.data) { + const data = result.data; + this.statuses = data.estatus_disponibles; + this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size }; + this.draft = { ...this.applied }; + if (!this.metadataLoaded) { + this.metadataLoaded = true; + this.indicators.metadatos('cacu', 'cacu_eu7').pipe(catchError(() => of(undefined)), takeUntilDestroyed(this.destroy)).subscribe(meta => { + if (meta?.categorias) this.categories = meta.categorias; + this.changeDetector.markForCheck(); + }); + } + } + }); + } + ngOnChanges() { + if (this.previousDomain !== this.dominio) { + this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined; + this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft }; + } + if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); } + } + private load(q: SeguimientoQuery) { + if (this.dominio !== 'cacu') return; + if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; } + this.status = 'loading'; this.message = ''; this.data = undefined; this.applied = { ...q }; this.requests.next(q); + } + apply() { this.load({ ...this.draft, page: 1 }); } + retry() { this.load(this.applied); } + navigate(page: number) { + if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return; + this.load({ ...this.applied, page }); + } + cytologyLabel(code: string | null) { return code === null ? 'No disponible' : this.categories[code]?.etiqueta ?? code; } +} diff --git a/src/app/features/indicadores/indicadores-visibility.spec.ts b/src/app/features/indicadores/indicadores-visibility.spec.ts index 5aacf8e..d875b55 100644 --- a/src/app/features/indicadores/indicadores-visibility.spec.ts +++ b/src/app/features/indicadores/indicadores-visibility.spec.ts @@ -131,6 +131,22 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await idle(); expect(panel.result()).toBe(result); http.expectNone(() => true); }); + it('pestañas ocultan regiones sin activar tarjetas diferidas ni recargar las ya consultadas', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); + notify(); await confirm(); respond(); await render(); + const before = cards(), panel = panels()[0], result = panel.result(); + for (const section of ['seguimiento', 'datos'] as const) { + page.changeSection(section); await render(); + // Even stale geometry/observer notifications cannot activate hidden cards. + positions(cards().map(() => [200, 0])); notify(1); await idle(); + expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true); + } + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); + page.changeSection('resumen'); await idle(); + expect(cards()).toEqual(before); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); + expect(cards().map(card => card.visible)).toEqual([true, false, false, false, false]); + http.expectNone(() => true); + }); it('filtro fuera de vista conserva host y consulta únicamente el último aplicado al regresar', async () => { await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart'); @@ -215,6 +231,11 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart, host = chart.host.nativeElement; expect(runtime.react).toHaveBeenCalledTimes(1); positions([[-1000, 0]]); notify(0, false); await idle(); expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled(); + for (const section of ['seguimiento', 'datos', 'resumen'] as const) { + page.changeSection(section); await idle(); + expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled(); + expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true); + } positions([[200, 0]]); notify(); await idle(); expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true); fixture.destroy(); expect(runtime.purge).toHaveBeenCalledWith(host); }); diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 3cb1bea..90e08be 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -10,10 +10,28 @@ export function requireDominio(value: unknown): Dominio { } export interface Indicador { id: string; + version?: string; titulo: string; contrato: string; figuras: string[]; tipos_periodo: TipoPeriodo[]; + filtros?: IndicadorFiltro[]; +} +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento'; +export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } +export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } +export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; } +export interface IndicadorDatosEstratificados extends IndicadorDatos { + estrato: DimensionEstrato; + valores_estrato: string[]; + etiquetas_estrato: Record; + totales_estrato?: EstratoTotal[]; +} +export interface IndicadorMetadatos { + referencias?: { tipo: string; etiqueta: string; ref: string | null }[]; + poblaciones?: { grupo: string; codigo: string; descripcion: string }[]; + categorias?: Record; + [key: string]: unknown; } // Keep the complete HTTP figure, including future attributes and interpretation notes. diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 96c363c..0dcfb02 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -107,7 +107,7 @@ describe('contrato datos exclusivo de KPI', () => { TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v); const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos'); expect(req.request.params.keys()).toEqual(['periodos']); expect(req.request.params.get('periodos')).toBe('2025-01'); - const payload = { id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'mes', periodos: ['2025-01'], filas: [{ n: null, suprimido: 1 }], notas: ['Nota'] }; + const payload = { id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'mes', periodos: ['2025-01'], filas: [{ periodo: '2025-01', n: null, suprimido: 1 }], notas: ['Nota'] }; req.flush(payload); expect(result).toEqual(payload); http.verify(); }); it('Todos omite periodos y rechaza respuesta de otro indicador', () => { diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index 47fe164..03f74f5 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -1,7 +1,7 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; -import { Dominio, IndicadorDatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models'; +import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models'; function record(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); @@ -15,6 +15,7 @@ export class IndicadoresService { if (!Array.isArray(value) || !value.every(item => record(item) && typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string' && typeof item['contrato'] === 'string' && Array.isArray(item['figuras']) + && (item['version'] === undefined || typeof item['version'] === 'string') && item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0) && new Set(item['figuras']).size === item['figuras'].length && Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0 @@ -26,21 +27,44 @@ export class IndicadoresService { return value as Indicador[]; })); } - datos(dominio: Dominio, indicador: string, tipo: 'semestre' | 'mes', periodos?: string[]) { + metadatos(dominio: Dominio, indicador: string) { + return this.http.get(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(value => { + if (!record(value)) throw new Error('Metadatos inválidos'); + for (const field of ['referencias', 'poblaciones']) { + const list = value[field]; + if (list !== undefined && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias' + ? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string') + : typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos'); + } + return value as IndicadorMetadatos; + })); + } + datos(dominio: Dominio, indicador: string, tipo: 'semestre' | 'mes', periodos?: string[], scope: DatosScope = {}) { const domain = requireDominio(dominio); if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) { throw new Error('Periodos inválidos'); } let params = new HttpParams(); + if (scope.estrato) { + if (!['grupo_edad', 'estatus_seguimiento'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); + params = params.set('estrato', scope.estrato); + } + for (const filtro of scope.filtros ?? []) params = params.append('filtro', filtro); if (periodos) params = params.set('periodos', [...new Set(periodos)].join(',')); return this.http.get(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => { if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string' - || !['mes', 'semestre'].includes(value['tipo_periodo'] as string) + || value['tipo_periodo'] !== tipo || !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string') || !Array.isArray(value['filas']) || !value['filas'].every(record) || (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) { throw new Error('Respuesta de datos inválida'); } + const publishedPeriods = value['periodos'] as string[]; + if ((value['estrato'] ?? undefined) !== scope.estrato) throw new Error('Dimensión recibida distinta de la solicitada'); + if ((periodos && publishedPeriods.some(p => !periodos.includes(p))) + || value['filas'].some(row => typeof row['periodo'] !== 'string' || !publishedPeriods.includes(row['periodo']))) { + throw new Error('Los datos recibidos no corresponden a los periodos solicitados'); + } return value as unknown as IndicadorDatos; })); } diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts index e5015ab..03f0b09 100644 --- a/src/app/shared/plotly/plotly-chart.ts +++ b/src/app/shared/plotly/plotly-chart.ts @@ -22,7 +22,7 @@ import { PLOTLY_LOADER } from './plotly-runtime'; } `, - styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-width: var(--plot-min-width, 0px); min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, + styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-width: var(--plot-min-width, 0px); min-height: var(--plot-height, 620px); visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`, }) export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input() showNotes = true; @@ -31,6 +31,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); readonly widthChanged = output(); + readonly plotClick = output(); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); get notes(): string[] { const annotations = this.figure?.layout['annotations']; @@ -56,7 +57,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { this.status.set(state); if (state === 'error') this.renderError.emit(); - }); + }, event => this.plotClick.emit(event)); if (typeof ResizeObserver !== 'undefined') { this.observer = new ResizeObserver(this.windowResize); this.observer.observe(this.host.nativeElement); diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts index 7d6e7cf..da71695 100644 --- a/src/app/shared/plotly/plotly-controller.spec.ts +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -31,6 +31,22 @@ describe('PlotlyController async', () => { expect(host.style.visibility).toBe('visible'); expect(state).toHaveBeenLastCalledWith('ready'); }); + it('suscribe click una vez, ignora clicks durante react y retira listener al destruir', async () => { + let listener!: (event: unknown) => void; + const on = vi.fn((_name, callback) => { listener = callback; }); + const removeListener = vi.fn(), click = vi.fn(); + Object.assign(host, { on, removeListener }); + controller = new PlotlyController(host, () => Promise.resolve(plotly), state, click); + controller.setFigure(fig(1)); await settle(); + listener({ points: [1] }); expect(click).toHaveBeenCalledTimes(1); + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + controller.setFigure(fig(2)); await settle(); listener({ points: [2] }); + expect(click).toHaveBeenCalledTimes(1); + pending.resolve(); await settle(); expect(on).toHaveBeenCalledTimes(1); + listener({ points: [3] }); expect(click).toHaveBeenCalledTimes(2); + controller.destroy(); expect(removeListener).toHaveBeenCalledWith('plotly_click', listener); + listener({ points: [4] }); expect(click).toHaveBeenCalledTimes(2); + }); it('desactiva el envío externo sin alterar el JSON ni las opciones locales recibidas', async () => { const figure: PlotlyFigure = { ...fig(1), diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts index 9ac0add..2a98f3f 100644 --- a/src/app/shared/plotly/plotly-controller.ts +++ b/src/app/shared/plotly/plotly-controller.ts @@ -1,6 +1,11 @@ import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; import { PlotlyRuntime } from './plotly-runtime'; +interface EventHost extends HTMLElement { + on?: (name: string, listener: (event: unknown) => void) => void; + removeListener?: (name: string, listener: (event: unknown) => void) => void; +} + // One serialized queue owns the host. A completed stale operation cannot expose // its graph or overwrite a newer react operation. Resize uses the same queue. export class PlotlyController { @@ -12,8 +17,13 @@ export class PlotlyController { private resizePending = false; private plotly?: PlotlyRuntime; private frameCount = 0; + private listenerAttached = false; + private readonly handleClick = (event: unknown) => { + if (!this.destroyed && !this.busy && this.rendered === this.version) this.click?.(event); + }; constructor(private host: HTMLElement, private load: () => Promise, - private state: (state: 'loading' | 'ready' | 'error') => void) {} + private state: (state: 'loading' | 'ready' | 'error') => void, + private click?: (event: unknown) => void) {} setFigure(figure: PlotlyFigure) { if (this.destroyed) return; @@ -30,6 +40,8 @@ export class PlotlyController { } destroy() { this.destroyed = true; + if (this.listenerAttached) (this.host as EventHost).removeListener?.('plotly_click', this.handleClick); + this.listenerAttached = false; this.host.style.visibility = 'hidden'; this.plotly?.purge(this.host); } @@ -52,6 +64,10 @@ export class PlotlyController { showSendToCloud: false, modeBarButtonsToRemove: ['sendChartToCloud'], }); + if (!this.destroyed && !this.listenerAttached && this.click && (this.host as EventHost).on) { + (this.host as EventHost).on!('plotly_click', this.handleClick); + this.listenerAttached = true; + } if (this.destroyed) break; if (version !== this.version) continue; if (figure.frames?.length) { diff --git a/tsconfig.spec.json b/tsconfig.spec.json index 9c8efb9..2eab4db 100644 --- a/tsconfig.spec.json +++ b/tsconfig.spec.json @@ -3,6 +3,7 @@ { "extends": "./tsconfig.json", "compilerOptions": { + "resolveJsonModule": true, "types": [ "vitest/globals" ] From 9639423a3226fd2ef7051a2ccc1030f2de337054 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 23 Oct 2026 01:18:24 -0600 Subject: [PATCH 27/51] =?UTF-8?q?feat(indicadores):=20completa=20metadatos?= =?UTF-8?q?=20y=20navegaci=C3=B3n=20multiperiodo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores/cacu-seguimiento.models.ts | 2 +- .../indicadores/cacu-seguimiento.service.ts | 2 +- .../indicadores/cacu-seguimiento.spec.ts | 26 ++- .../indicador-catalog-card.spec.ts | 19 ++ .../indicadores/indicador-catalog-card.ts | 29 ++- .../indicadores/indicador-figure-card.html | 13 +- .../indicadores/indicador-figure-card.scss | 7 + .../indicadores/indicador-figure-card.spec.ts | 52 ++++- .../indicadores/indicador-figure-card.ts | 27 ++- .../indicadores/indicador-figure-panel.ts | 124 ++++++++++-- .../indicadores/indicador-metadata.scss | 14 ++ .../indicadores/indicador-metadata.spec.ts | 93 ++++++++- .../indicadores/indicador-metadata.ts | 44 ++++- .../indicadores-c2-adapter.spec.ts | 31 ++- .../indicadores-donut-drilldown.ts | 42 +++- .../indicadores-donut-periods.spec.ts | 183 ++++++++++++++++++ .../indicadores/indicadores-donut-periods.ts | 58 ++++++ .../indicadores/indicadores-methodology.ts | 9 +- .../indicadores/indicadores-page.spec.ts | 6 +- .../indicadores/indicadores-search.spec.ts | 4 +- .../indicadores-stratified-panel.spec.ts | 35 ++++ .../indicadores/indicadores-tracking.html | 6 +- .../indicadores/indicadores.models.ts | 20 +- .../indicadores/indicadores.service.spec.ts | 64 ++++++ .../indicadores/indicadores.service.ts | 24 ++- 25 files changed, 864 insertions(+), 70 deletions(-) create mode 100644 src/app/features/indicadores/indicador-metadata.scss create mode 100644 src/app/features/indicadores/indicadores-donut-periods.spec.ts create mode 100644 src/app/features/indicadores/indicadores-donut-periods.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index 956243e..d6f1b6c 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -4,7 +4,7 @@ export interface SeguimientoPaciente { id_seudonimo: string; grupo_edad: string; estatus: SeguimientoStatus; - ultima_citologia: { fecha: string; bethesda: string | null; calidad: string } | null; + ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null; dias_toma_diagnostico: number | null; prioridad: SeguimientoStatus | null; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index 1b86c8e..a9d9924 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -21,7 +21,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { || !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => { if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; const c = item['ultima_citologia'], h = item['ultimo_vph']; - return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && typeof c['calidad'] === 'string') + return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string')) && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); })) throw new Error('Respuesta de seguimiento inválida'); diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index 7c8663c..42c509c 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -16,17 +16,35 @@ 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('consulta solo al abrir CaCu, presenta simulación, nulos, calidad y genotipo sin prioridad clínica', () => { + it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => { fixture.detectChanges(); http.expectNone(()=>true); respond(); const root:HTMLElement=fixture.nativeElement; - expect(root.textContent).toContain('Datos simulados — uso de demostración'); + expect(root.textContent).not.toContain('Datos simulados — uso de demostración'); + expect(root.textContent).not.toContain('Las reglas de selección son provisionales'); + expect(root.textContent).toContain('Ventana consultada:'); expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado'); expect(root.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(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15'); expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull(); }); + it('acepta calidad nula por paciente y la presenta de forma neutra sin rechazar la página', () => { + const items = fixtureData.items.map((item, index) => index === 2 + ? {...item, ultima_citologia:{...item.ultima_citologia!, calidad:null}} + : item); + expect(seguimientoResponse({...fixtureData, items}).items).toHaveLength(fixtureData.items.length); + fixture.componentRef.setInput('active',true); fixture.detectChanges(); + http.expectOne(r=>r.url==='/cacu/seguimiento').flush({...fixtureData,items}); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); + const rows = fixture.nativeElement.querySelectorAll('tbody tr'); + expect(rows).toHaveLength(fixtureData.items.length); + expect(rows[2].textContent).toContain('Calidad: —'); + expect(rows[2].textContent).not.toContain('Calidad: null'); + }); it('página y filtros conservan los parámetros aplicados; navegación por pestañas no repite GET', () => { respond(); fixture.componentInstance.draft={corte:'2026-09-30',meses:6,estatus:'VIGILANCIA',page:1,page_size:10}; fixture.componentInstance.apply(); let req=http.expectOne(r=>r.url==='/cacu/seguimiento'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('estatus')).toBe('VIGILANCIA'); @@ -49,11 +67,15 @@ describe('Seguimiento CaCu con contrato de demostración', () => { it('no activa registros reales ni acepta respuestas malformadas', () => { expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow(); expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow(); + expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow(); open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); }); it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => { fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true); expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible'); + expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.'); + expect(fixture.nativeElement.querySelector('table')).not.toBeNull(); + expect(fixture.nativeElement.querySelector('caption')).toBeNull(); }); it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => { const service=TestBed.inject(CacuSeguimientoService); diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index b221ae9..27f3a03 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -78,6 +78,25 @@ describe('UX-06E.D.2.1 selector de representación', () => { fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); }); + it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => { + fixture.componentRef.setInput('indicador', { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2', + figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] }); + fixture.detectChanges(); + const helps = fixture.nativeElement.querySelectorAll('.methodology-toggle') as NodeListOf; + expect(helps).toHaveLength(2); + helps[0].click(); helps[1].click(); fixture.detectChanges(); + const metadata = http.expectOne('/cacu/indicadores/cacu_eu7/metadatos'); + http.expectNone('/cacu/indicadores/cacu_eu7/metadatos'); + metadata.flush({ figuras_detalle: [ + { figura: 'fig_c2_donas', descripcion: null, como_leer: ['Instrucción para donas.'] }, + { figura: 'fig_c2_barras', descripcion: null, como_leer: ['Instrucción para barras.'] }, + { figura: 'otra', descripcion: null, como_leer: ['No debe asignarse.'] }, + ] }); + fixture.detectChanges(); + const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(e => e.componentInstance as IndicadorFigureCard); + expect(cards.map(card => card.interpretation)).toEqual([['Instrucción para donas.'], ['Instrucción para barras.']]); + expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true); + }); it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => { open(); const first = request('f'); expect(select().disabled).toBe(false); expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 2fcddda..fb93ded 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -1,11 +1,11 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChanges, OnDestroy, output, untracked, ViewChild } from '@angular/core'; -import { Subscription } from 'rxjs'; +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, Tema } from './indicadores.models'; +import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; import { IndicadorFigurePanel } from './indicador-figure-panel'; @@ -15,6 +15,7 @@ import { dualFigures } from './indicadores-dual-figures'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { filterCompatibility } from './indicadores-memory'; import { DonutSelection } from './indicadores-donut-drilldown'; +import { IndicadoresService } from './indicadores.service'; @Component({ selector: 'app-indicador-catalog-card', @@ -49,7 +50,7 @@ import { DonutSelection } from './indicadores-donut-drilldown'; @for (figure of displayFigures; track panelIdentity(figure)) {
@if (isDual) {

{{ figureDisplayName(figure, indicador.figuras) }}

} - +
} @@ -87,6 +88,10 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { private readonly snapshots = inject(IndicadoresSnapshots); private numericSubscription?: Subscription; private numericKey = ''; + private readonly indicators = inject(IndicadoresService); + private metadataSubscription?: Subscription; + private metadataKey = ''; + metadata?: IndicadorMetadatos; private activatedKey = ''; constructor() { effect(() => { @@ -112,7 +117,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { this.numericSubscription?.unsubscribe(); this.numericSubscription = this.snapshots.read(this.dominio, this.indicador, this.applied).subscribe(); } - ngOnDestroy() { this.numericSubscription?.unsubscribe(); } + ngOnDestroy() { this.numericSubscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); } readonly figureDisplayName = figureDisplayName; @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; @@ -146,6 +151,9 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { const identity = indicatorIdentity(this.dominio, this.indicador.id); if (identity === this.identity) { this.updateNumeric(); return; } this.identity = identity; + this.metadataSubscription?.unsubscribe(); + this.metadata = undefined; + this.metadataKey = ''; const id = identityElementId(identity); this.titleId = id + '-title'; this.contentId = id + '-content'; @@ -158,4 +166,17 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { this.updateNumeric(); this.changeDetector.markForCheck(); } + loadMetadata() { + const key = JSON.stringify([this.dominio, this.indicador.id]); + if (this.metadataKey === key) return; + this.metadataKey = key; + this.metadataSubscription?.unsubscribe(); + this.metadataSubscription = this.indicators.metadatos(this.dominio, this.indicador.id) + .pipe(catchError(() => of(undefined))).subscribe(value => { + if (this.metadataKey !== key) return; + if (!value) this.metadataKey = ''; + this.metadata = value; + this.changeDetector.markForCheck(); + }); + } } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index bf671f4..64c4b38 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -3,7 +3,7 @@ @@ -75,7 +75,16 @@ } - + @if (state.status === 'ready' && state.donutLegend?.length) { +
+ @for (entry of state.donutLegend; track entry.label) { + + {{ entry.label }} + + } +
+ } + @if (state.footnotes?.length) {
@for (note of state.footnotes; track $index) {

{{ note }}

} diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index cc5c6ae..050a7ec 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -85,6 +85,13 @@ .donut-legend button:focus-visible, .donut-restore:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; } +.donut-static-legend { + display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: .25rem .9rem; + padding: .5rem .75rem .25rem; color: var(--issste-text); box-sizing: border-box; +} +.dark .donut-static-legend { color: #eef1f7; } +.donut-static-legend__item { display: flex; align-items: center; gap: .5rem; min-height: 32px; max-width: 100%; + font: var(--mat-sys-body-small); overflow-wrap: anywhere; } @media (prefers-reduced-motion: reduce) { .donut-children-region, .donut-children-region.expanded { transition: none; transform: none; } } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index a075e94..1919dd2 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -7,7 +7,7 @@ import { presentationFigure } from './indicadores.presentation'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; import { donutFixture } from './indicadores-donut-drilldown.testing'; -import { donutHierarchy } from './indicadores-donut-drilldown'; +import { donutHierarchy, donutLegend } from './indicadores-donut-drilldown'; describe('IndicadorFigureCard', () => { const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] }; @@ -91,6 +91,21 @@ describe('IndicadorFigureCard', () => { state({ status: 'ready', figure: structuredClone(figure), presentationFigure: figure, hierarchy }); await settle(); expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.plot')).toBe(host); }); + it('homologa la dona simple con leyenda HTML superior sin alterar categorías ni valores', async () => { + const { figure } = donutFixture(); + figure.data.pop(); + fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); + const copy = presentationFigure(figure, { indicador: selected.id, figura: 'fig_c2_donas', tema: 'claro' }); + const legend = donutLegend(copy)!; + state({ status: 'ready', figure, presentationFigure: copy, donutLegend: legend }); await settle(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(fixture.nativeElement.querySelectorAll('.donut-static-legend__item')).toHaveLength(3); + expect(fixture.nativeElement.querySelector('.donut-static-legend').textContent).toContain('A'); + expect(chart.figure.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } }); + expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); + expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']); + expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']); + }); it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => { const { figure, data } = donutFixture(); state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data) }); @@ -292,6 +307,41 @@ describe('IndicadorFigureCard', () => { expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls')) .toBe(fixture.nativeElement.querySelector('.methodology-detail').id); }); + it('usa instrucciones exactas en orden y conserva caracteres especiales como texto', () => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); + fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_donas', descripcion: 'No repetir', como_leer: [ + 'Primera línea ', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final', + ] }] }); + state({ status: 'idle' }); + const lines = fixture.nativeElement.querySelectorAll('.methodology-detail li'); + expect([...lines].map((line: Element) => line.textContent)).toEqual([ + 'Primera línea ', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final', + ]); + expect(fixture.nativeElement.querySelector('img')).toBeNull(); + expect(fixture.componentInstance.interpretation).toEqual([...lines].map((line: Element) => line.textContent)); + }); + it.each([ + ['sin coincidencia', [{ figura: 'otra_figura', descripcion: null, como_leer: ['No corresponde.'] }]], + ['vacías', [{ figura: 'fig_c2_apiladas', descripcion: 'Sin instrucciones específicas.', como_leer: [] }]], + ['nulas', [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: null }]], + ])('mantiene fallback local con figuras_detalle %s', (_label, details) => { + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + fixture.componentRef.setInput('metadata', { figuras_detalle: details }); + state({ status: 'idle' }); + expect(fixture.componentInstance.interpretation).toContain('Las categorías corresponden a la distribución de cada grupo y periodo.'); + expect(fixture.componentInstance.interpretation).toContain('SIN_DATO, cuando aparece, es una categoría legítima de la representación.'); + }); + it('preserva íntegramente, sin filtrado semántico, instrucciones sobre supresión y categorías pequeñas', () => { + const instructions = ['Se ocultan categorías individuales pequeñas.', 'La supresión se determina por grupo.', 'Conclusión.']; + fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' }); + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: instructions }] }); + state({ status: 'idle' }); + expect(fixture.componentInstance.interpretation).toEqual(instructions); + expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((line: Element) => line.textContent)).toEqual(instructions); + }); it.each([ ['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index ad44b60..6ea8ab1 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -4,14 +4,14 @@ import { MatIconModule } from '@angular/material/icon'; import { MatCardModule } from '@angular/material/card'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatTooltipModule } from '@angular/material/tooltip'; -import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models'; +import { Dominio, hasNoVisibleValues, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { figureTitle } from './indicadores.presentation'; import { figureDisplayName } from './indicadores-figure-labels'; import { CategoryLabel } from './indicadores-axis-labels'; import { figureIdentity, identityElementId } from './indicadores-identities'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; -import { DonutHierarchy, DonutSelection, donutView } from './indicadores-donut-drilldown'; +import { contractInterpretation, figureMetadataInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; +import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown'; // The panel owns requests; the card receives the original and its presentation copy. export interface FigureState { @@ -21,7 +21,9 @@ export interface FigureState { footnotes?: readonly string[]; categoryLabels?: readonly CategoryLabel[]; minimumPlotWidth?: number; + donutLegend?: readonly DonutLegendEntry[]; plotWidth?: number; + plotHeight?: number; message?: string; hierarchy?: DonutHierarchy; source?: 'datos' | 'figuras'; @@ -78,8 +80,13 @@ export class IndicadorFigureCard implements OnChanges { } private updateDonut() { const { presentationFigure, hierarchy } = this.state; - this.chartFigure = presentationFigure && hierarchy - ? donutView(presentationFigure, hierarchy, this.activeParent, this.state.plotWidth) : presentationFigure; + // Empty pages retain the series' plot height as well. This is a derived + // layout copy; the original figure and its annotations remain available. + const source = presentationFigure && this.state.plotHeight + ? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure; + this.chartFigure = source && hierarchy + ? donutView(source, hierarchy, this.activeParent, this.state.plotWidth) + : source && this.state.donutLegend ? donutSimpleView(source) : source; } expandParent(parent: string) { if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent) @@ -108,6 +115,7 @@ export class IndicadorFigureCard implements OnChanges { else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label); } @Input() selected?: Indicador; + @Input() metadata?: IndicadorMetadatos; @Input({ required: true }) figuraId!: string; @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) tema!: Tema; @@ -117,6 +125,12 @@ export class IndicadorFigureCard implements OnChanges { if (typeof width === 'number') this.plotWidthChanged.emit(width); } readonly methodologyExpanded = signal(false); + readonly metadataRequested = output(); + toggleMethodology() { + const open = !this.methodologyExpanded(); + this.methodologyExpanded.set(open); + if (open && !this.metadata) this.metadataRequested.emit(); + } get methodologyId(): string { return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology'; } @@ -144,6 +158,7 @@ export class IndicadorFigureCard implements OnChanges { readonly periodInterpretation = PERIOD_INTERPRETATION; get interpretation(): readonly string[] { - return contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie')); + return figureMetadataInterpretation(this.metadata, this.figuraId) + ?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie')); } } diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 0219ae3..7fef5d0 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -2,7 +2,7 @@ import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal, import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; -import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, Tema } from './indicadores.models'; +import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; import { figurePresentation } from './indicadores.presentation'; import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile'; @@ -10,10 +10,11 @@ import { FigureState, IndicadorFigureCard } from './indicador-figure-card'; import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory'; import { httpMessage } from './indicadores-http'; import { figureIdentity, identityElementId } from './indicadores-identities'; -import { DonutHierarchy, DonutSelection, donutHierarchy, donutPeriod } from './indicadores-donut-drilldown'; +import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown'; import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; +import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; @Component({ selector: 'app-indicador-figure-panel', @@ -23,16 +24,34 @@ import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indica

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

Filtro general aplicado: {{ appliedSummary }}

@if (figuraId === 'fig_c2_barras' && capabilities.length) { - - @if (!singlePeriod) {

Selecciona un periodo para consultar la distribución estratificada.

} +
+ Distribución +
+ + +
+ @if (dimension && capabilities.length > 1) { +
+ @for (d of capabilities; track d) { + + } +
+ } +
+ @if (!singlePeriod) {

Selecciona un periodo para consultar la distribución estratificada.

} + } + @if (result().status === 'ready' && donutPages.length > 1) { + } + [metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" /> @if (dimension && result().status === 'ready') { @if (hasSuppressedCells) {

Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

} @if (hasMissingCells) {

Hay datos no disponibles; los espacios sin barra no representan un cero observado.

} @@ -49,8 +68,23 @@ import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indica :host { display: block; min-width: 0; } section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); } .applied-summary { color: var(--issste-text-secondary); overflow-wrap: anywhere; } - select { margin: .5rem; padding: .75rem; max-width: 100%; background: var(--issste-surface); color: var(--issste-text); } + .distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; } + .distribution-control legend { padding: 0; font-weight: 600; } + .distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; } + .distribution-dimensions { margin-top: .75rem; } + .distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem; + border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text); + font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; } + .distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; } + .distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; } + .distribution-toggle button:focus-visible, .distribution-dimensions button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + .distribution-note { margin: .5rem 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; } .cells { overflow: auto; max-height: 24rem; } th, td { text-align: start; padding: .5rem; } + .donut-periods { display: flex; align-items: center; justify-content: center; gap: .75rem; min-height: 48px; } + .donut-periods span { text-align: center; overflow-wrap: anywhere; } + .donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; } + .donut-periods button:disabled { opacity: .45; } + .donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; @@ -60,6 +94,7 @@ import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indica export class IndicadorFigurePanel implements OnChanges { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; + @Input() metadata?: IndicadorMetadatos; @Input({ required: true }) figuraId!: string; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @@ -67,6 +102,35 @@ export class IndicadorFigurePanel implements OnChanges { @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; @Input() localSelection: DonutSelection = {}; readonly hierarchySelected = output(); + readonly metadataRequested = output(); + donutPages: { period: string; state: FigureState }[] = []; + activeDonutPeriod?: string; + private donutIdentity = ''; + get donutPeriodIndex() { return this.donutPages.findIndex(p => p.period === this.activeDonutPeriod); } + changeDonutPeriod(step: number) { + if (this.result().status !== 'ready' || ![-1, 1].includes(step)) return; + const page = this.donutPages[this.donutPeriodIndex + step]; + if (!page) return; + this.activeDonutPeriod = page.period; + // Selection belongs to one page. Reset dependent category/stratum state + // even when the same labels exist in the following period. + this.hierarchySelected.emit({}); + this.result.set(this.refreshDonutPage(page.state)); + } + selectHierarchy(selection: DonutSelection) { + this.hierarchySelected.emit(selection.parent || selection.category + ? { ...selection, period: this.activeDonutPeriod ?? this.readySelection?.periodos?.[0] } : {}); + } + private refreshDonutPage(state: FigureState): FigureState { + const presentation = this.present(state.figure!, this.readySelection!, state.hierarchy); + return { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes }; + } + private activateDonutPages(pages: { period: string; state: FigureState }[]): FigureState { + const plotHeight = pages.some(p => p.state.hierarchy) ? 440 : undefined; + this.donutPages = pages.map(p => ({ ...p, state: { ...p.state, plotHeight } })); + this.activeDonutPeriod = pages.some(p => p.period === this.activeDonutPeriod) ? this.activeDonutPeriod : pages[0]?.period; + return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state; + } dimension: DimensionEstrato | '' = ''; cells: StratifiedCell[] = []; get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } @@ -79,8 +143,12 @@ export class IndicadorFigurePanel implements OnChanges { if (this.dimension === value) return; this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure(); } + chooseStratified() { + if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]); + } private presentStratified(data: IndicadorDatos): FigureState { - const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, this.localSelection); + const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {}; + const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local); this.cells = adapted.cells; return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id, tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }), @@ -96,6 +164,7 @@ export class IndicadorFigurePanel implements OnChanges { private generation = 0; private currentKey = ''; titleId = ''; + distributionAvailabilityId = ''; readonly result = signal({ status: 'idle' }); get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; } constructor() { @@ -112,7 +181,11 @@ export class IndicadorFigurePanel implements OnChanges { : of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef)) .subscribe(({ state, selection, revision, generation }) => { if (generation === this.generation && revision === this.applied?.revision) { - if (state.status === 'ready') this.readySelection = selection; + if (state.status === 'ready') { + this.readySelection = selection; + if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1 + ? selection.periodos[0] : state.figure && donutPeriod(state.figure); + } this.result.set(state); } }); @@ -130,18 +203,35 @@ export class IndicadorFigurePanel implements OnChanges { return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe( switchMap(data => { if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.'); + const periods = selection.periodos ?? data.periodos; + if (selection.figura === 'fig_c2_donas' && periods.length > 1) { + const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) })); + if (pages.every(p => p.adapted.status === 'supported')) { + return of(this.activateDonutPages(pages.map(({ period, adapted }) => { + if (adapted.status !== 'supported') throw new Error('Periodo no soportado'); + return { period, state: { ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const, + footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage } }; + }))); + } + return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data); + } const adapted = c2Figure(data, selection); return adapted.status === 'supported' ? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage }) - : this.publishedFigure(selection, adapted.reason); + : this.publishedFigure(selection, adapted.reason, data); })); } return this.publishedFigure(selection); } - private publishedFigure(selection: FigureSelection, fallbackReason?: string) { + private publishedFigure(selection: FigureSelection, fallbackReason?: string, data?: IndicadorDatos) { return defer(() => this.service.figura(selection)).pipe( switchMap(figure => { + const pages = donutPeriodFigures(figure, selection, data?.periodos); + if (pages) return of(this.activateDonutPages(pages.map(({ period, figure: page }) => ({ period, + state: { ...this.present(page, selection, data && donutHierarchy(page, periodDatos(data, period))), + source: 'figuras' as const, fallbackReason, + emptyMessage: !page.data.length ? 'No hay valores representables publicados para el periodo ' + period + '. Consulta las notas de la figura.' : undefined } })))); const period = this.indicador.contrato === 'C2' ? donutPeriod(figure) : undefined; const present = (hierarchy?: DonutHierarchy) => ({ ...this.present(figure, selection, hierarchy), source: 'figuras' as const, fallbackReason }); @@ -158,6 +248,7 @@ export class IndicadorFigurePanel implements OnChanges { const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth); return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes, categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth, hierarchy, + donutLegend: selection.figura === 'fig_c2_donas' && !hierarchy ? donutLegend(presentation.figure) : undefined, plotWidth: selection.figura === 'fig_c2_donas' && this.indicador.contrato === 'C2' && this.plotWidth !== undefined ? (this.plotWidth < 480 ? 320 : 480) : undefined }; } @@ -180,7 +271,9 @@ export class IndicadorFigurePanel implements OnChanges { ngOnChanges(changes: SimpleChanges) { if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = ''; const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); + if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; } this.titleId = identityElementId(identity) + '-title'; + this.distributionAvailabilityId = this.titleId + '-distribution-availability'; const key = this.requestKey(); if (key === this.currentKey) { if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') { @@ -215,6 +308,7 @@ export class IndicadorFigurePanel implements OnChanges { if (!this.visible) return; this.currentKey = this.requestKey(); this.stratifiedData = undefined; this.cells = []; + this.donutPages = []; const applied = this.applied; const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo); this.generation++; diff --git a/src/app/features/indicadores/indicador-metadata.scss b/src/app/features/indicadores/indicador-metadata.scss new file mode 100644 index 0000000..9834ece --- /dev/null +++ b/src/app/features/indicadores/indicador-metadata.scss @@ -0,0 +1,14 @@ +:host { display: block; min-width: 0; overflow-wrap: anywhere; } +section + section { margin-top: var(--issste-space-4); } +h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; } +.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; } +.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); } +@media (max-width: 36rem) { + .ficha-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); } + dd { margin-bottom: var(--issste-space-2); } +} diff --git a/src/app/features/indicadores/indicador-metadata.spec.ts b/src/app/features/indicadores/indicador-metadata.spec.ts index 3f42810..4c8b357 100644 --- a/src/app/features/indicadores/indicador-metadata.spec.ts +++ b/src/app/features/indicadores/indicador-metadata.spec.ts @@ -2,16 +2,89 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { IndicadorMetadata } from './indicador-metadata'; -describe('Metadatos opcionales verificados',()=>{ - it('muestra referencias y poblaciones como texto seguro y etiquetas legibles',()=>{ - TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); - const f=TestBed.createComponent(IndicadorMetadata), http=TestBed.inject(HttpTestingController); - f.componentRef.setInput('dominio','cacu');f.componentRef.setInput('indicador','future');f.detectChanges(); - http.expectOne('/cacu/indicadores/future/metadatos').flush({referencias:[{tipo:'citation',etiqueta:'Guía publicada ',ref:'Indicador 7'}],poblaciones:[{grupo:'TOTAL',codigo:'initial-population',descripcion:'Pacientes con estudio publicado.'}]});f.detectChanges(); - expect(f.nativeElement.textContent).toContain('Guía publicada ');expect(f.nativeElement.querySelector('img')).toBeNull();expect(f.nativeElement.textContent).toContain('Pacientes con estudio publicado.');expect(f.nativeElement.textContent).not.toMatch(/initial-population|citation|TOTAL/);http.verify();f.destroy(); + +function render(data: unknown) { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const fixture = TestBed.createComponent(IndicadorMetadata); + const http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cacu'); + fixture.componentRef.setInput('indicador', 'future'); + fixture.detectChanges(); + http.expectOne('/cacu/indicadores/future/metadatos').flush(data as Record); + fixture.detectChanges(); + return { fixture, http, text: fixture.nativeElement.textContent as string }; +} + +describe('Metadatos metodológicos opcionales', () => { + it('muestra descripción sin ficha y trata etiquetas recibidas como texto', () => { + const { fixture, http, text } = render({ titulo: 'Título del catálogo', descripcion: 'Guía \nSegunda línea', ficha: null }); + expect(text).toContain('Guía '); + expect(fixture.nativeElement.querySelector('img')).toBeNull(); + expect(text).toContain('Segunda línea'); + expect(text).not.toContain('Ficha metodológica'); + expect(text).not.toContain('Título del catálogo'); + expect(text).not.toContain('no está disponible'); + http.verify(); fixture.destroy(); }); - it.each([{}, {referencias:[],poblaciones:[]},{referencias:'invalid'}])('conserva el estado actual sin campos opcionales válidos',data=>{ - TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); - const f=TestBed.createComponent(IndicadorMetadata), http=TestBed.inject(HttpTestingController);f.componentRef.setInput('dominio','tea');f.componentRef.setInput('indicador','i1');f.detectChanges();http.expectOne('/tea/indicadores/i1/metadatos').flush(data);f.detectChanges();expect(f.nativeElement.textContent).toContain('no está disponible');http.verify();f.destroy(); + + it('muestra todos los campos no vacíos de la ficha', () => { + const { fixture, http, text } = render({ + descripcion: 'Información general.', + ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' }, + }); + for (const content of ['Descripción', 'Información general.', 'Ficha 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); + expect(text).not.toContain('no está disponible'); + http.verify(); fixture.destroy(); + }); + + it('muestra sólo los campos utilizables de una ficha parcial', () => { + const { fixture, http, text } = render({ ficha: { codigo: 'IND-02', para: ' ', unidad: null, definicion: 'Definición breve', nota: '' } }); + expect(text).toContain('Código'); expect(text).toContain('IND-02'); + expect(text).toContain('Definición breve'); expect(text).not.toContain('Para'); + expect(text).not.toContain('Unidad'); expect(text).not.toContain('Pregunta'); expect(text).not.toContain('Nota'); + expect(text).not.toContain('no está disponible'); + http.verify(); fixture.destroy(); + }); + + it('acepta nota nula y conserva el resto de la ficha', () => { + const { fixture, http, text } = render({ ficha: { unidad: 'Tasa', nota: null } }); + expect(text).toContain('Unidad'); expect(text).toContain('Tasa'); + expect(text).not.toContain('Nota'); expect(text).not.toContain('no está disponible'); + http.verify(); fixture.destroy(); + }); + + it('muestra estado vacío con descripción y ficha ausentes o nulas', () => { + const { fixture, http, text } = render({ descripcion: null, ficha: null, referencias: null, poblaciones: null }); + expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.'); + expect(text).not.toContain('Ficha metodológica'); expect(text).not.toContain('Descripción'); + http.verify(); fixture.destroy(); + }); + + it('mantiene referencias y poblaciones de payloads anteriores junto con la descripción', () => { + const { fixture, http, text } = render({ + descripcion: 'Descripción publicada.', + referencias: [{ tipo: 'citation', etiqueta: 'Guía publicada edición 2', ref: 'Indicador 7' }], + poblaciones: [{ grupo: 'TOTAL', codigo: 'initial-population', descripcion: 'Pacientes con estudio publicado.' }], + categorias: { NORMAL: { etiqueta: 'Normal' } }, + }); + expect(text).toContain('Descripción publicada.'); + expect(text).toContain('Guía publicada edición 2 · Indicador 7'); + expect(text).toContain('Pacientes con estudio publicado.'); + expect(fixture.nativeElement.querySelector('em')).toBeNull(); + expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/); + http.verify(); fixture.destroy(); + }); + + it('conserva compatibilidad con el payload anterior que sólo trae categorías', () => { + const { fixture, http, text } = render({ categorias: { NORMAL: { etiqueta: 'Normal' } } }); + expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.'); + expect(text).not.toContain('Normal'); + http.verify(); fixture.destroy(); + }); + + it('no anuncia ausencia cuando hay ficha utilizable aunque sus demás campos estén vacíos', () => { + const { fixture, http, text } = render({ ficha: { codigo: ' IND-03 ' } }); + expect(text).toContain('IND-03'); expect(text).not.toContain('no está disponible'); + http.verify(); fixture.destroy(); }); }); diff --git a/src/app/features/indicadores/indicador-metadata.ts b/src/app/features/indicadores/indicador-metadata.ts index 23d9e83..4f0de55 100644 --- a/src/app/features/indicadores/indicador-metadata.ts +++ b/src/app/features/indicadores/indicador-metadata.ts @@ -6,15 +6,36 @@ import { IndicadoresService } from './indicadores.service'; @Component({ selector: 'app-indicador-metadata', + styleUrl: './indicador-metadata.scss', template: ` @if (loading) {

Cargando información metodológica…

} - @if (metadata?.referencias?.length) { -

Referencias

    @for (ref of metadata!.referencias; track $index) {
  • {{ ref.etiqueta }}@if (ref.ref) { · {{ ref.ref }} }
  • }
+ @if (description; as text) { +
+

Descripción

+ +
} - @if (metadata?.poblaciones?.length) { -

Poblaciones del estudio

    @for (p of metadata!.poblaciones; track $index) {
  • {{ p.descripcion }}
  • }
+ @if (fichaFields.length) { +
+

Ficha metodológica

+
@for (field of fichaFields; track field.key) { +
{{ field.label }}
+ }
+
} - @if (!loading && !metadata?.referencias?.length && !metadata?.poblaciones?.length) {

La información metodológica ampliada no está disponible para este indicador.

} + @if (references.length) { +
+

Referencias

+
    @for (ref of references; track $index) {
  • {{ ref.etiqueta }}@if (hasText(ref.ref)) { · {{ ref.ref }} }
  • }
+
+ } + @if (populations.length) { +
+

Poblaciones del estudio

+
    @for (population of populations; track $index) {
  • {{ population.descripcion }}
  • }
+
+ } + @if (!loading && !hasUsableMetadata) {

La información metodológica ampliada no está disponible para este indicador.

} `, }) export class IndicadorMetadata implements OnChanges { @@ -25,6 +46,19 @@ export class IndicadorMetadata implements OnChanges { metadata?: IndicadorMetadatos; loading = false; private readonly changeDetector = inject(ChangeDetectorRef); + private readonly fichaLabels = [ + ['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'], + ['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'], + ] as const; + hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; } + get description() { return this.hasText(this.metadata?.descripcion) ? this.metadata!.descripcion!.trim() : undefined; } + get fichaFields() { + const ficha = this.metadata?.ficha; + return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : []; + } + get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); } + get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); } + get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); } constructor() { this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); }); } diff --git a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts index 7ccdad0..56524b2 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts @@ -3,7 +3,7 @@ import { c2Color, C2_PALETTE } from './indicadores-c2-palette'; import { c2Fixture } from './indicadores-c2-adapter.testing'; import { FigureSelection } from './indicadores.models'; import { donutFixture } from './indicadores-donut-drilldown.testing'; -import { donutView } from './indicadores-donut-drilldown'; +import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown'; import { numericRows } from './indicadores-numeric-rows'; import { figurePresentation } from './indicadores.presentation'; @@ -37,14 +37,33 @@ describe('C2: datos publicados a Plotly', () => { expect(final.data[0]['hovertemplate']).toContain(''); expect(final.data[0]['hovertemplate']).not.toContain('2025-S2'); }); - it('el layout final de dona simple reserva el sector superior derecho para la leyenda', () => { + it('la vista de dona simple comparte el lienzo centrado y la leyenda superior', () => { const data = c2Fixture(); data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record>).forEach(c => c['grupo'] = null); const result = supported(data); - const final = figurePresentation(result.figure, selection).figure; - expect(final.layout['legend']).toMatchObject({ orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top' }); - expect(final.data[0]['domain']).toEqual({ x: [0, 0.72], y: [0, 1] }); - expect(final.data[0]['hovertemplate']).toContain(''); + 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' }, + ]); + 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] }); + expect(view.data[0]['showlegend']).toBe(false); + expect(view.data[0]['labels']).toEqual(final.data[0]['labels']); + expect(view.data[0]['values']).toEqual(final.data[0]['values']); + expect(final).toEqual(before); + }); + it('homologa la dona jerárquica en los tres dominios con el mismo periodo único', () => { + const snapshots = (['tea', 'cacu', 'cama'] as const).map(dominio => { + const adapted = supported(c2Fixture(), { ...selection, dominio }); + expect(adapted.model.period).toBe('2025-S2'); + expect(adapted.hierarchy).toBeDefined(); + return donutView(adapted.figure, adapted.hierarchy!); + }); + for (const view of snapshots.slice(1)) expect(view).toEqual(snapshots[0]); + expect(snapshots[0].layout['showlegend']).toBe(false); + expect(snapshots[0].layout['margin']).toMatchObject({ l: 16, r: 16, t: 16, b: 16, pad: 0 }); + expect(snapshots[0].data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); }); it('ordena por orden publicado aunque las filas lleguen desordenadas; conserva ceros explícitos', () => { const data = c2Fixture(); data.filas[0]['n'] = 0; data.filas.reverse(); diff --git a/src/app/features/indicadores/indicadores-donut-drilldown.ts b/src/app/features/indicadores/indicadores-donut-drilldown.ts index 794208e..4690aa0 100644 --- a/src/app/features/indicadores/indicadores-donut-drilldown.ts +++ b/src/app/features/indicadores/indicadores-donut-drilldown.ts @@ -6,7 +6,8 @@ export interface DonutHierarchy { categoryTrace: number; parentTrace?: number; } -export interface DonutSelection { parent?: string; category?: string; } +export interface DonutSelection { parent?: string; category?: string; period?: string; } +export interface DonutLegendEntry { label: string; color?: string; } function record(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } @@ -37,6 +38,39 @@ function centerCountAt(value: unknown, x: number, y: number): value is Record\d+<\/b>$/.test(value['text']); } +export function donutLegend(figure: PlotlyFigure): readonly DonutLegendEntry[] | undefined { + if (figure.data.length !== 1) return; + const trace = figure.data[0]; + if (trace['type'] !== 'pie' || !labels(trace)) return; + const marker = record(trace['marker']) ? trace['marker'] : undefined; + const colors = marker && Array.isArray(marker['colors']) && marker['colors'].length === trace.labels.length + ? marker['colors'] : []; + return trace.labels.map((label, index) => ({ + label, + color: typeof colors[index] === 'string' && /^#[0-9a-f]{6}$/i.test(colors[index] as string) + ? colors[index] as string : undefined, + })); +} + +function donutCanvas(source: PlotlyFigure): PlotlyFigure { + const figure = structuredClone(source); + figure.layout['showlegend'] = false; + figure.layout['height'] = 440; + figure.layout['margin'] = { ...(record(figure.layout['margin']) ? figure.layout['margin'] : {}), + l: 16, r: 16, t: 16, b: 16, pad: 0, autoexpand: false }; + const annotations = figure.layout['annotations']; + if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a) + ? { ...a, x: 0.5, y: 0.5, xanchor: 'center', yanchor: 'middle' } : a); + return figure; +} + +export function donutSimpleView(source: PlotlyFigure): PlotlyFigure { + const figure = donutCanvas(source); + figure.data = figure.data.map(trace => trace['type'] === 'pie' + ? { ...trace, domain: { x: [0, 1], y: [0, 1] }, showlegend: false } : trace); + return figure; +} + // Only a structural candidate: /datos supplies the semantics. No indicator ID, // category count, legendgroup, trace order or exact domain decides eligibility. // C2 metadata describes category -> parent, not further levels or facets. @@ -117,7 +151,7 @@ export function donutHierarchy(figure: PlotlyFigure, data: IndicadorDatos): Donu // The inner ring retains ALL parents so another can be selected directly. Its // denominator is the full verified partition; the outer ring is within-parent. export function donutView(source: PlotlyFigure, hierarchy: DonutHierarchy, parent?: string, _availableWidth?: number): PlotlyFigure { - const figure = structuredClone(source); + const figure = donutCanvas(source); const meta = figure.layout['meta']; const unit = record(meta) && typeof meta['unit'] === 'string' && !/[<>&]/.test(meta['unit']) ? ' ' + meta['unit'] : ''; const outer = figure.data[hierarchy.categoryTrace]; @@ -139,10 +173,6 @@ export function donutView(source: PlotlyFigure, hierarchy: DonutHierarchy, paren x: (plotDomain.x[0] + plotDomain.x[1]) / 2, y: (plotDomain.y[0] + plotDomain.y[1]) / 2, }; - figure.layout['showlegend'] = false; - figure.layout['height'] = 440; - figure.layout['margin'] = { ...(record(figure.layout['margin']) ? figure.layout['margin'] : {}), - l: 16, r: 16, t: 16, b: 16, pad: 0, autoexpand: false }; const annotations = figure.layout['annotations']; if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a) ? { ...a, x: center.x, y: center.y, xanchor: 'center', yanchor: 'middle' } : a); diff --git a/src/app/features/indicadores/indicadores-donut-periods.spec.ts b/src/app/features/indicadores/indicadores-donut-periods.spec.ts new file mode 100644 index 0000000..e9f3cc0 --- /dev/null +++ b/src/app/features/indicadores/indicadores-donut-periods.spec.ts @@ -0,0 +1,183 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { vi } from 'vitest'; +import { donutPeriodFigures } from './indicadores-donut-periods'; +import { Dominio, FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; +import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +const periods = ['2025-S2', '2025-S1', '2026-S1']; +const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_donas', tipoPeriodo: 'semestre', tema: 'claro', periodos: periods }; +function multiData(): IndicadorDatos { + const data = c2Fixture(); + return { ...data, periodos: [...periods], filas: periods.flatMap((periodo, i) => data.filas.map(r => ({ ...r, periodo, n: Number(r['n']) + i }))) }; +} +function multiFigure(): PlotlyFigure { + return { data: periods.map((p, i) => ({ type: 'pie', name: p, hole: .62, labels: ['A', 'B', 'C'], values: [6 + i, 3 + i, 1 + i], + domain: { x: [i / 3, (i + 1) / 3], y: [0, 1] }, customdata: [[p], [p], [p]], text: ['60%', '30%', '10%'], marker: { colors: ['red','blue','green'] } })), + layout: { title: { text: 'Título publicado' }, annotations: [ + ...periods.map((p, i) => ({ text: p + '
N publicado', x: (i + .5) / 3, y: .5, xref: 'paper', yref: 'paper', showarrow: false })), + { text: 'Nota metodológica íntegra', x: 0, y: -.22, xref: 'paper', yref: 'paper', showarrow: false }, + { text: 'Anotación desconocida', x: .1, y: .8 }, + ] }, config: { responsive: true }, extra: { retained: true } }; +} +describe('selección de trazas por periodo de dona', () => { + it('selecciona trazas, conserva arrays completos y normaliza dominio y anotación sin mutar HTTP', () => { + const original = multiFigure(), before = JSON.stringify(original); + const pages = donutPeriodFigures(original, selection)!; + expect(pages.map(p => p.period)).toEqual(periods); + pages.forEach(({ figure }, i) => { + expect(figure.data).toHaveLength(1); + expect(figure.data[0]).toEqual({ ...original.data[i], domain: { x: [0,1], y: [0,1] } }); + expect(figure.layout['annotations']).toEqual([ + expect.objectContaining({ text: periods[i] + '
N publicado', x: expect.closeTo(.5) }), + ...(original.layout['annotations'] as unknown[]).slice(3), + ]); + expect(figure.config).toEqual(original.config); expect(figure['extra']).toEqual(original['extra']); + }); + expect(JSON.stringify(original)).toBe(before); + }); + it('no agrega trazas de un periodo sin datos ni convierte cero, null o supresión', () => { + const original = multiFigure(); original.data.splice(1, 1); + original.data[0]['values'] = [0, null, 10]; original.data[0]['customdata'] = [{ suprimido: true }]; + const pages = donutPeriodFigures(original, selection)!; + expect(pages[0].figure.data[0]['values']).toEqual([0, null, 10]); + expect(pages[0].figure.data[0]['customdata']).toEqual([{ suprimido: true }]); + expect(pages[1].figure.data).toEqual([]); + expect(pages[1].figure.layout['xaxis']).toMatchObject({ visible: false }); + expect(pages[0].figure.layout['annotations']).not.toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '
N publicado' })])); + expect(pages[1].figure.layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '
N publicado', x: .5 })])); + }); + it('mantiene ambos anillos de un único periodo y sus proporciones geométricas', () => { + const source = multiFigure(); + source.data.push({ ...source.data[0], name: periods[0] + ', grupos', domain: { x: [.06333333333333333, .27], y: [.19,.81] } }); + const first = donutPeriodFigures(source, selection)![0].figure; + expect(first.data.map(t => t['name'])).toEqual([periods[0], periods[0] + ', grupos']); + expect((first.data[1]['domain'] as { x: number[] }).x[0]).toBeCloseTo(.19); + expect((first.data[1]['domain'] as { x: number[] }).x[1]).toBeCloseTo(.81); + }); + it('todos sigue el orden explícito de reportes o el recibido, sin ordenar por índice', () => { + const all = { ...selection, periodos: undefined }; + expect(donutPeriodFigures(multiFigure(), all)!.map(p => p.period)).toEqual(periods); + expect(donutPeriodFigures(multiFigure(), all, [...periods].reverse())!.map(p => p.period)).toEqual([...periods].reverse()); + }); + it('cero periodos y un solo periodo conservan el comportamiento anterior', () => { + expect(donutPeriodFigures({ data: [], layout: {} }, { ...selection, periodos: [] })).toBeUndefined(); + const one = multiFigure(); one.data = [one.data[0]]; + expect(donutPeriodFigures(one, { ...selection, periodos: [periods[0]] })).toBeUndefined(); + expect(donutPeriodFigures({ data: [], layout: {} }, { ...selection, figura: 'fig_c2_barras' })).toBeUndefined(); + }); + it.each(['bar', 'animation', 'unidentified', 'solid-pie'])('no aplica a otra familia o navegación propia: %s', kind => { + const source = multiFigure(); + if (kind === 'bar') source.data[0]['type'] = 'bar'; + if (kind === 'animation') source.frames = [{ data: [] }]; + if (kind === 'unidentified') source.data[0]['name'] = 'No identificado'; + if (kind === 'solid-pie') source.data[0]['hole'] = 0; + expect(donutPeriodFigures(source, selection)).toBeUndefined(); + }); + it('admite otra representación publicada con la misma estructura de dona', () => { + expect(donutPeriodFigures(multiFigure(), { ...selection, figura: 'future_donut' })).toHaveLength(3); + }); +}); + +@Component({ selector: 'app-plotly-chart', inputs: ['figure','label','showNotes'], template: '' }) +class ChartStub { figure?: PlotlyFigure; } +describe('navegación multiperiodo en el panel común', () => { + let fixture: ReturnType>, http: HttpTestingController; + const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] }; + function apply(selected = periods, revision = 1) { + fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [...selected] }, revision }); + fixture.detectChanges(); + } + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController); + for (const [name, value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro' })) fixture.componentRef.setInput(name, value); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos')); + const panel = () => fixture.componentInstance; + const card = () => fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; + const buttons = () => fixture.nativeElement.querySelectorAll('.donut-periods button') as NodeListOf; + function load(data = multiData()) { apply(); dataRequest().flush(data); fixture.detectChanges(); } + it.each(['tea', 'cacu', 'cama'] as Dominio[])('%s: datos completos, navegación acotada sin HTTP ni cambio del filtro', domain => { + fixture.componentRef.setInput('dominio', domain); load(); const applied = structuredClone(panel().applied); + const host = fixture.nativeElement.querySelector('app-plotly-chart'); + expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false); + for (let i = 0; i < periods.length; i++) { + expect(panel().activeDonutPeriod).toBe(periods[i]); + expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} / 3`); + expect(card().chartFigure?.data).toHaveLength(1); + expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true); + if (i < 2) { buttons()[1].click(); fixture.detectChanges(); } + } + expect(buttons()[1].disabled).toBe(true); panel().changeDonutPeriod(1); expect(panel().activeDonutPeriod).toBe(periods[2]); + buttons()[0].click(); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[1]); + expect(panel().applied).toEqual(applied); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true); + }); + it('dos periodos, controles nativos accesibles y sin interceptar Enter/Espacio', () => { + apply(periods.slice(0,2)); dataRequest().flush({ ...multiData(), periodos: periods.slice(0,2), filas: multiData().filas.filter(r => r['periodo'] !== periods[2]) }); fixture.detectChanges(); + expect(buttons()[1].tagName).toBe('BUTTON'); expect(buttons()[1].type).toBe('button'); + expect(buttons()[1].getAttribute('aria-label')).toBe('Periodo siguiente de la dona'); + for (const key of ['Enter', ' ']) { const e = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); buttons()[1].dispatchEvent(e); expect(e.defaultPrevented).toBe(false); } + buttons()[1].click(); fixture.detectChanges(); expect(buttons()[1].disabled).toBe(true); + }); + it('retiene periodo activo seleccionado y elige primero si se elimina; no comparte índice con otra figura', () => { + load(); panel().changeDonutPeriod(1); fixture.detectChanges(); + apply([periods[1], periods[2]], 2); dataRequest().flush({ ...multiData(), periodos: periods.slice(1), filas: multiData().filas.filter(r => r['periodo'] !== periods[0]) }); fixture.detectChanges(); + expect(panel().activeDonutPeriod).toBe(periods[1]); + const subset = { ...multiData(), periodos: [periods[0], periods[2]], filas: multiData().filas.filter(r => r['periodo'] !== periods[1]) }; + apply([periods[0], periods[2]], 3); dataRequest().flush(subset); fixture.detectChanges(); + expect(panel().result().status).toBe('ready'); expect(panel().activeDonutPeriod).toBe(periods[0]); + panel().changeDonutPeriod(1); fixture.detectChanges(); + fixture.componentRef.setInput('indicador', { ...item, id: 'otro' }); fixture.detectChanges(); + dataRequest().flush({ ...subset, id: 'otro' }); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[0]); + }); + it('navegación limpia selección dependiente; cada nueva categoría declara el periodo', () => { + load(); const selected = vi.fn(); panel().hierarchySelected.subscribe(selected); + card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges(); + expect(selected).toHaveBeenLastCalledWith({ parent: 'G2', category: 'B', period: periods[0] }); + panel().changeDonutPeriod(1); fixture.detectChanges(); + expect(selected).toHaveBeenLastCalledWith({}); expect(card().activeParent).toBeUndefined(); expect(card().activeCategory).toBeUndefined(); + card().expandParent('G2'); expect(selected).toHaveBeenLastCalledWith({ parent: 'G2', period: periods[1] }); http.expectNone(() => true); + }); + it('perfil y ancho se aplican también al navegar a páginas ya cargadas', () => { + load(); fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); panel().updatePlotWidth(320); + panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().plotWidth).toBe(320); + expect(panel().result().footnotes).toEqual(multiData().notas); http.expectNone(() => true); + }); + it('periodo vacío y cero conservan su identidad, notas y posibilidad de navegar', () => { + const data = multiData(); data.filas = data.filas.filter(r => r['periodo'] !== periods[1]); data.filas.filter(r => r['periodo'] === periods[2]).forEach(r => r['n'] = 0); + load(data); panel().changeDonutPeriod(1); fixture.detectChanges(); + expect(panel().result().figure?.data).toEqual([]); expect(fixture.nativeElement.textContent).toContain('No hay filas publicadas'); + expect(card().chartFigure?.layout['height']).toBe(440); + expect(fixture.nativeElement.querySelector('app-plotly-chart').style.getPropertyValue('--plot-height')).toBe('440px'); + panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().emptyMessage).toContain('conteos publicados son cero'); + expect(fixture.nativeElement.textContent).toContain('2026-S1'); http.expectNone(() => true); + }); + it.each(['null', 'suppressed', 'simple'])('/figuras %s separa las trazas sin peticiones por clic', kind => { + const data = multiData(); + if (kind === 'null') data.filas[0]['n'] = null; + else if (kind === 'suppressed') { data.filas[0]['n'] = null; data.filas[0]['suprimido'] = 1; } + else delete data['unidad']; + apply(); dataRequest().flush(data); const source = multiFigure(); + if (kind !== 'simple') source.data[0]['values'] = [null, 3, 1]; + const before = JSON.stringify(source); http.expectOne(r => r.url.includes('/figuras/')).flush(source); fixture.detectChanges(); + expect(panel().result().source).toBe('figuras'); expect(card().chartFigure?.data).toHaveLength(1); + if (kind !== 'simple') expect(card().chartFigure?.data[0]['values']).toEqual([null,3,1]); + panel().changeDonutPeriod(1); fixture.detectChanges(); expect(card().chartFigure?.data[0]['name']).toBe(periods[1]); + expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true); + }); + it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => { + apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges(); + expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy(); + apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-donut-periods.ts b/src/app/features/indicadores/indicadores-donut-periods.ts new file mode 100644 index 0000000..f94dad1 --- /dev/null +++ b/src/app/features/indicadores/indicadores-donut-periods.ts @@ -0,0 +1,58 @@ +import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models'; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +// Published C2 trace identity, shared by simple pies and the two concentric rings. +export function tracePeriod(trace: Record): string | undefined { + return typeof trace['name'] === 'string' + ? /^(\d{4}-(?:S[12]|0[1-9]|1[0-2]))(?:$|, )/.exec(trace['name'])?.[1] : undefined; +} +export function periodDatos(data: IndicadorDatos, period: string): IndicadorDatos { + return { ...data, periodos: [period], filas: data.filas.filter(row => row['periodo'] === period) }; +} +export interface DonutPeriodFigure { period: string; figure: PlotlyFigure; } + +// Select traces before Plotly receives them. Never change counts, per-point +// attributes, suppression, or the original response. Other chart families and +// figures with their own animation/navigation retain their existing renderer. +export function donutPeriodFigures(source: PlotlyFigure, selection: FigureSelection, + reportedPeriods: readonly string[] = []): DonutPeriodFigure[] | undefined { + if ((!source.data.length && selection.figura !== 'fig_c2_donas') || source.frames?.length + || source.layout['sliders'] !== undefined || source.layout['updatemenus'] !== undefined + || source.data.some(t => t['type'] !== 'pie' || typeof t['hole'] !== 'number' || t['hole'] <= 0 || t['hole'] >= 1 || !tracePeriod(t))) return; + const received = [...new Set(source.data.map(t => tracePeriod(t)!))]; + const periods = [...new Set(selection.periodos ?? [...reportedPeriods, ...received])]; + if (!periods.length || periods.some(p => !selection.tipoPeriodo || parsePeriodos(p, selection.tipoPeriodo)?.[0] !== p)) return; + // A single-period figure keeps its exact published geometry and annotations. + if (periods.length === 1 && received.every(p => p === periods[0])) return; + return periods.map(period => { + const figure = structuredClone(source); + figure.data = figure.data.filter(t => tracePeriod(t) === period); + const domains = figure.data.map(t => t['domain']).filter(record); + const xs = domains.flatMap(d => Array.isArray(d['x']) ? d['x'] as number[] : [0, 1]); + const left = Math.min(...xs), right = Math.max(...xs); + const normalize = (x: number) => (x - left) / (right - left); + // Remove only period-labelled center annotations belonging to other pages. + // Documentary notes and all unrecognized annotations remain untouched. + if (Array.isArray(figure.layout['annotations'])) figure.layout['annotations'] = figure.layout['annotations'].flatMap(a => { + if (!record(a) || a['xref'] !== 'paper' || a['yref'] !== 'paper' || a['y'] !== 0.5 + || a['showarrow'] !== false || typeof a['text'] !== 'string') return [a]; + const owner = /(?:^|[^\d])(\d{4}-(?:S[12]|0[1-9]|1[0-2]))(?=$|[^\d])/.exec(a['text'])?.[1]; + if (!owner || ![...periods, ...reportedPeriods, ...received].includes(owner)) return [a]; + return owner === period ? [{ ...a, x: typeof a['x'] === 'number' && right > left ? normalize(a['x']) : 0.5 }] : []; + }); + if (Number.isFinite(left) && Number.isFinite(right) && right > left) { + for (const trace of figure.data) { + const domain = trace['domain']; + if (record(domain) && Array.isArray(domain['x']) && domain['x'].every(x => typeof x === 'number')) { + trace['domain'] = { ...domain, x: domain['x'].map(normalize) }; + } + } + } + if (!figure.data.length) { + // An empty donut page has no Cartesian observations. Keep the active + // suppression/availability annotation, without Plotly's default axes. + for (const axis of ['xaxis', 'yaxis']) figure.layout[axis] = { ...(record(figure.layout[axis]) ? figure.layout[axis] : {}), visible: false }; + } + return { period, figure }; + }); +} diff --git a/src/app/features/indicadores/indicadores-methodology.ts b/src/app/features/indicadores/indicadores-methodology.ts index 98651e9..c848790 100644 --- a/src/app/features/indicadores/indicadores-methodology.ts +++ b/src/app/features/indicadores/indicadores-methodology.ts @@ -1,4 +1,4 @@ -import { Dominio } from './indicadores.models'; +import { Dominio, IndicadorMetadatos } from './indicadores.models'; // Existing WebApp explanations, shared by figures and the definitions section. // These are editorial guidance, not additional metadata supplied by WebApi. @@ -17,6 +17,13 @@ const CONTRACT_INTERPRETATIONS: Readonly> = { }; export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.'; +export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined { + const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId); + if (!detail) return undefined; + const instructions = detail.como_leer ?? []; + return instructions.some(line => line.trim().length > 0) ? instructions : undefined; +} + export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] { if (contract === 'C2') return [ pie diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 737562a..31dfc1f 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -202,7 +202,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); themedA.flush({ data: [], layout: {} }); }); - it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => { + it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => { load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll(); const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; const filters = control(); @@ -212,6 +212,10 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; for (let i = 0; i < 2; i++) { button.click(); fixture.detectChanges(); + if (i === 0) { + http.expectOne(r => r.url === '/tea/indicadores/i1/metadatos').flush({}); + fixture.detectChanges(); + } expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false'); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts index ad8db27..55cbbd7 100644 --- a/src/app/features/indicadores/indicadores-search.spec.ts +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -158,7 +158,9 @@ describe('UX-05C búsqueda local y partición estable', () => { const helpIds = helps.map(button => button.getAttribute('aria-controls')!); expect(new Set(helpIds).size).toBe(5); for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true); - helps[0].click(); fixture.detectChanges(); await settle(); + helps[0].click(); fixture.detectChanges(); + http.expectOne(r => r.url.endsWith('/metadatos')).flush({}); + fixture.detectChanges(); await settle(); expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]); for (const query of ['sexo', 'evaluacion', '']) { diff --git a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts index 54505c7..39f831c 100644 --- a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts @@ -35,10 +35,45 @@ describe('Barras estratificadas: activación y caché',()=>{ fixture.componentInstance.changeDimension(''); http.expectNone(()=>true); expect(fixture.componentInstance.result().figure?.data[0]['x']).toEqual(general().filas.map(r=>r['n'])); }); + it('reemplaza el selector por un toggle accesible y conserva las dimensiones publicadas',()=>{ + fixture.detectChanges(); request().flush(general()); fixture.detectChanges(); + const toggle = fixture.nativeElement.querySelectorAll('.distribution-toggle [role="radio"]') as NodeListOf; + expect(toggle).toHaveLength(2); expect(fixture.nativeElement.querySelector('select')).toBeNull(); + expect(toggle[0].textContent).toContain('Distribución general'); expect(toggle[0].getAttribute('aria-checked')).toBe('true'); + expect(toggle[1].getAttribute('aria-checked')).toBe('false'); expect(toggle[1].disabled).toBe(false); + for(const key of ['Enter', ' ']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); + toggle[1].dispatchEvent(event); expect(event.defaultPrevented).toBe(false); + } + toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges(); + expect(fixture.componentInstance.dimension).toBe('grupo_edad'); + expect(toggle[1].getAttribute('aria-checked')).toBe('true'); + expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2); + for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); } + }); + it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{ + fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'todos'}}); fixture.detectChanges(); + request().flush(general()); fixture.detectChanges(); + const stratified = fixture.nativeElement.querySelectorAll('.distribution-toggle [role="radio"]')[1] as HTMLButtonElement; + expect(stratified.disabled).toBe(true); expect(stratified.getAttribute('aria-checked')).toBe('false'); + expect(fixture.nativeElement.querySelector('.distribution-note').textContent).toContain('Selecciona un periodo'); + expect(fixture.nativeElement.querySelector('.distribution-control').getAttribute('aria-describedby')) + .toBe(fixture.nativeElement.querySelector('.distribution-note').id); + }); it('no declara ni consulta capacidades ausentes; no acepta ronda',()=>{ fixture.componentRef.setInput('indicador',{...item,filtros:undefined});fixture.detectChanges();request().flush(general());fixture.detectChanges(); expect(fixture.nativeElement.querySelector('select')).toBeNull();fixture.componentInstance.changeDimension('grupo_edad');http.expectNone(()=>true); }); + it('aplica categoría solo en su periodo y limpia dependencia sin HTTP al restaurar',()=>{ + fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');request().flush(age);fixture.detectChanges(); + const all=structuredClone(fixture.componentInstance.result().figure); + fixture.componentRef.setInput('localSelection',{parent:'Anormal',category:'LIEAG',period:'2025-S2'});fixture.detectChanges(); + expect(fixture.componentInstance.result().figure?.data[0]['y']).toEqual(['LIEAG']); + fixture.componentRef.setInput('localSelection',{parent:'Anormal',category:'LIEAG',period:'2026-S1'});fixture.detectChanges(); + expect(fixture.componentInstance.result().figure).toEqual(all); + fixture.componentRef.setInput('localSelection',{});fixture.detectChanges(); + expect(fixture.componentInstance.result().figure).toEqual(all);http.expectNone(()=>true); + }); it('cambio de periodo cancela transporte y consulta dimensión con el nuevo periodo',()=>{ fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');const old=request(); fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'explicit',periodos:['2026-S1']}});fixture.detectChanges();expect(old.cancelled).toBe(true); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 920ac80..0fe4166 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -2,7 +2,7 @@ @if (dominio !== 'cacu') {

El seguimiento aún no está disponible.

- +
Columnas propuestas para revisión.
Paciente / identificaciónProceso o etapaEstadoFecha de referenciaResponsableAcciones
No hay registros de seguimiento disponibles.
@@ -25,9 +25,7 @@ @if (message && status !== 'pending') {

{{ message }}

} @if (status === 'error' || status === 'pending') { } @if (data; as response) { - @if (response.simulado) {

Datos simulados — uso de demostración

}

Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.

- @if (provisional) {

Las reglas de selección son provisionales.

}
@@ -36,7 +34,7 @@ @for (item of response.items; track item.id_seudonimo) { - + diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 90e08be..aa083d2 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -27,9 +27,25 @@ export interface IndicadorDatosEstratificados extends IndicadorDatos { etiquetas_estrato: Record; totales_estrato?: EstratoTotal[]; } +export interface IndicadorFicha { + codigo?: string | null; + para?: string | null; + unidad?: string | null; + pregunta?: string | null; + definicion?: string | null; + nota?: string | null; +} +export interface IndicadorFiguraDetalle { + figura: string; + descripcion: string | null; + como_leer: string[] | null; +} export interface IndicadorMetadatos { - referencias?: { tipo: string; etiqueta: string; ref: string | null }[]; - poblaciones?: { grupo: string; codigo: string; descripcion: string }[]; + descripcion?: string | null; + ficha?: IndicadorFicha | null; + referencias?: { tipo: string; etiqueta: string; ref: string | null }[] | null; + poblaciones?: { grupo: string; codigo: string; descripcion: string }[] | null; + figuras_detalle?: IndicadorFiguraDetalle[] | null; categorias?: Record; [key: string]: unknown; } diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 0dcfb02..615f775 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -15,6 +15,39 @@ describe('IndicadoresService HTTP', () => { }); afterEach(() => http.verify()); + it('acepta metadatos de figura y conserva payloads anteriores sin figuras_detalle', () => { + let legacy: unknown, nullDetails: unknown, current: unknown; + service.metadatos('cacu', 'old').subscribe(value => legacy = value); + http.expectOne('/cacu/indicadores/old/metadatos').flush({ descripcion: 'Anterior', ficha: null, referencias: null, poblaciones: null }); + service.metadatos('cacu', 'empty').subscribe(value => nullDetails = value); + http.expectOne('/cacu/indicadores/empty/metadatos').flush({ figuras_detalle: null }); + service.metadatos('cacu', 'new').subscribe(value => current = value); + http.expectOne('/cacu/indicadores/new/metadatos').flush({ figuras_detalle: [ + { figura: 'fig_a', descripcion: null, como_leer: ['Una instrucción.', 'Otra instrucción.'] }, + { figura: 'fig_b', descripcion: 'Descripción sin instrucciones.', como_leer: [] }, + { figura: 'fig_c', descripcion: null, como_leer: null }, + ] }); + expect(legacy).toMatchObject({ descripcion: 'Anterior' }); + expect(nullDetails).toMatchObject({ figuras_detalle: null }); + expect(current).toMatchObject({ figuras_detalle: [ + { figura: 'fig_a', como_leer: ['Una instrucción.', 'Otra instrucción.'] }, + { figura: 'fig_b', descripcion: 'Descripción sin instrucciones.', como_leer: [] }, + { figura: 'fig_c', como_leer: null }, + ] }); + }); + it.each([ + { figuras_detalle: 'incorrecto' }, + { figuras_detalle: [{ figura: '', descripcion: null, como_leer: [] }] }, + { figuras_detalle: [{ figura: 'fig', descripcion: null, como_leer: [] }, { figura: 'fig', descripcion: null, como_leer: ['ambiguo'] }] }, + { figuras_detalle: [{ figura: 'fig', descripcion: 1, como_leer: [] }] }, + { figuras_detalle: [{ figura: 'fig', descripcion: null, como_leer: ['válida', 1] }] }, + ])('rechaza elementos de figuras_detalle mal formados $figuras_detalle', payload => { + let error: unknown; + service.metadatos('cacu', 'i').subscribe({ error: value => error = value }); + http.expectOne('/cacu/indicadores/i/metadatos').flush(payload); + expect(error).toBeInstanceOf(Error); + }); + it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => { service.catalogo(dominio).subscribe(items => { expect(items).toEqual(syntheticCatalogs[dominio]); @@ -117,4 +150,35 @@ describe('contrato datos exclusivo de KPI', () => { req.flush({ id: 'otro', contrato: 'C3r', tipo_periodo: 'semestre', periodos: [], filas: [] }); expect(error).toBeInstanceOf(Error); http.verify(); }); + it('serializa cero, uno, dos y tres filtros en un único parámetro ordenado', () => { + const http = TestBed.inject(HttpTestingController); + const service = TestBed.inject(IndicadoresService); + const comprobar = (filtros: readonly string[]) => { + service.datos('cacu', 'cacu_eu7', 'mes', ['2025-01'], { + estrato: 'grupo_edad', filtros, + }).subscribe(); + const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos'); + expect(req.request.params.getAll('filtro')).toEqual(filtros.length ? [filtros.join(',')] : null); + expect(req.request.params.getAll('filtro')?.length ?? 0).toBe(filtros.length ? 1 : 0); + expect(req.request.params.get('periodos')).toBe('2025-01'); + expect(req.request.params.get('estrato')).toBe('grupo_edad'); + req.flush({ id:'cacu_eu7', contrato:'C2', tipo_periodo:'mes', periodos:['2025-01'], filas:[], estrato:'grupo_edad' }); + }; + comprobar([]); + comprobar(['grupo_edad:35-44']); + comprobar(['grupo_edad:35-44', 'estatus_seguimiento:VIGILANCIA']); + comprobar(['grupo_edad:35-44', 'estatus_seguimiento:VIGILANCIA', 'otra_dimension:valor']); + }); + it('deja que HttpParams codifique caracteres reservados dentro de los pares', () => { + const http = TestBed.inject(HttpTestingController); + const service = TestBed.inject(IndicadoresService); + const pair = 'grupo_edad:35 & más'; + service.datos('cacu', 'cacu_eu7', 'mes', undefined, { filtros:[pair] }).subscribe(); + const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos'); + expect(req.request.params.getAll('filtro')).toEqual([pair]); + expect(req.request.params.toString()).toContain('filtro=grupo_edad:35%20%26%20m%C3%A1s'); + expect(req.request.params.has('periodos')).toBe(false); + expect(req.request.params.has('estrato')).toBe(false); + req.flush({ id:'cacu_eu7', contrato:'C2', tipo_periodo:'mes', periodos:[], filas:[] }); + }); }); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index 03f74f5..48d783d 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -30,12 +30,32 @@ export class IndicadoresService { metadatos(dominio: Dominio, indicador: string) { return this.http.get(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(value => { if (!record(value)) throw new Error('Metadatos inválidos'); + const description = value['descripcion']; + if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos'); + const ficha = value['ficha']; + if (ficha !== undefined && ficha !== null) { + if (!record(ficha)) throw new Error('Metadatos inválidos'); + for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) { + const content = ficha[field]; + if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos'); + } + } for (const field of ['referencias', 'poblaciones']) { const list = value[field]; - if (list !== undefined && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias' + if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias' ? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string') : typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos'); } + const figureDetails = value['figuras_detalle']; + if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v) + && typeof v['figura'] === 'string' && v['figura'].trim().length > 0 + && (v['descripcion'] === null || typeof v['descripcion'] === 'string') + && (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) { + throw new Error('Metadatos inválidos'); + } + if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record)['figura'])).size !== figureDetails.length) { + throw new Error('Metadatos inválidos'); + } return value as IndicadorMetadatos; })); } @@ -49,7 +69,7 @@ export class IndicadoresService { if (!['grupo_edad', 'estatus_seguimiento'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); params = params.set('estrato', scope.estrato); } - for (const filtro of scope.filtros ?? []) params = params.append('filtro', filtro); + if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(',')); if (periodos) params = params.set('periodos', [...new Set(periodos)].join(',')); return this.http.get(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => { if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string' From 540506bde07f95c0fdcbe85651f728f2ae6caf7b Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 23 Oct 2026 10:32:40 -0600 Subject: [PATCH 28/51] =?UTF-8?q?feat(indicadores):=20conectar=20donas=20j?= =?UTF-8?q?er=C3=A1rquicas=20con=20barras=20generales?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Habilita el filtrado visual local de barras generales mediante selecciones jerárquicas C2, preservando datos originales, periodos, porcentajes y restauración de la distribución completa. --- .../indicadores/indicador-figure-panel.ts | 31 +++- .../indicadores/indicadores-c2-adapter.ts | 4 +- .../indicadores-c2-general-panel.spec.ts | 98 ++++++++++++ .../indicadores-c2-general-selection.spec.ts | 142 ++++++++++++++++++ .../indicadores-c2-general-selection.ts | 75 +++++++++ .../indicadores-numeric-summary.spec.ts | 10 +- 6 files changed, 353 insertions(+), 7 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-c2-general-panel.spec.ts create mode 100644 src/app/features/indicadores/indicadores-c2-general-selection.spec.ts create mode 100644 src/app/features/indicadores/indicadores-c2-general-selection.ts diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 7fef5d0..98b44fd 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -15,6 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; +import { c2GeneralSelection } from './indicadores-c2-general-selection'; @Component({ selector: 'app-indicador-figure-panel', @@ -50,6 +51,7 @@ import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; } + @if (generalSelectionContext) {

{{ generalSelectionContext }}

} @if (dimension && result().status === 'ready') { @@ -136,6 +138,9 @@ export class IndicadorFigurePanel implements OnChanges { get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); } private stratifiedData?: IndicadorDatos; + private generalData?: IndicadorDatos; + private generalState?: FigureState; + generalSelectionContext?: string; get capabilities() { return stratifiedCapabilities(this.indicador); } get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; } changeDimension(value: DimensionEstrato | '') { @@ -155,6 +160,16 @@ export class IndicadorFigurePanel implements OnChanges { source: 'datos', footnotes: data.notas, emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' }; } + private presentGeneral(state: FigureState, selection: FigureSelection): FigureState { + const selected = this.generalData && state.figure + ? c2GeneralSelection(state.figure, this.generalData, selection, this.localSelection) : undefined; + this.generalSelectionContext = selected?.context; + const presentation = this.present(selected?.figure ?? state.figure!, selection); + // Keep the complete original figure in state. Width/profile changes and + // restoration always derive afresh, including published percentage arrays. + return { ...state, ...presentation, figure: state.figure, + footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes }; + } private readySelection?: FigureSelection; private plotWidth?: number; private readonly service = inject(IndicadoresService); @@ -183,6 +198,11 @@ export class IndicadorFigurePanel implements OnChanges { if (generation === this.generation && revision === this.applied?.revision) { if (state.status === 'ready') { this.readySelection = selection; + if (!this.dimension && this.indicador.contrato === 'C2' + && selection?.figura === 'fig_c2_barras' && this.indicador.figuras.includes('fig_c2_donas')) { + this.generalState = state; + state = this.presentGeneral(state, selection); + } if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1 ? selection.periodos[0] : state.figure && donutPeriod(state.figure); } @@ -203,6 +223,7 @@ export class IndicadorFigurePanel implements OnChanges { return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe( switchMap(data => { if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.'); + if (selection.figura === 'fig_c2_barras') this.generalData = data; const periods = selection.periodos ?? data.periodos; if (selection.figura === 'fig_c2_donas' && periods.length > 1) { const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) })); @@ -260,7 +281,8 @@ export class IndicadorFigurePanel implements OnChanges { const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas'; if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut) && state.status === 'ready' && state.figure && this.readySelection) { - const presentation = this.present(state.figure, this.readySelection, state.hierarchy); + const presentation = this.generalState ? this.presentGeneral(this.generalState, this.readySelection) + : this.present(state.figure, this.readySelection, state.hierarchy); const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes }; // A width change within the same label budget must not hide/repaint an // equivalent graph (for example when only the scrollbar gutter changes). @@ -279,10 +301,13 @@ export class IndicadorFigurePanel implements OnChanges { if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') { try { this.result.set(this.presentStratified(this.stratifiedData)); } catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); } + } else if (changes['localSelection'] && this.generalState && this.readySelection && this.result().status === 'ready') { + this.result.set(this.presentGeneral(this.generalState, this.readySelection)); } const state = this.result(); if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) { - const next = this.present(state.figure, this.readySelection, state.hierarchy); + const next = this.generalState ? this.presentGeneral(this.generalState, this.readySelection) + : this.present(state.figure, this.readySelection, state.hierarchy); this.result.set({ ...state, ...next, footnotes: state.source === 'datos' ? state.footnotes : next.footnotes }); } return; @@ -296,6 +321,7 @@ export class IndicadorFigurePanel implements OnChanges { this.generation++; this.figureRequests.next(null); this.currentKey = ''; + this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined; this.result.set({ status: 'deferred', message }); } } @@ -308,6 +334,7 @@ export class IndicadorFigurePanel implements OnChanges { if (!this.visible) return; this.currentKey = this.requestKey(); this.stratifiedData = undefined; this.cells = []; + this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined; this.donutPages = []; const applied = this.applied; const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo); diff --git a/src/app/features/indicadores/indicadores-c2-adapter.ts b/src/app/features/indicadores/indicadores-c2-adapter.ts index e19b826..59117be 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.ts @@ -4,8 +4,8 @@ import { c2Color, c2Theme } from './indicadores-c2-palette'; export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; } // Normalized presentation nodes and a selection path are independent of Plotly. -// No level-3 wire format is assumed. General bars keep the complete partition; -// stratified bars have their own decoder and consume the shared local selection. +// No level-3 wire format is assumed. This decoder keeps the complete partition; +// local selection is applied to a separate, verified presentation copy. export interface C2Node { id: string; label: string; parentId?: string; } export interface C2Selection { path: readonly string[]; } export function c2Descendants(nodes: readonly C2Node[], selection: C2Selection): readonly C2Node[] { diff --git a/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts b/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts new file mode 100644 index 0000000..d6f3ac6 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts @@ -0,0 +1,98 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; +import { c2Figure } from './indicadores-c2-adapter'; +import { DonutSelection } from './indicadores-donut-drilldown'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; +import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +const applied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; +const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] }; +describe('barras generales conectadas con la selección compartida de la dona', () => { + let fixture: ReturnType>, http: HttpTestingController; + const panel = () => fixture.componentInstance; + const select = (local: DonutSelection) => { fixture.componentRef.setInput('localSelection', local); fixture.detectChanges(); }; + const request = () => http.expectOne(r => r.url.endsWith('/datos')); + const displayed = () => panel().result().presentationFigure!; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController); + for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_barras', tema: 'claro', applied })) fixture.componentRef.setInput(k, v); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + function load() { fixture.detectChanges(); request().flush(c2Fixture()); fixture.detectChanges(); } + it('grupo → categoría → restaurar actualiza sólo la presentación, sin GET ni cambio de filtro', () => { + load(); const original = panel().result().figure, before = structuredClone(original), all = structuredClone(displayed()); + const filter = structuredClone(panel().applied), host = fixture.nativeElement.querySelector('app-plotly-chart'); + expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); + 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.textContent).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); + }); + it('una selección recibida mientras carga se aplica al terminar sin otro GET', () => { + fixture.detectChanges(); const pending = request(); select({ parent: 'G2', period: '2025-S2' }); + pending.flush(c2Fixture()); fixture.detectChanges(); expect(displayed().data[0]['y']).toEqual(['B', 'C']); http.expectNone(() => true); + }); + it('ancho y perfil conservan selección y notas desde el original', () => { + load(); select({ parent: 'G2', period: '2025-S2' }); panel().updatePlotWidth(320); + fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); + expect(displayed().data[0]['y']).toEqual(['B', 'C']); expect(panel().result().footnotes).toEqual(c2Fixture().notas); + select({}); expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true); + }); + it.each(['unknown', 'wrong-parent', 'wrong-period', 'missing-period'])('%s restaura la presentación completa', kind => { + load(); const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' }); + select({ parent: kind === 'unknown' ? 'desconocido' : kind === 'wrong-parent' ? 'G1' : 'G2', category: 'B', period: kind === 'missing-period' ? undefined : kind === 'wrong-period' ? '2026-S1' : '2025-S2' }); + expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true); + }); + it.each(['null', 'suppressed', 'simple'])('%s mantiene la figura completa sin nuevas peticiones', kind => { + const data = c2Fixture(); + if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record>).forEach(c => c['grupo'] = null); } + else { data.filas[0]['n'] = null; if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; } + fixture.detectChanges(); request().flush(data); + if (kind !== 'simple') http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ type: 'bar', orientation: 'h', name: '2025-S2', x: [null, 3, 1], y: ['A', 'B', 'C'] }], layout: {} }); + const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' }); + expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true); + }); + it('un cambio de filtro invalida el periodo anterior aunque conserve las mismas etiquetas', () => { + load(); select({ parent: 'G2', category: 'B', period: '2025-S2' }); + fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges(); + expect(panel().generalSelectionContext).toBeUndefined(); + const data = c2Fixture(); data.periodos = ['2026-S1']; data.filas.forEach(r => r['periodo'] = '2026-S1'); request().flush(data); + expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true); + }); + it('la dona hermana aporta el periodo, navegar restaura todas las series y no cambia el filtro global', () => { + const periods = ['2025-S2', '2025-S1'], data = c2Fixture(); + data.periodos = periods; data.filas.push(...data.filas.map(r => ({ ...r, periodo: periods[1], n: Number(r['n']) * 2 }))); + const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tipoPeriodo: 'semestre', tema: 'claro', periodos: [periods[0]] }; + const single = c2Figure(c2Fixture(), selection); if (single.status !== 'supported') throw new Error(single.reason); + const original: PlotlyFigure = { data: [single.figure.data[0], { ...structuredClone(single.figure.data[0]), name: periods[1], x: [12, 6, 2], text: ['60%', '30%', '10%'] }], layout: single.figure.layout }; + delete original.layout['meta']; + fixture.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); + fixture.detectChanges(); request().flush(data); http.expectOne(r => r.url.includes('/figuras/')).flush(original); fixture.detectChanges(); + const full = structuredClone(displayed()), donut = TestBed.createComponent(IndicadorFigurePanel); + for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied: panel().applied })) donut.componentRef.setInput(k, v); + donut.componentInstance.hierarchySelected.subscribe(s => fixture.componentRef.setInput('localSelection', s)); + donut.detectChanges(); http.expectNone(() => true); + const card = () => donut.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; + card().expandParent('G2'); fixture.detectChanges(); expect(displayed().data).toHaveLength(1); expect(displayed().data[0]['name']).toBe(periods[0]); + donut.componentInstance.changeDonutPeriod(1); donut.detectChanges(); fixture.detectChanges(); + expect(displayed()).toEqual(full); expect(donut.componentInstance.donutPeriodIndex).toBe(1); + card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges(); + expect(displayed().data[0]).toMatchObject({ name: periods[1], x: [6], y: ['B'], text: ['30%'] }); + expect(panel().applied.selection).toEqual({ mode: 'explicit', periodos: periods }); expect(panel().result().figure).toEqual(original); + card().returnToParents(); fixture.detectChanges(); expect(displayed()).toEqual(full); + http.expectNone(() => true); donut.destroy(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts new file mode 100644 index 0000000..26ca678 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts @@ -0,0 +1,142 @@ +import { c2Figure } from './indicadores-c2-adapter'; +import { c2Fixture } from './indicadores-c2-adapter.testing'; +import { c2GeneralSelection } from './indicadores-c2-general-selection'; +import { FigureSelection, PlotlyFigure } from './indicadores.models'; + +const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; +const local = { parent: 'G2', period: '2025-S2' }; +function bars(data = c2Fixture()): PlotlyFigure { + const result = c2Figure(data, selection); + if (result.status !== 'supported') throw new Error(result.reason); + return result.figure; +} +describe('selección local segura de barras generales C2', () => { + it('sin selección conserva la distribución completa', () => { + const data = c2Fixture(), source = bars(data), before = structuredClone(source); + expect(c2GeneralSelection(source, data, selection, {})).toBeUndefined(); + expect(source).toEqual(before); + }); + 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.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({ data, source }).toEqual(before); + (view.figure.data[0]['x'] as number[])[0] = 999; + expect(source).toEqual(before.source); + }); + it.each([true, false])('categoría con padre declarado: %s, conserva porcentaje original sin renormalizar', withParent => { + const data = c2Fixture(), source = bars(data); + source.data[0]['text'] = ['60%', '30%', '10%']; + source.data[0]['customdata'] = [['A', 10], ['B', 10], ['C', 10]]; + source.data[0]['hovertemplate'] = '%{y}: %{x} (%{text})'; + const view = c2GeneralSelection(source, data, selection, { ...local, parent: withParent ? 'G2' : undefined, category: 'B' })!; + expect(view.figure.data[0]).toMatchObject({ x: [3], y: ['B'], text: ['30%'], customdata: [['B', 10]], hovertemplate: '%{y}: %{x} (%{text})' }); + expect(view.context).toContain('denominador de la distribución completa del periodo'); + }); + it('preserva colores escalares, arrays de errores y atributos escalares desconocidos', () => { + const data = c2Fixture(), source = bars(data); + source.data[0]['marker'] = { color: '#abcdef' }; + source.data[0]['error_x'] = { array: [1, 2, 3], arrayminus: [0, 1, 2] }; + source.data[0]['future'] = { retained: true }; + expect(c2GeneralSelection(source, data, selection, local)!.figure.data[0]).toMatchObject({ marker: { color: '#abcdef' }, error_x: { array: [2, 3], arrayminus: [1, 2] }, future: { retained: true } }); + }); + it.each([ + { parent: 'inexistente', period: local.period }, { category: 'inexistente', period: local.period }, + { parent: 'G1', category: 'B', period: local.period }, { parent: 'G2' }, + { ...local, period: '2026-S1' }, { period: local.period }, + ])('selección inválida %j mantiene la vista completa', candidate => { + const data = c2Fixture(), source = bars(data), before = structuredClone(source); + expect(c2GeneralSelection(source, data, selection, candidate)).toBeUndefined(); + expect(source).toEqual(before); + }); + it.each(['simple', 'partial-hierarchy', 'missing-row', 'null', 'suppressed', 'missing-unit', 'denominator', 'ambiguous-label'])('contrato %s no produce un filtrado parcial', kind => { + const data = c2Fixture(), source = bars(data), catalog = data['categorias'] as Record>; + if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(catalog).forEach(c => c['grupo'] = null); } + if (kind === 'partial-hierarchy') catalog['A']['grupo'] = null; + if (kind === 'missing-row') data.filas.shift(); + if (kind === 'null') data.filas[0]['n'] = null; + if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; + if (kind === 'missing-unit') delete data['unidad']; + if (kind === 'denominator') data['denominador'] = 999; + if (kind === 'ambiguous-label') catalog['A']['etiqueta'] = 'B'; + const before = structuredClone({ source, data }); + expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); + expect({ source, data }).toEqual(before); + }); + it.each(['partial', 'mismatch', 'duplicate-period', 'unnamed', 'wrong-type', 'frames', 'menu', 'unknown-array', 'short-array', 'explicit-ticks', 'normalization', 'metadata-period', 'metadata-denominator', 'secondary-axis', 'external-data'])('figura %s conserva la presentación publicada', kind => { + const data = c2Fixture(), source = bars(data); + if (kind === 'partial') { source.data[0]['x'] = [3, 1]; source.data[0]['y'] = ['B', 'C']; } + if (kind === 'mismatch') source.data[0]['x'] = [7, 3, 1]; + if (kind === 'duplicate-period') source.data.push(structuredClone(source.data[0])); + if (kind === 'unnamed') delete source.data[0]['name']; + if (kind === 'wrong-type') source.data[0]['type'] = 'scatter'; + if (kind === 'frames') source.frames = [{ name: 'future' }]; + if (kind === 'menu') source.layout['updatemenus'] = []; + if (kind === 'unknown-array') source.data[0]['future'] = [1, 2, 3]; + if (kind === 'short-array') source.data[0]['text'] = ['60%']; + if (kind === 'explicit-ticks') source.layout['yaxis'] = { tickvals: [0, 1, 2] }; + if (kind === 'normalization') source.layout['barnorm'] = 'percent'; + if (kind === 'metadata-period') source.layout['meta'] = { period: '2026-S1' }; + if (kind === 'metadata-denominator') source.layout['meta'] = { denominator: 999 }; + if (kind === 'secondary-axis') source.data[0]['yaxis'] = 'y2'; + if (kind === 'external-data') source.data[0]['xsrc'] = 'remote'; + const before = structuredClone(source); + expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); expect(source).toEqual(before); + }); + it('cero explícito permanece cero y no se reconstruye un valor null/suprimido', () => { + const data = c2Fixture(); data.filas[2]['n'] = 0; + const source = bars(data); + expect(c2GeneralSelection(source, data, selection, { ...local, category: 'C' })!.figure.data[0]['x']).toEqual([0]); + data.filas[2]['n'] = null; data.filas[2]['suprimido'] = 1; + source.data[0]['x'] = [6, 3, null]; + expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); + expect(source.data[0]['x']).toEqual([6, 3, null]); + }); + it('multiperiodo conserva únicamente la traza seleccionada y sus porcentajes, sin sumar periodos', () => { + const data = c2Fixture(), source = bars(data); + delete source.layout['meta']; // Published multiperiod bars have per-trace periods. + data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1', n: Number(r['n']) * 2 }))); + const second = { ...structuredClone(source.data[0]), name: '2025-S1', x: [12, 6, 2], text: ['60%', '30%', '10%'] }; + source.data.push(second); + const multiple = { ...selection, periodos: [...data.periodos] }, before = structuredClone({ data, source }); + const view = c2GeneralSelection(source, data, multiple, { ...local, period: '2025-S1' })!; + expect(view.figure.data).toHaveLength(1); + expect(view.figure.data[0]).toMatchObject({ name: '2025-S1', x: [6, 2], y: ['B', 'C'], text: ['30%', '10%'] }); + expect(c2GeneralSelection(source, data, selection, { ...local, period: '2025-S1' })).toBeUndefined(); + expect(c2GeneralSelection(source, data, multiple, {})).toBeUndefined(); + expect({ data, source }).toEqual(before); + }); + it('Todos con reporte: un periodo sin traza publicada conserva la vista completa disponible', () => { + const data = c2Fixture(), source = bars(data); + data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1' }))); + const before = structuredClone(source); + expect(c2GeneralSelection(source, data, { ...selection, periodos: undefined }, { ...local, period: '2025-S1' })).toBeUndefined(); + 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' }, + 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']] }, + { id: 'cama_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Benigno', ANORMAL: 'Cáncer', SIN_DATO: 'Sin dato' }, + categories: [['BENIGNO', 'Benigno', 'NO_ANORMAL'], ['CARCINOMA_IN_SITU', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA_INVASOR', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] }, + ])('$id: relaciones publicadas con conteos sintéticos, sin reglas por ID', candidate => { + const data = c2Fixture(); data.id = candidate.id; data['unidad'] = candidate.unit; + data['grupos_de_categoria'] = candidate.groups; + data['categorias'] = Object.fromEntries(candidate.categories.map(([id, etiqueta, grupo]) => [id, { etiqueta, grupo }])); + data.filas = candidate.categories.map(([categoria], orden) => ({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, orden, n: orden + 1, suprimido: 0 })); + const s = { ...selection, indicador: candidate.id }, adapted = c2Figure(data, s); + if (adapted.status !== 'supported') throw new Error(adapted.reason); + const source = adapted.figure, parent = candidate.groups.ANORMAL; + expect(c2GeneralSelection(source, data, s, { parent, period: local.period })!.figure.data[0]['y']) + .toEqual(candidate.categories.filter(c => c[2] === 'ANORMAL').map(c => c[1])); + const category = candidate.categories.find(c => c[2] === 'ANORMAL')![1]; + expect(c2GeneralSelection(source, data, s, { parent, category, period: local.period })!.figure.data[0]['y']).toEqual([category]); + // Re-identification does not change capabilities or behavior. + data.id = 'otro-identificador'; + expect(c2GeneralSelection(source, data, { ...s, indicador: data.id }, { parent, period: local.period })).toBeDefined(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c2-general-selection.ts b/src/app/features/indicadores/indicadores-c2-general-selection.ts new file mode 100644 index 0000000..5d1baaa --- /dev/null +++ b/src/app/features/indicadores/indicadores-c2-general-selection.ts @@ -0,0 +1,75 @@ +import { c2Figure } from './indicadores-c2-adapter'; +import { DonutSelection } from './indicadores-donut-drilldown'; +import { periodDatos } from './indicadores-donut-periods'; +import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +// Only known per-point arrays may be sliced. Unknown array semantics require +// the complete presentation, rather than risking misaligned metadata. +const pointArrays = new Set([ + 'x', 'y', 'text', 'hovertext', 'customdata', 'ids', 'hovertemplate', 'texttemplate', 'textposition', + 'base', 'width', 'offset', 'marker.color', 'marker.opacity', 'marker.line.color', 'marker.line.width', + 'marker.pattern.shape', 'marker.pattern.size', 'marker.pattern.solidity', 'marker.pattern.fgcolor', 'marker.pattern.bgcolor', + 'error_x.array', 'error_x.arrayminus', 'error_y.array', 'error_y.arrayminus', + 'textfont.color', 'textfont.size', 'textfont.family', 'insidetextfont.color', 'insidetextfont.size', 'insidetextfont.family', + 'outsidetextfont.color', 'outsidetextfont.size', 'outsidetextfont.family', +]); + +export interface C2GeneralSelection { figure: PlotlyFigure; context: string; } +// Select published observations, never recompute a denominator or interpret a +// visual parent as filas[].grupo (the latter is the statistical population). +export function c2GeneralSelection(source: PlotlyFigure, data: IndicadorDatos, + selection: FigureSelection, local: DonutSelection): C2GeneralSelection | undefined { + const period = local.period; + if (selection.figura !== 'fig_c2_barras' || (!local.parent && !local.category) || !period + || !data.periodos.includes(period) || (selection.periodos && !selection.periodos.includes(period)) + || source.frames?.length || source.layout['sliders'] !== undefined || source.layout['updatemenus'] !== undefined + || !!source.layout['barnorm'] || Object.keys(source.layout).some(key => /^[xy]axis\d+$/.test(key))) return; + const adapted = c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }); + if (adapted.status !== 'supported' || !adapted.model.parents.length || !adapted.model.categories.length) return; + const { categories, parents } = adapted.model; + const meta = source.layout['meta']; + if (record(meta) && ((meta['period'] !== undefined && meta['period'] !== period) + || (meta['denominator'] !== undefined && meta['denominator'] !== adapted.model.total))) return; + const parent = local.parent ? parents.find(p => p.label === local.parent) : undefined; + const category = local.category ? categories.find(c => c.label === local.category) : undefined; + if ((local.parent && !parent) || (local.category && !category) + || (parent && category && 'group:' + category.parentId !== parent.id)) return; + const selected = categories.filter(c => (!parent || 'group:' + c.parentId === parent.id) && (!category || c.id === category.id)); + if (!selected.length) return; + // A trace must explicitly identify its period and match the entire verified + // partition before any categories are hidden. Never filter a partial trace. + const names = source.data.map(t => t['name']); + if (new Set(names).size !== names.length || source.data.some(t => t['type'] !== 'bar' || t['orientation'] !== 'h' + || typeof t['name'] !== 'string' || !data.periodos.includes(t['name']))) return; + const trace = source.data.find(t => t['name'] === period); + if (!trace || !Array.isArray(trace['x']) || !Array.isArray(trace['y']) + || ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined) + || (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y') + || trace['x'].length !== categories.length || trace['y'].length !== categories.length + || new Set(trace['y']).size !== categories.length) return; + const labels = trace['y'] as unknown[], values = trace['x'] as unknown[]; + if (categories.some(c => { const i = labels.indexOf(c.label); return i < 0 || values[i] !== c.value; })) return; + const indices = labels.flatMap((label, i) => selected.some(c => c.label === label) ? [i] : []); + let compatible = true; + const slice = (value: unknown, path: string): unknown => { + if (Array.isArray(value)) { + if (!pointArrays.has(path) || value.length !== categories.length) { compatible = false; return value; } + return indices.map(i => structuredClone(value[i])); + } + if (record(value)) return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, slice(v, path ? path + '.' + key : key)])); + return value; + }; + const filtered = slice(trace, '') as Record; + if (!compatible) return; + const axis = source.layout['yaxis']; + if (record(axis) && (axis['tickvals'] !== undefined || axis['ticktext'] !== undefined + || (axis['type'] !== undefined && axis['type'] !== 'category'))) return; + const figure = structuredClone(source); + figure.data = [filtered]; + 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(' · ') + + '. 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.' }; +} diff --git a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts index a4323b5..da4f8b6 100644 --- a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts +++ b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts @@ -178,16 +178,20 @@ describe('card doble, jerarquía y carga numérica diferida', () => { expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']); http.expectNone(() => true); }); - it('drill-down y restauración de dona no alteran barras, JSON original ni generan consultas', () => { + it('drill-down filtra la presentación de barras y restaurar recupera la distribución sin alterar JSON ni consultar', () => { activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges(); const bars = structuredClone(panels()[1].result().figure); const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard); const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result(); const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf].find(button => button.textContent?.trim() === 'G2')!; parentButton.click(); fixture.detectChanges(); expect(cards[0].activeParent).toBe('G2'); - expect(panels()[1].result()).toBe(barState); expect(panels()[1].result().figure).toEqual(bars); + expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B', 'C']); + expect(panels()[1].result().figure).toBe(barState.figure); expect(panels()[1].result().figure).toEqual(bars); + cards[0].selectCategory('B'); fixture.detectChanges(); + expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B']); (fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges(); - expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); http.expectNone(() => true); + expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); + expect(panels()[1].result().presentationFigure).toEqual(barState.presentationFigure); http.expectNone(() => true); }); it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => { snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true); From ec642df83472eaa60a5c11e977685199de46306e Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 23 Oct 2026 12:14:17 -0600 Subject: [PATCH 29/51] =?UTF-8?q?style(indicadores):=20homologar=20tarjeta?= =?UTF-8?q?s=20y=20navegaci=C3=B3n=20de=20dominios?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Homologa la presentación de figuras y tarjetas en TEA, CaCu y CaMa; recupera las leyendas superiores, permite la expansión independiente de Cómo leer y mueve la navegación de dominios a un selector compacto con resaltado institucional en la topbar. Preserva el comportamiento de Plotly y la interacción dona-barras. --- src/app/app.html | 11 ++++++ src/app/app.routes.spec.ts | 2 +- src/app/app.scss | 20 +++++++++- src/app/app.spec.ts | 31 ++++++++++++++- src/app/app.ts | 21 ++++++++-- .../indicadores/indicador-catalog-card.ts | 31 +++++++++++---- .../indicadores/indicador-figure-card.html | 16 ++++++-- .../indicadores/indicador-figure-card.scss | 25 +++++++++--- .../indicadores/indicador-figure-card.spec.ts | 38 +++++++++++++++++- .../indicadores/indicador-figure-card.ts | 1 + .../indicadores/indicador-figure-panel.ts | 39 ++++++++++++++++--- .../indicadores-c2-general-panel.spec.ts | 31 ++++++++++++++- .../indicadores-navigation.spec.ts | 23 +---------- .../indicadores/indicadores-page.html | 6 --- .../indicadores/indicadores-page.scss | 26 +------------ .../indicadores/indicadores-page.spec.ts | 25 +++++------- .../features/indicadores/indicadores-page.ts | 4 +- .../indicadores/indicadores-sections.spec.ts | 3 +- 18 files changed, 248 insertions(+), 105 deletions(-) diff --git a/src/app/app.html b/src/app/app.html index 5d3c7ac..9061833 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -4,6 +4,17 @@ {{ title }} + @if (activeDomain(); as domain) { + + + @for (option of otherDomains(); track option) { + {{ domainLabels[option] }} + } + + } diff --git a/src/app/app.routes.spec.ts b/src/app/app.routes.spec.ts index 6f041e4..4bbfe73 100644 --- a/src/app/app.routes.spec.ts +++ b/src/app/app.routes.spec.ts @@ -24,7 +24,7 @@ for (const dominio of ['tea', 'cacu', 'cama']) { expect(page.dominio).toBe(dominio); const http = TestBed.inject(HttpTestingController); http.expectOne(`/${dominio}/indicadores`).flush([]); - expect(harness.routeNativeElement?.querySelectorAll('nav a').length).toBe(3); + expect(harness.routeNativeElement?.querySelector('nav')).toBeNull(); http.verify(); }); } diff --git a/src/app/app.scss b/src/app/app.scss index f52f0dc..22e0425 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -38,6 +38,18 @@ overflow-wrap: anywhere; } +.domain-selector { + flex: 0 0 auto; + margin-inline-start: auto; + background-color: var(--issste-accent); + color: var(--issste-text); + font-weight: 700; + white-space: nowrap; +} +.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); } +.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } +.domain-selector:disabled { background-color: var(--issste-accent); color: var(--issste-text-secondary); } + main { padding: var(--issste-space-4) var(--issste-page-gutter) 5.5rem; scroll-margin-top: var(--issste-header-clearance); @@ -71,6 +83,8 @@ main { .platform-title { font-size: 1.125rem; + min-width: 0; + overflow-wrap: anywhere; } } @@ -83,9 +97,11 @@ main { } .platform-title { - flex-basis: 100%; - text-align: center; + font-size: 1rem; } + .header-content { gap: .25rem; } + .institutional-logo { width: 112px; } + .domain-selector { padding-inline: .5rem; } } .back-to-top { diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts index c6ea793..d5ac7a0 100644 --- a/src/app/app.spec.ts +++ b/src/app/app.spec.ts @@ -3,12 +3,14 @@ import { provideRouter } from '@angular/router'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { App } from './app'; +import { routes } from './app.routes'; +import { Router } from '@angular/router'; describe('App — UX-06B', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [App], - providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()], + providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()], }).compileComponents(); }); @@ -53,6 +55,33 @@ describe('App — UX-06B', () => { TestBed.inject(HttpTestingController).expectNone(() => true); TestBed.inject(HttpTestingController).verify(); }); + + it.each([ + ['tea', 'TEA', 'CaCu', 'CaMa'], + ['cacu', 'CaCu', 'TEA', 'CaMa'], + ['cama', 'CaMa', 'TEA', 'CaCu'], + ] as const)('announces %s as the active domain and offers the other domains in the shell', async (domain, active, ...others) => { + const fixture = render(); + await TestBed.inject(Router).navigateByUrl(`/indicadores/${domain}`); + fixture.detectChanges(); + const http = TestBed.inject(HttpTestingController); + const catalog = http.expectOne({ method: 'GET', url: `/${domain}/indicadores` }); + catalog.flush([]); + fixture.detectChanges(); + + const element = fixture.nativeElement as HTMLElement; + const selector = element.querySelector('.domain-selector')!; + expect(selector.textContent).toContain(active); + expect(selector.getAttribute('aria-label')).toBe(`Dominio actual: ${active}. Cambiar dominio`); + selector.click(); + fixture.detectChanges(); + const menuItems = Array.from(document.querySelectorAll('[role="menuitem"]')); + expect(menuItems.map(item => item.textContent?.trim())).toEqual(others); + expect(element.querySelector('nav')).toBeNull(); + http.expectNone(() => true); + fixture.destroy(); + http.verify(); + }); }); describe('App — UX-06D volver al inicio', () => { diff --git a/src/app/app.ts b/src/app/app.ts index ff7f2d1..b1c6779 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,15 +1,29 @@ import { DOCUMENT } from '@angular/common'; -import { Component, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core'; -import { RouterOutlet } from '@angular/router'; +import { Component, computed, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core'; +import { NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { MatMenuModule } from '@angular/material/menu'; +import { filter } from 'rxjs'; @Component({ - imports: [RouterOutlet], + imports: [RouterOutlet, RouterLink, MatButtonModule, MatMenuModule], selector: 'app-root', styleUrl: './app.scss', templateUrl: './app.html', }) export class App implements OnInit, OnDestroy { protected readonly title = 'Plataforma de Indicadores'; + private readonly router = inject(Router); + private readonly currentUrl = signal(this.router.url); + protected readonly activeDomain = computed(() => { + const match = /^\/indicadores\/(tea|cacu|cama)(?:\/|$)/.exec(this.currentUrl()); + return match?.[1] as 'tea' | 'cacu' | 'cama' | undefined; + }); + protected readonly domainLabels = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' } as const; + protected readonly otherDomains = computed(() => (['tea', 'cacu', 'cama'] as const) + .filter(domain => domain !== this.activeDomain())); + private readonly routeSubscription = this.router.events.pipe(filter(event => event instanceof NavigationEnd)) + .subscribe(event => this.currentUrl.set(event.urlAfterRedirects)); readonly showBackToTop = signal(false); @ViewChild('mainContent') private mainContent?: ElementRef; private readonly browserWindow = inject(DOCUMENT).defaultView; @@ -28,6 +42,7 @@ export class App implements OnInit, OnDestroy { } ngOnDestroy() { + this.routeSubscription.unsubscribe(); this.browserWindow?.removeEventListener('scroll', this.updateScroll); } } diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index fb93ded..642b355 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -33,7 +33,7 @@ import { IndicadoresService } from './indicadores.service'; (click)="pinChanged.emit()"> {{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }} -
+
@if (selectedFigure) { @if (!pair.length || otherFigures.length) { @@ -59,16 +59,31 @@ import { IndicadoresService } from './indicadores.service'; `, styles: ` - :host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } - mat-card { padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); + :host { display: flex; min-width: 0; margin: 0; } + mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); } - .graphic-region { min-height: 620px; } + .catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; } + .graphic-region { flex: 1; min-width: 0; } :host(.dual-card) { grid-column: 1 / -1; } - .dual-panels { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--issste-space-4); } - .representation-panel { min-width: 0; } - .representation-panel > h3 { margin-bottom: 0; } - @media (max-width: 900px) { .dual-panels { grid-template-columns: minmax(0, 1fr); } } + .graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); } + .representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); } + .representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; } + app-indicador-figure-panel { grid-row: 2; } + // Nine shared tracks: name, controls, help, title, legend, plot, notes, + // full labels and stratified detail. Content determines their height. + @supports (grid-template-rows: subgrid) { + .graphic-region { grid-auto-rows: auto; grid-template-rows: auto auto auto auto auto minmax(0, 1fr) auto auto auto; } + .representation-panel { grid-row: span 9; grid-template-rows: subgrid; } + app-indicador-figure-panel { grid-row: 2 / span 8; } + .graphic-region:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: none; align-items: start; } + .graphic-region:has(app-indicador-figure-card.methodology-expanded) .representation-panel { grid-row: auto; grid-template-rows: auto auto; } + .graphic-region:has(app-indicador-figure-card.methodology-expanded) app-indicador-figure-panel { grid-row: auto; grid-template-rows: auto auto auto; } + .graphic-region:has(app-indicador-figure-card.methodology-expanded) app-indicador-figure-card { grid-row: auto; grid-template-rows: auto auto auto auto auto auto; } + } + @media (min-width: 901px) { + .dual-panels { grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: var(--issste-space-4); } + } .card-identity { min-width: 0; } h2, p { overflow-wrap: anywhere; } h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index 64c4b38..c2813dc 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -1,3 +1,4 @@ + @if (selected) {
} - +
@if (state.status === 'loading') {

Cargando figura…

@@ -35,8 +36,9 @@ } @else {

{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}

} +
@if (chartFigure) { -
+
@if (state.status === 'ready' && state.hierarchy; as hierarchy) {

{{ activeParent ? 'Categorías de ' + activeParent + '. Anillo exterior: porcentajes dentro de este grupo. Anillo interior: todos los grupos.' : 'Selecciona un segmento para ver sus categorías. También puedes explorar los grupos con Tab y Enter o Espacio.' }}

@@ -84,12 +86,19 @@ }
} +
+
+
+ } + +
@if (state.categoryLabels?.length) {
Nombres completos de las categorías @@ -100,6 +109,5 @@
} -
- } +
diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index 050a7ec..7b66cf7 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -1,6 +1,7 @@ -:host { display: block; min-width: 0; } +:host { display: grid; min-width: 0; } .interpretation { - margin-bottom: var(--issste-space-4); + margin: 0; + padding: 0 1rem .75rem; color: var(--issste-text); font-family: var(--issste-font-body); line-height: 1.5; @@ -14,12 +15,26 @@ .interpretation ul { margin: 0; padding-left: 1.25rem; } .interpretation li + li { margin-top: .25rem; } .period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); } -.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; +.methodology-toggle { margin-top: .75rem; min-height: 44px; max-width: 100%; height: auto; white-space: normal; --mat-button-outlined-label-text-color: var(--issste-text); --mat-button-outlined-outline-color: var(--issste-border); } .methodology-detail p { margin: 0; } .methodology-detail p + p { margin-top: var(--issste-space-2); } .methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } -.figure-card { overflow: visible; min-width: 0; border: 1px solid var(--issste-border); } +.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto; + overflow: visible; min-width: 0; border: 1px solid var(--issste-border); } +.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; } +.interpretation { grid-row: 1; } +.figure-legend { grid-row: 3; min-width: 0; } +.plot-slot { grid-row: 4; min-width: 0; align-content: start; } +.plot-slot[hidden] { display: none; } +.figure-footer { grid-row: 5; min-width: 0; align-content: end; } +.figure-labels { grid-row: 6; min-width: 0; } +@supports (grid-template-rows: subgrid) { + :host, .figure-card { grid-template-rows: subgrid; } + .figure-card { grid-row: span 6; } +} +:host(.methodology-expanded), :host(.methodology-expanded) .figure-card { grid-template-rows: auto auto auto auto auto auto; } +:host(.methodology-expanded) .figure-card { grid-row: auto; } .figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; } .state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; } .dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } @@ -49,7 +64,7 @@ .category-labels ul { margin: .25rem 0 0; padding-left: 1.25rem; } .category-labels li + li { margin-top: .5rem; } -.figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } +.figure-skeleton { min-height: 12rem; display: flex; flex-direction: column; } .skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } .donut-navigation { position: relative; diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 1919dd2..b4de189 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -48,6 +48,30 @@ describe('IndicadorFigureCard', () => { state({ status: 'ready', figure: original, presentationFigure: copy }); return copy; } + it.each(['bar', 'box', 'scatter'])('%s conserva el dimensionamiento intrínseco de Plotly', async type => { + const automatic: PlotlyFigure = { data: [{ type, x: ['A'], y: [2] }], layout: { autosize: true } }; + ready(automatic); await settle(); + const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement; + expect(chart.style.getPropertyValue('--plot-height')).toBe(''); + expect(automatic.layout['height']).toBeUndefined(); + const tall = { ...automatic, layout: { ...automatic.layout, height: 830 } }; + ready(tall); await settle(); + expect(chart.style.getPropertyValue('--plot-height')).toBe(''); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); + expect(tall.layout.height).toBe(830); + }); + it('la leyenda de exploración precede al lienzo y conserva su host y altura al expandir', async () => { + const { figure, data } = donutFixture(); + state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data)! }); await settle(); + const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement; + const slot = plot.closest('.plot-slot')!; + const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement; + expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + fixture.componentInstance.expandParent('G2'); await settle(); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot); + expect(plot.style.getPropertyValue('--plot-height')).toBe('440px'); + expect(fixture.nativeElement.querySelector('.figure-card .interpretation')).toBeTruthy(); + }); it('C2 expande por Plotly y teclado, vuelve con foco y conserva host; reinicia al cambiar resultado', async () => { const { figure, data } = donutFixture(); const hierarchy = donutHierarchy(figure, data)!; @@ -105,6 +129,13 @@ describe('IndicadorFigureCard', () => { expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']); expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']); + const heading = fixture.nativeElement.querySelector('.figure-heading') as HTMLElement; + const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement; + const slot = fixture.nativeElement.querySelector('.plot-slot') as HTMLElement; + const notes = fixture.nativeElement.querySelector('.figure-footer') as HTMLElement; + expect(heading.compareDocumentPosition(legendElement) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(slot.compareDocumentPosition(notes) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); }); it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => { const { figure, data } = donutFixture(); @@ -124,9 +155,9 @@ describe('IndicadorFigureCard', () => { expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura'); expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes); expect(section.querySelector('img, script, a')).toBeNull(); - expect(section.previousElementSibling?.tagName).toBe('APP-PLOTLY-CHART'); + expect(section.parentElement?.previousElementSibling?.querySelector('app-plotly-chart')).toBeTruthy(); expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull(); - expect(section.nextElementSibling?.classList.contains('category-labels')).toBe(true); + expect(section.parentElement?.parentElement?.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(); @@ -277,6 +308,7 @@ describe('IndicadorFigureCard', () => { const button = section.querySelector('button')!; const detail = section.querySelector('[id]') as HTMLElement; expect(button.getAttribute('aria-expanded')).toBe('false'); + expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false); expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); expect(button.tagName).toBe('BUTTON'); @@ -289,10 +321,12 @@ describe('IndicadorFigureCard', () => { expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation); button.click(); fixture.detectChanges(); expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true'); + expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(true); state({ status: 'loading' }); expect(detail.hidden).toBe(false); button.click(); fixture.detectChanges(); expect(detail.hidden).toBe(true); + expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false); expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail); }); it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => { diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 6ea8ab1..101a918 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -34,6 +34,7 @@ export interface FigureState { @Component({ selector: 'app-indicador-figure-card', standalone: true, + host: { '[class.methodology-expanded]': 'methodologyExpanded()' }, imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart], templateUrl: './indicador-figure-card.html', styleUrl: './indicador-figure-card.scss', diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 98b44fd..edf3992 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -16,14 +16,23 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; +import { MatTooltipModule } from '@angular/material/tooltip'; @Component({ selector: 'app-indicador-figure-panel', - imports: [IndicadorFigureCard], + imports: [IndicadorFigureCard, MatTooltipModule], template: ` -
+

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

+

Filtro general aplicado: {{ appliedSummary }}

+ @if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) { + + {{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }} + + } @if (figuraId === 'fig_c2_barras' && capabilities.length) {
Distribución @@ -51,9 +60,10 @@ import { c2GeneralSelection } from './indicadores-c2-general-selection'; } - @if (generalSelectionContext) {

{{ generalSelectionContext }}

} +
+
@if (dimension && result().status === 'ready') { @if (hasSuppressedCells) {

Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

} @if (hasMissingCells) {

Hay datos no disponibles; los espacios sin barra no representan un cero observado.

} @@ -64,12 +74,29 @@ import { c2GeneralSelection } from './indicadores-c2-general-selection'; @if (!cells.length) {

No hay categorías publicadas para esta selección.

} } +
`, styles: ` - :host { display: block; min-width: 0; } - section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); } - .applied-summary { color: var(--issste-text-secondary); overflow-wrap: anywhere; } + :host { display: grid; min-width: 0; } + .figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; } + .panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); } + .applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; } + .selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap; + font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; } + .selection-active { color: var(--issste-text); font-weight: 600; } + .selection-status:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } + .stratified-detail { min-width: 0; overflow-wrap: anywhere; } + @supports (grid-template-rows: subgrid) { + :host, .figure-panel { grid-template-rows: subgrid; } + .figure-panel { grid-row: span 8; } + .panel-controls { grid-row: 1; } + app-indicador-figure-card { grid-row: 2 / span 6; } + .stratified-detail { grid-row: 8; } + } + :host:has(app-indicador-figure-card.methodology-expanded), + .figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: auto auto auto; } + .figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-row: auto; } .distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; } .distribution-control legend { padding: 0; font-weight: 600; } .distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; } diff --git a/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts b/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts index d6f3ac6..ca462e9 100644 --- a/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-general-panel.spec.ts @@ -37,10 +37,39 @@ 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.textContent).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); }); + it('mantiene el mismo estado compacto antes, durante y después de seleccionar, fuera del lienzo', () => { + load(); + const status = fixture.nativeElement.querySelector('.selection-status') as HTMLElement; + const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement; + const height = plot.style.getPropertyValue('--plot-height'); + expect(status.textContent).toContain('Distribución completa'); + expect(status.closest('.panel-controls')).toBeTruthy(); + select({ parent: 'G2', period: '2025-S2' }); + expect(fixture.nativeElement.querySelector('.selection-status')).toBe(status); + expect(status.textContent).toContain('Selección activa'); + expect(status.getAttribute('aria-label')).toContain('denominador de la distribución completa'); + expect(fixture.nativeElement.querySelectorAll('.distribution-note')).toHaveLength(0); + expect(plot.style.getPropertyValue('--plot-height')).toBe(height); + select({}); + expect(status.textContent).toContain('Distribución completa'); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot); + http.expectNone(() => true); + }); + it('el estado compacto general no describe una distribución estratificada ni oculta su error', () => { + fixture.componentRef.setInput('indicador', { ...item, filtros: [ + { estrato: 'grupo_edad', etiqueta: 'Edad', valores: [{ valor: 'adulto', etiqueta: 'Adulto' }] }, + ] }); + load(); select({ parent: 'G2', period: '2025-S2' }); + panel().chooseStratified(); request().flush({}, { status: 500, statusText: 'Failure' }); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.selection-status')).toBeNull(); + expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy(); + expect(panel().result().status).toBe('error'); + http.expectNone(() => true); + }); it('una selección recibida mientras carga se aplica al terminar sin otro GET', () => { fixture.detectChanges(); const pending = request(); select({ parent: 'G2', period: '2025-S2' }); pending.flush(c2Fixture()); fixture.detectChanges(); expect(displayed().data[0]['y']).toEqual(['B', 'C']); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index c2cb052..60a662a 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -44,28 +44,7 @@ describe('UX-04 navegación Angular', () => { const harness = await setup(); await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); load(domain, harness); harness.detectChanges(); - const links = Array.from(harness.routeNativeElement!.querySelectorAll('nav a')) as HTMLAnchorElement[]; - expect(links.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu', 'CaMa']); - expect(links.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu', '/indicadores/cama']); - const selected = links.find(a => a.getAttribute('aria-current') === 'page')!; - expect(selected.getAttribute('href')).toBe('/indicadores/' + domain); - expect(links.filter(a => a.hasAttribute('aria-current'))).toHaveLength(1); - // Check the compiled CSSOM rule against the actual encapsulated element. - // jsdom's computed link decoration can remain stale after aria-current changes. - const activeRule = Array.from(document.styleSheets).flatMap(sheet => Array.from(sheet.cssRules)) - .find((rule): rule is CSSStyleRule => rule instanceof CSSStyleRule - && rule.selectorText.includes('[aria-current=') && selected.matches(rule.selectorText))!; - expect(activeRule).toBeTruthy(); - expect(activeRule.style.getPropertyValue('text-decoration')).toBe('none'); - expect(activeRule.style.getPropertyValue('font-weight')).toBe('700'); - expect(activeRule.style.getPropertyValue('background')).toBe('var(--issste-accent)'); - for (const link of links) { - expect(link.tabIndex).toBe(0); - link.focus(); expect(document.activeElement).toBe(link); - const key = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }); - link.dispatchEvent(key); expect(key.defaultPrevented).toBe(false); - expect(selected.getAttribute('aria-current')).toBe('page'); - } + expect(harness.routeNativeElement!.querySelector('nav')).toBeNull(); http.expectNone(() => true); }); it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => { diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index db3cb6b..33124c2 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -4,12 +4,6 @@

Dashboard de indicadores

Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.

- -
@for (section of sections; track section.id) {
diff --git a/src/app/features/indicadores/indicadores-methodology.ts b/src/app/features/indicadores/indicadores-methodology.ts index c848790..53b5f87 100644 --- a/src/app/features/indicadores/indicadores-methodology.ts +++ b/src/app/features/indicadores/indicadores-methodology.ts @@ -6,13 +6,13 @@ const CONTRACT_INTERPRETATIONS: Readonly> = { C1: [ 'El punto representa la proporción observada.', 'Cuando la figura publica intervalos Wilson al 95 %, la línea vertical representa ese intervalo. No se infieren intervalos cuando faltan.', - 'Los intervalos amplios pueden deberse a denominadores pequeños.', + 'Los intervalos amplios pueden deberse a un tamaño de muestra pequeño.', 'Un porcentaje observado del 100 % no implica certeza poblacional.', ], C3r: [ 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', 'Los límites de dibujo no representan necesariamente extremos observados.', - 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', + 'Pueden mostrarse etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', ], }; export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.'; @@ -41,5 +41,5 @@ export function contractInterpretation(contract: string | undefined, domain: Dom ]; return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract) ? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] - : ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.']; + : ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de la figura; no se infiere su significado estadístico.']; } From 1940f4fa47c9410a31d996b34854d141661cdda9 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 23 Oct 2026 13:18:57 -0600 Subject: [PATCH 31/51] feat(isssteleon): add EU7 clinical scenario charts --- .../indicadores/fixtures/eu7-c2-ejemplos.json | 936 ++++++++++++++++++ .../indicador-catalog-card.spec.ts | 6 +- .../indicadores/indicador-catalog-card.ts | 12 +- .../indicadores/indicador-eu7-escenario.html | 94 ++ .../indicadores/indicador-eu7-escenario.scss | 29 + .../indicador-eu7-escenario.spec.ts | 150 +++ .../indicadores/indicador-eu7-escenario.ts | 146 +++ .../indicadores-eu7-escenario.spec.ts | 101 ++ .../indicadores/indicadores-eu7-escenario.ts | 236 +++++ .../indicadores-initial-integration.spec.ts | 11 +- 10 files changed, 1711 insertions(+), 10 deletions(-) create mode 100644 src/app/features/indicadores/fixtures/eu7-c2-ejemplos.json create mode 100644 src/app/features/indicadores/indicador-eu7-escenario.html create mode 100644 src/app/features/indicadores/indicador-eu7-escenario.scss create mode 100644 src/app/features/indicadores/indicador-eu7-escenario.spec.ts create mode 100644 src/app/features/indicadores/indicador-eu7-escenario.ts create mode 100644 src/app/features/indicadores/indicadores-eu7-escenario.spec.ts create mode 100644 src/app/features/indicadores/indicadores-eu7-escenario.ts diff --git a/src/app/features/indicadores/fixtures/eu7-c2-ejemplos.json b/src/app/features/indicadores/fixtures/eu7-c2-ejemplos.json new file mode 100644 index 0000000..20a28e9 --- /dev/null +++ b/src/app/features/indicadores/fixtures/eu7-c2-ejemplos.json @@ -0,0 +1,936 @@ +{ + "_nota": "Datos SIMULADOS con la forma exacta de GET /cacu/indicadores/cacu_eu7/datos (contrato C2, kit 054837b). Sin 'reportes' (procedencia). Las tres respuestas son del mismo semestre y suman lo mismo.", + "general": { + "id": "cacu_eu7", + "titulo": "Distribución de resultados citológicos", + "version": "0.3.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "NORMAL": { + "etiqueta": "Normal", + "color": "#9DBFE3", + "grupo": "NO_ANORMAL", + "gravedad": 1 + }, + "ASC-US": { + "etiqueta": "ASC-US", + "color": "#2F6DB3", + "grupo": "NO_ANORMAL", + "gravedad": 2 + }, + "LIEBG": { + "etiqueta": "LIEBG", + "color": "#E8C28E", + "grupo": "ANORMAL", + "gravedad": 3 + }, + "ASC-H": { + "etiqueta": "ASC-H", + "color": "#D98E4A", + "grupo": "ANORMAL", + "gravedad": 4 + }, + "LIEAG": { + "etiqueta": "LIEAG", + "color": "#B55A1F", + "grupo": "ANORMAL", + "gravedad": 5 + }, + "CIS": { + "etiqueta": "Carcinoma in situ", + "color": "#7A2E0E", + "grupo": "ANORMAL", + "gravedad": 6 + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_ANORMAL": "Sin anomalía", + "ANORMAL": "Anormal", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así." + ], + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "NORMAL", + "n": 798, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "ASC-US", + "n": 62, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "LIEBG", + "n": 46, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "ASC-H", + "n": 17, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "LIEAG", + "n": 19, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "CIS", + "n": 4, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_DATO", + "n": 87, + "orden": 6, + "suprimido": 0 + } + ], + "totales_estrato": [] + }, + "estatus_seguimiento": { + "id": "cacu_eu7", + "titulo": "Distribución de resultados citológicos", + "version": "0.3.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "estrato": "estatus_seguimiento", + "valores_estrato": [ + "VIGILANCIA", + "POST_COLPOSCOPIA", + "POST_TRATAMIENTO", + "INFO_INSUFICIENTE" + ], + "etiquetas_estrato": { + "VIGILANCIA": "Vigilancia", + "POST_COLPOSCOPIA": "Post colposcopia", + "POST_TRATAMIENTO": "Post tratamiento", + "INFO_INSUFICIENTE": "Información insuficiente" + }, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "NORMAL": { + "etiqueta": "Normal", + "color": "#9DBFE3", + "grupo": "NO_ANORMAL", + "gravedad": 1 + }, + "ASC-US": { + "etiqueta": "ASC-US", + "color": "#2F6DB3", + "grupo": "NO_ANORMAL", + "gravedad": 2 + }, + "LIEBG": { + "etiqueta": "LIEBG", + "color": "#E8C28E", + "grupo": "ANORMAL", + "gravedad": 3 + }, + "ASC-H": { + "etiqueta": "ASC-H", + "color": "#D98E4A", + "grupo": "ANORMAL", + "gravedad": 4 + }, + "LIEAG": { + "etiqueta": "LIEAG", + "color": "#B55A1F", + "grupo": "ANORMAL", + "gravedad": 5 + }, + "CIS": { + "etiqueta": "Carcinoma in situ", + "color": "#7A2E0E", + "grupo": "ANORMAL", + "gravedad": 6 + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_ANORMAL": "Sin anomalía", + "ANORMAL": "Anormal", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así." + ], + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "NORMAL", + "n": 610, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "ASC-US", + "n": 38, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "LIEBG", + "n": 22, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "ASC-H", + "n": 6, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "LIEAG", + "n": 5, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "CIS", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "categoria": "SIN_DATO", + "n": 48, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "NORMAL", + "n": 92, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "ASC-US", + "n": 14, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "LIEBG", + "n": 16, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "ASC-H", + "n": 7, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "LIEAG", + "n": 9, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "CIS", + "n": 2, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "categoria": "SIN_DATO", + "n": 11, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "NORMAL", + "n": 41, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "ASC-US", + "n": 6, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "LIEBG", + "n": 5, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "ASC-H", + "n": 3, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "LIEAG", + "n": 4, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "CIS", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "categoria": "SIN_DATO", + "n": 7, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "NORMAL", + "n": 55, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "ASC-US", + "n": 4, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "LIEBG", + "n": 3, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "ASC-H", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "LIEAG", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "CIS", + "n": 0, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "categoria": "SIN_DATO", + "n": 21, + "orden": 6, + "suprimido": 0 + } + ], + "totales_estrato": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "VIGILANCIA", + "n": 730, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_COLPOSCOPIA", + "n": 151, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "POST_TRATAMIENTO", + "n": 67, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "INFO_INSUFICIENTE", + "n": 85, + "suprimido": 0 + } + ] + }, + "grupo_edad": { + "id": "cacu_eu7", + "titulo": "Distribución de resultados citológicos", + "version": "0.3.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S2" + ], + "estrato": "grupo_edad", + "valores_estrato": [ + "<25", + "25-34", + "35-44", + "45-54", + "55-64" + ], + "etiquetas_estrato": { + "<25": "<25", + "25-34": "25-34", + "35-44": "35-44", + "45-54": "45-54", + "55-64": "55-64" + }, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "NORMAL": { + "etiqueta": "Normal", + "color": "#9DBFE3", + "grupo": "NO_ANORMAL", + "gravedad": 1 + }, + "ASC-US": { + "etiqueta": "ASC-US", + "color": "#2F6DB3", + "grupo": "NO_ANORMAL", + "gravedad": 2 + }, + "LIEBG": { + "etiqueta": "LIEBG", + "color": "#E8C28E", + "grupo": "ANORMAL", + "gravedad": 3 + }, + "ASC-H": { + "etiqueta": "ASC-H", + "color": "#D98E4A", + "grupo": "ANORMAL", + "gravedad": 4 + }, + "LIEAG": { + "etiqueta": "LIEAG", + "color": "#B55A1F", + "grupo": "ANORMAL", + "gravedad": 5 + }, + "CIS": { + "etiqueta": "Carcinoma in situ", + "color": "#7A2E0E", + "grupo": "ANORMAL", + "gravedad": 6 + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_ANORMAL": "Sin anomalía", + "ANORMAL": "Anormal", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así." + ], + "filas": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "NORMAL", + "n": 40, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "ASC-US", + "n": 5, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "LIEBG", + "n": 4, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "ASC-H", + "n": 0, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "LIEAG", + "n": 0, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "CIS", + "n": 0, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "categoria": "SIN_DATO", + "n": 6, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "NORMAL", + "n": 190, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "ASC-US", + "n": 18, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "LIEBG", + "n": 17, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "ASC-H", + "n": 4, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "LIEAG", + "n": 4, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "CIS", + "n": 0, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "categoria": "SIN_DATO", + "n": 22, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "NORMAL", + "n": 230, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "ASC-US", + "n": 20, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "LIEBG", + "n": 14, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "ASC-H", + "n": 6, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "LIEAG", + "n": 7, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "CIS", + "n": 2, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "categoria": "SIN_DATO", + "n": 25, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "NORMAL", + "n": 205, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "ASC-US", + "n": 12, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "LIEBG", + "n": 7, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "ASC-H", + "n": 4, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "LIEAG", + "n": 5, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "CIS", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "categoria": "SIN_DATO", + "n": 20, + "orden": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "NORMAL", + "n": 133, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "ASC-US", + "n": 7, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "LIEBG", + "n": 4, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "ASC-H", + "n": 3, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "LIEAG", + "n": 3, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "CIS", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "categoria": "SIN_DATO", + "n": 14, + "orden": 6, + "suprimido": 0 + } + ], + "totales_estrato": [ + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "<25", + "n": 55, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "25-34", + "n": 255, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "35-44", + "n": 304, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "45-54", + "n": 254, + "suprimido": 0 + }, + { + "periodo": "2025-S2", + "grupo": "TOTAL", + "estrato": "55-64", + "n": 165, + "suprimido": 0 + } + ] + } +} \ No newline at end of file diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index 27f3a03..eb30893 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -79,14 +79,14 @@ describe('UX-06E.D.2.1 selector de representación', () => { expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); }); it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => { - fixture.componentRef.setInput('indicador', { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2', + fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] }); fixture.detectChanges(); const helps = fixture.nativeElement.querySelectorAll('.methodology-toggle') as NodeListOf; expect(helps).toHaveLength(2); helps[0].click(); helps[1].click(); fixture.detectChanges(); - const metadata = http.expectOne('/cacu/indicadores/cacu_eu7/metadatos'); - http.expectNone('/cacu/indicadores/cacu_eu7/metadatos'); + const metadata = http.expectOne('/cacu/indicadores/cacu_eu13/metadatos'); + http.expectNone('/cacu/indicadores/cacu_eu13/metadatos'); metadata.flush({ figuras_detalle: [ { figura: 'fig_c2_donas', descripcion: null, como_leer: ['Instrucción para donas.'] }, { figura: 'fig_c2_barras', descripcion: null, como_leer: ['Instrucción para barras.'] }, diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 642b355..c4d2f43 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -16,11 +16,12 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { filterCompatibility } from './indicadores-memory'; import { DonutSelection } from './indicadores-donut-drilldown'; import { IndicadoresService } from './indicadores.service'; +import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; @Component({ selector: 'app-indicador-catalog-card', - host: { '[class.dual-card]': 'isDual' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel], + host: { '[class.dual-card]': 'isDual || isEu7' }, + imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario], template: `
@@ -35,7 +36,11 @@ import { IndicadoresService } from './indicadores.service';
- @if (selectedFigure) { + @if (isEu7) { +
+ +
+ } @else if (selectedFigure) { @if (!pair.length || otherFigures.length) { Representación gráfica @@ -115,6 +120,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { }); } get pair() { return dualFigures(this.indicador); } + get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } 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] : []; } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html new file mode 100644 index 0000000..373332c --- /dev/null +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -0,0 +1,94 @@ +
+

Filtro general aplicado: {{ appliedSummary }}

+ + @if (helpOpen) { +
+

El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.

+

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.

+

El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.

+

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.

+

Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.

+ @if (metadata; as info) { + @if (info.descripcion) {

{{ info.descripcion }}

} + @if (info.ficha; as ficha) { + @if (ficha.pregunta) {

{{ ficha.pregunta }}

} + @if (ficha.definicion) {

{{ ficha.definicion }}

} + @if (ficha.unidad) {

Unidad: {{ ficha.unidad }}

} + @if (ficha.nota) {

{{ ficha.nota }}

} + } +
Metadatos publicados de las figuras originales +

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.

+ @for (detail of info.figuras_detalle; track detail.figura) { + @if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') { +

{{ detail.descripcion }}

+ @for (line of detail.como_leer; track $index) {

{{ line }}

} + } + } + @for (reference of info.referencias; track $index) {

{{ reference.etiqueta }} {{ reference.ref }}

} +
+ } @else {

Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

} +
+ } + @switch (status()) { + @case ('deferred') {

La vista se cargará al acercarse a esta región.

} + @case ('loading') {

Cargando el mismo periodo para dona y barras…

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + } + @if (status() === 'ready' || status() === 'empty') { + @if (periods.length > 1) { + + } + @if (model; as m) { +

{{ m.periodo }} · Selección: {{ selectionLabel }}

+ @if (status() === 'empty') {

No hay pacientes publicados para este periodo.

} + @else { +
+ +
+ @for (g of m.grupos; track g.id; let i = $index) { + + } +
+
+ @for (c of m.categorias; track c.id; let i = $index) { + + } +
+
+
+

Distribución de resultados · {{ m.periodo }}

+ @if (m.total !== null && m.total > 0 && donutFigure) { + + } @else {

{{ 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.' }}

} +

{{ sinDatoNote }}

+
+

{{ selectionLabel }} por escenario clínico · {{ m.periodo }}

+

Porcentaje del total válido de cada escenario; excluye «Sin dato».

+ @if (m.escenarios.length && barsFigure) { + + } + @for (s of m.escenarios; track s.id) {

{{ s.etiqueta }}: {{ scenarioText(s) }}.

} +
+
+ } + @for (note of m.notas; track $index) {

{{ note }}

} +
Valores publicados y celdas suprimidas +
+
Resultados disponibles por paciente
{{ item.id_seudonimo }}{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }}@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad }} } @else { No disponible }@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible } {{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
+ + @for (row of generalCells; track $index) { } +
Datos generales · {{ m.periodo }}
CategoríaConteo
{{ row.etiqueta }}{{ cellText(row.celda) }}
+ + + @for (row of scenarioCells; track $index) { } +
Escenarios clínicos · {{ m.periodo }} · Porcentajes sin «Sin dato»
EscenarioCategoríaConteoDenominador válidoPorcentaje
{{ row.escenario }}{{ row.categoria }}{{ cellText(row.celda) }}{{ row.den === null ? 'No disponible / no aplica' : row.den }}{{ percentText(row.pct) }}
+
+ + } + } +
diff --git a/src/app/features/indicadores/indicador-eu7-escenario.scss b/src/app/features/indicadores/indicador-eu7-escenario.scss new file mode 100644 index 0000000..79a0c71 --- /dev/null +++ b/src/app/features/indicadores/indicador-eu7-escenario.scss @@ -0,0 +1,29 @@ +:host { display: block; min-width: 0; } +.eu7 { min-width: 0; padding-top: var(--issste-space-3); } +p, h3, summary { overflow-wrap: anywhere; } +.applied-summary, .note { color: var(--issste-text-secondary); } +.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +.selection-status { font-weight: 600; } +.legend { display: grid; gap: .6rem; margin-block: 1rem; } +.keys { display: flex; flex-wrap: wrap; gap: .5rem; } +.legend > button { justify-self: start; } +button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border); + border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; } +.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; } +button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; } +button:disabled { opacity: .5; cursor: default; } +button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; } +.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; } +.figure { min-width: 0; border-top: 1px solid var(--issste-border); } +h3 { font-size: 1rem; line-height: 1.5; } +app-plotly-chart { --plot-height: 440px; } +.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; } +.periods span { text-align: center; } +.periods button { min-width: 44px; font-size: 1.5rem; } +summary { cursor: pointer; padding-block: .75rem; } +.table-scroll { overflow: auto; max-height: 28rem; } +table { border-collapse: collapse; width: 100%; margin-block: 1rem; } +th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } +caption { text-align: start; font-weight: 600; } +@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts new file mode 100644 index 0000000..afef467 --- /dev/null +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -0,0 +1,150 @@ +import { Component, input, output } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import fixtureData from './fixtures/eu7-c2-ejemplos.json'; +import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { IndicadoresSnapshots } from './indicadores-snapshots'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { GlobalApplied } from './indicadores-memory'; +import { Indicador } from './indicadores.models'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { + figure = input(); label = input(); showNotes = input(); + plotClick = output(); +} +describe('EU7 integración Angular y caché compartida', () => { + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; + const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0', + figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'], + filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] }; + let f: ReturnType>; + let http: HttpTestingController; + let data: typeof fixtureData; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData); + f = TestBed.createComponent(IndicadorEu7Escenario); + f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador); + f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); + }); + afterEach(() => { f.destroy(); http.verify(); vi.useRealTimers(); }); + function requests() { + const general = http.expectOne(r => r.url.endsWith('/datos') && !r.params.has('estrato')); + const escenarios = http.expectOne(r => r.url.endsWith('/datos') && r.params.get('estrato') === 'estatus_seguimiento'); + expect(general.request.params.get('periodos')).toBe(escenarios.request.params.get('periodos')); + return { general, escenarios }; + } + function flush() { const r = requests(); r.general.flush(data.general); r.escenarios.flush(data.estatus_seguimiento); f.detectChanges(); } + it('carga diferida; dos GET compartidos con el KPI y ningún GET por clic, tema o navegación de selección', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); + const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe(); + f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); + flush(); expect(f.componentInstance.model!.total).toBe(946); + const general = data.general; const original = structuredClone(applied); + const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf).find(b => b.textContent!.includes('Anormal'))!; + anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); + const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub; + chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges(); + expect(f.componentInstance.selection.categoria).toBe('LIEAG'); + expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG'); + f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({}); + f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); + expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839'); + expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe(); + }); + it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => { + const periods: [string, string] = ['2025-S1', '2025-S2']; + for (const d of [data.general, data.estatus_seguimiento]) { + d.periodos = periods; d.filas = [...d.filas.map(r => ({ ...r, periodo: '2025-S1', n: r.n * 2 })), ...d.filas] as typeof d.filas; + d.totales_estrato = [...d.totales_estrato.map(t => ({ ...t, periodo: '2025-S1', n: t.n * 2 })), ...d.totales_estrato]; + } + f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush(); + expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364); + f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2'); + expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682); + expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined(); + expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2'); + expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true); + }); + it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => { + f.detectChanges(); const r = requests(); r.general.flush(data.general); + r.escenarios.flush({}, { status: 500, statusText: 'Internal Server Error' }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); + f.componentInstance.retry(); http.expectNone(r => r.url.endsWith('/datos') && !r.params.has('estrato')); + http.expectOne(r => r.params.get('estrato') === 'estatus_seguimiento').flush(data.estatus_seguimiento); f.detectChanges(); + expect(f.componentInstance.status()).toBe('ready'); + }); + it('timeout cancela transportes y permite recuperación', async () => { + vi.useFakeTimers(); f.detectChanges(); const r = requests(); + await vi.advanceTimersByTimeAsync(40001); f.detectChanges(); + expect(r.general.cancelled && r.escenarios.cancelled).toBe(true); + expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.textContent).toContain('tardó demasiado'); + f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready'); + }); + it('error de red permite reintento sin figuras engañosas', () => { + f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges(); + expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error'); + expect(f.componentInstance.donutFigure).toBeUndefined(); + f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready'); + }); + it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => { + f.detectChanges(); const old = requests(); + f.componentRef.setInput('visible', false); f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S1'] } }); + f.detectChanges(); expect(old.general.cancelled && old.escenarios.cancelled).toBe(true); + expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); + for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = ['2025-S1']; d.filas.forEach(r => r.periodo = '2025-S1'); d.totales_estrato.forEach(t => t.periodo = '2025-S1'); } + f.componentRef.setInput('visible', true); f.detectChanges(); flush(); expect(f.componentInstance.model!.periodo).toBe('2025-S1'); + }); + it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => { + data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush(); + expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => { + data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = []; + f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + expect(f.nativeElement.textContent).toContain('No hay pacientes publicados'); + }); + it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => { + Object.assign(data.general.filas[0], { n: 987654, suprimido: 1 }); + Object.assign(data.estatus_seguimiento.filas[0], { n: 987654, suprimido: 1 }); + f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido'); + expect(f.nativeElement.textContent).not.toContain('987654'); + expect(f.nativeElement.querySelector('table caption')).not.toBeNull(); + expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0); + }); + it('catálogo sin capacidad temporal o clínica no inicia GET', () => { + f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + }); + it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => { + f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges(); + const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure; + f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges(); + f.componentRef.setInput('visible', true); f.detectChanges(); + expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars); + expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true); + }); + it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const card = TestBed.createComponent(IndicadorCatalogCard); + card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador); + card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(1); + expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0); + for (const [domain, id] of [['cacu', 'cacu_eu13'], ['tea', 'M23_pacientes_evaluados'], ['cama', 'cama_birads_456_paciente'], ['tea', 'cacu_eu7']]) { + card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(0); + expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(2); + } + card.destroy(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.ts b/src/app/features/indicadores/indicador-eu7-escenario.ts new file mode 100644 index 0000000..fa4c25d --- /dev/null +++ b/src/app/features/indicadores/indicador-eu7-escenario.ts @@ -0,0 +1,146 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +import { stratifiedCapabilities } from './indicadores-stratified'; +import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, + periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; + +@Component({ + selector: 'app-indicador-eu7-escenario', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicador-eu7-escenario.html', + styleUrl: './indicador-eu7-escenario.scss', +}) +export class IndicadorEu7Escenario implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); + message = ''; + selection: Seleccion = {}; + periods: string[] = []; + periodIndex = 0; + model?: Modelo; + donutFigure?: PlotlyFigure; + barsFigure?: PlotlyFigure; + helpOpen = false; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + private pages: Modelo[] = []; + get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } + get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; } + get sinDatoNote() { + const m = this.model; + if (!m) return ''; + if (m.vacio) return 'No hay registros publicados en este periodo.'; + const n = m.sinDato.n; + return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.` + : m.total === null ? `Fuera de la dona: ${n} pacientes 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.`; + } + get generalCells() { + const m = this.model; + return !m || m.vacio ? [] : [...m.categorias.map(c => ({ etiqueta: c.etiqueta, celda: m.celdas[c.id] })), + { etiqueta: m.sinDatoEtiqueta, celda: m.sinDato }]; + } + get scenarioCells() { + const m = this.model; + return !m ? [] : m.escenarios.flatMap(s => [...m.categorias.map(c => ({ escenario: s.etiqueta, categoria: c.etiqueta, + celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })), + { escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]); + } + 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) + ' %'; } + scenarioText(s: Escenario) { return s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' : `${s.den} pacientes con resultado`; } + toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + ngOnChanges(changes: SimpleChanges) { + const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([ + this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras, this.indicador.filtros]); + if (key !== this.key) { + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; + this.pages = []; this.periods = []; this.model = undefined; + this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; + if (!this.visible) { this.status.set('deferred'); return; } + this.load(); + } else if (this.visible && !this.loaded) this.load(); + else if (this.model && changes['tema']) this.draw(); + // Visibility and metadata changes must not restart Plotly rendering. + } + retry() { if (this.visible) this.load(); } + private load() { + this.subscription?.unsubscribe(); + this.loaded = true; this.model = undefined; this.pages = []; this.periods = []; + this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; + const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); + if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2' + || !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras') + || !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.'; + this.status.set('incompatible'); return; + } + const key = this.key; + const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = combineLatest([ + this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version), + this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }), + ]).pipe(timeout({ first: 40000 })).subscribe({ + next: ([general, escenarios]) => { + if (key !== this.key) return; + try { + this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods); + this.pages = this.periods.map(p => modelo(general, escenarios, p)); + this.periodIndex = 0; this.activatePeriod(); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined; + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' + : error instanceof Eu7Incompatible ? error.message + : httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit' + && this.applied.selection.periodos.length > 1 ? ' La respuesta corresponde al conjunto de periodos solicitado.' : ''); + this.status.set(error instanceof Eu7Incompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + } + private activatePeriod() { + this.model = this.pages[this.periodIndex]; this.selection = {}; + this.draw(); this.status.set(this.model ? this.model.vacio ? 'empty' : 'ready' : 'empty'); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.activatePeriod(); + } + select(trace: string, index = 0) { + if (!this.model || this.status() !== 'ready') return; + this.selection = clic(this.model, this.selection, trace, index); this.draw(); + } + plotClicked(event: unknown) { + const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; + if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); + } + private draw() { + if (!this.model) return; + this.donutFigure = dona(this.model, this.selection, this.tema); + this.barsFigure = barras(this.model, this.selection, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts new file mode 100644 index 0000000..e12645c --- /dev/null +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -0,0 +1,101 @@ +import fixture from './fixtures/eu7-c2-ejemplos.json'; +import { IndicadorDatos } from './indicadores.models'; +import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario'; + +function eu7Datos() { + return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos }); +} +describe('EU7 modelo de presentación del entregable', () => { + let data: ReturnType; + beforeEach(() => data = eu7Datos()); + const periodo = '2025-S2'; + const model = () => modelo(data.general, data.escenarios, periodo); + it('946 con resultado y 87 sin dato; anillos pie conservan categorías, colores y no mutan el original', () => { + const original = structuredClone(data), m = model(), f = dona(m, {}, 'claro'); + expect(m.total).toBe(946); expect(m.sinDato.n).toBe(87); + expect(f.data.map(t => t['type'])).toEqual(['pie', 'pie', 'pie']); + expect(f.data[2]['labels']).not.toContain('Sin dato'); + expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]); + expect(data).toEqual(original); + }); + it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => { + const m = model(); let s: Seleccion = {}; + const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG'); + s = clic(m, s, 'grupos', g); expect(s).toEqual({ grupo: 'ANORMAL' }); + s = clic(m, s, 'categorias', c); expect(s).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' }); + expect(clic(m, s, 'categorias', c)).toEqual({ grupo: 'ANORMAL' }); + s = clic(m, s, 'centro', 0); expect(s).toEqual({ grupo: 'ANORMAL' }); + s = clic(m, s, 'centro', 0); expect(s).toEqual({}); + expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({}); + expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({}); + expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' }); + expect(clic(m, {}, 'otra', c)).toEqual({}); + expect(clic(m, {}, 'grupos', -1)).toEqual({}); + expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' }); + }); + it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => { + const m = model(), f = barras(m, {}, 'claro'); + m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8)); + const selected = barras(m, { grupo: 'ANORMAL' }, 'claro'); + expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1))) + .toEqual(['5.0', '24.3', '21.7', '7.8']); + const category = barras(m, { categoria: 'LIEAG' }, 'claro'); + expect(category.data).toHaveLength(1); + expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); + expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); + }); + it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => { + if (kind === 'estrato') data.escenarios['estrato'] = 'grupo_edad'; + if (kind === 'categorias') (data.escenarios['categorias'] as any)['LIEAG'].etiqueta = 'Otra'; + if (kind === 'periodos') data.escenarios.periodos = ['2025-S1']; + if (kind === 'orden') data.escenarios.filas[0]['orden'] = 5; + if (kind === 'duplicado') data.escenarios.filas.push(data.escenarios.filas[0]); + if (kind === 'version') data.escenarios['version'] = 'otra'; + if (kind === 'filtros') data.escenarios['filtros'] = { grupo_edad: '25-34' }; + if (kind === 'total') (data.escenarios['totales_estrato'] as any[])[0].n++; + if (kind === 'diferencia') data.general.filas[0]['n'] = 800; + expect(model).toThrow(); + }); + it('no acepta periodos omitidos por el servidor ni respuestas fuera de la selección', () => { + expect(() => periodosCompatibles(data.general, data.escenarios, 'semestre', ['2025-S1', periodo])).toThrow(); + expect(() => periodosCompatibles(data.general, data.escenarios, 'mes', [periodo])).toThrow(); + }); + it('rechaza procedencias diferentes entre respuestas incluso con conteos iguales', () => { + data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }]; + expect(model).toThrow(/reportes distintos/); + }); + it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: todos los puntos son null y no hay denominador inventado', kind => { + const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!; + if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row); + else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 }); + else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 }); + const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro'); + expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]); + expect(JSON.stringify(f)).not.toContain('123456'); + expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull(); + }); + it.each(['suprimido', 'nulo', 'sin fila'])('general con %s nunca produce una dona parcial ni convierte null en cero', kind => { + if (kind === 'sin fila') data.general.filas.splice(0, 1); + else Object.assign(data.general.filas[0], { n: null, suprimido: kind === 'suprimido' ? 1 : 0 }); + const m = model(); expect(m.total).toBeNull(); expect(dona(m, {}, 'claro').data).toEqual([]); + }); + it('escenario ausente no se inventa; solo se dibujan escenarios con filas publicadas', () => { + const removed = data.escenarios.filas.filter(f => f['estrato'] === 'INFO_INSUFICIENTE'); + data.escenarios.filas = data.escenarios.filas.filter(f => f['estrato'] !== 'INFO_INSUFICIENTE'); + data.general.filas.forEach(f => f['n'] = (f['n'] as number) - (removed.find(r => r['categoria'] === f['categoria'])!['n'] as number)); + const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE'); + expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3); + }); + it('escenario vacío y periodo de ceros no producen porcentajes 0/0', () => { + data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0); + (data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0); + const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]); + expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true); + expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })])); + }); + it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => { + data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = []; + const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]); + expect(m.celdas['NORMAL'].n).toBeNull(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts new file mode 100644 index 0000000..0ca3531 --- /dev/null +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -0,0 +1,236 @@ +import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Theme } from './indicadores-c2-palette'; + +// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. +// This boundary is intentionally specific to EU7. Unknown cells never become zero. +export const ESTRATO = 'estatus_seguimiento'; +const SIN_DATO = 'SIN_DATO'; +export interface Seleccion { grupo?: string; categoria?: string; } +export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; } +export interface Grupo { id: string; etiqueta: string; color: string; } +export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; } +export interface Escenario { + id: string; etiqueta: string; celdas: Record; + den: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; +} +export interface Modelo { + periodo: string; categorias: Categoria[]; grupos: Grupo[]; + celdas: Record; total: number | null; sinDato: Celda; + escenarios: Escenario[]; vacio: boolean; notas: string[]; + sinDatoEtiqueta: string; +} +export class Eu7Incompatible extends Error {} +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const miles = (v: number) => v.toLocaleString('es-MX'); +const fail = (message: string): never => { throw new Eu7Incompatible(message); }; +function celda(fila?: Record): Celda { + if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' }; + return typeof fila?.['n'] === 'number' && fila['suprimido'] === 0 + ? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' }; +} +function suma(celdas: Celda[]): number | null { + if (celdas.some(c => c.n === null)) return null; + const value = celdas.reduce((s, c) => s + c.n!, 0); + return Number.isSafeInteger(value) ? value : fail('Conteos fuera de rango.'); +} +function estado(celdas: Celda[]): Escenario['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})`; +} +function catalogo(data: IndicadorDatos): Categoria[] { + const cats = data['categorias'], grupos = data['grupos_de_categoria']; + if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.'); + const result = Object.entries(cats).map(([id, c]) => { + if (!registro(c) || typeof c['etiqueta'] !== 'string' || !c['etiqueta'].trim() + || typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']) + || typeof c['grupo'] !== 'string' || typeof grupos[c['grupo']] !== 'string' + || (id === SIN_DATO) !== (c['grupo'] === SIN_DATO)) return fail('Categorías EU7 incompatibles.'); + return { id, etiqueta: c['etiqueta'], color: c['color'], grupo: c['grupo'] }; + }); + if (result.length < 2 || new Set(result.map(c => c.etiqueta)).size !== result.length) return fail('Categorías EU7 ambiguas.'); + return result; +} + +/** Validate the common temporal scope before exposing any period's figures. */ +export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { + for (const d of [general, escenarios]) { + if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) + || new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string' + || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p)) + || !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) { + return fail('Los datos EU7 no corresponden al indicador o al periodo aplicado.'); + } + } + if (general.periodos.length !== escenarios.periodos.length || general.periodos.some(p => !escenarios.periodos.includes(p)) + || (solicitados && (solicitados.length !== general.periodos.length || solicitados.some(p => !general.periodos.includes(p)))) + || general['version'] !== escenarios['version'] || general['unidad'] !== escenarios['unidad']) { + return fail('Las respuestas general y estratificada no comparten periodos, versión o unidad.'); + } + return solicitados ? [...solicitados] : [...general.periodos].sort(); +} + +/** Two immutable /datos payloads -> one safe presentation model for a single period. */ +export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo { + periodosCompatibles(general, porEscenario, general.tipo_periodo); + const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato']; + if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo) + || !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length + || !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string') + || [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) { + return fail('Respuestas EU7 inválidas para el escenario clínico sin filtros locales.'); + } + const cats = catalogo(general), other = catalogo(porEscenario); + const nombres = general['grupos_de_categoria'] as Record; + const otrosNombres = porEscenario['grupos_de_categoria'] as Record; + if (cats.length !== other.length || cats.some(c => { + const o = other.find(v => v.id === c.id); + return !o || o.etiqueta !== c.etiqueta || o.color !== c.color || o.grupo !== c.grupo + || nombres[c.grupo] !== otrosNombres[c.grupo]; + })) return fail('Los catálogos general y estratificado son diferentes.'); + const orden = new Map(); + const indexar = (d: IndicadorDatos, estratificado: boolean) => { + const index = new Map>(); + for (const row of d.filas.filter(f => f['periodo'] === periodo)) { + const c = row['categoria'], e = row['estrato'], n = row['n'], o = row['orden']; + if (row['grupo'] !== 'TOTAL' || typeof c !== 'string' || !cats.some(cat => cat.id === c) + || (estratificado ? typeof e !== 'string' || !valores.includes(e) : e != null) + || typeof o !== 'number' || !Number.isSafeInteger(o) || o < 0 + || ![0, 1].includes(row['suprimido'] as number) + || (n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) return fail('Fila EU7 inválida.'); + const key = JSON.stringify([estratificado ? e : null, c]); + if (index.has(key) || (orden.has(c) && orden.get(c) !== o)) return fail('Filas u orden EU7 ambiguos.'); + orden.set(c, o); index.set(key, row); + } + return index; + }; + const g = indexar(general, false), e = indexar(porEscenario, true); + const reporte = (d: IndicadorDatos) => { + const reports = d['reportes']; + if (reports === undefined) return undefined; + if (!Array.isArray(reports) || !reports.every(registro)) return fail('Procedencia EU7 inválida.'); + const active = reports.filter(r => r['periodo'] === periodo); + if (active.length !== 1) return fail('Procedencia del periodo EU7 ambigua.'); + return active[0]; + }; + const rg = reporte(general), re = reporte(porEscenario); + if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha'] + .some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.'); + if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.'); + // Missing rows remain unavailable. Catalog order is used only for the accessible + // list of missing categories; a partial distribution is never drawn as a donut. + const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity)); + const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], + color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) })); + const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))])); + const totals = porEscenario['totales_estrato']; + if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.'); + const escenarios: Escenario[] = (valores as string[]).filter(v => [...e.values()].some(row => row['estrato'] === v)).map(id => { + const cells = Object.fromEntries(cats.map(c => [c.id, celda(e.get(JSON.stringify([id, c.id])))])); + const matches = (totals as Record[] | undefined)?.filter(t => t['periodo'] === periodo && t['estrato'] === id) ?? []; + if (matches.length > 1 || matches.some(t => t['grupo'] !== 'TOTAL' || ![0, 1].includes(t['suprimido'] as number) + || (t['n'] !== null && (typeof t['n'] !== 'number' || !Number.isSafeInteger(t['n']) || t['n'] < 0)))) return fail('Total de escenario ambiguo.'); + const total = matches[0] && celda(matches[0]); + const estadoEscenario = estado([...Object.values(cells), ...(total ? [total] : [])]); + const completo = suma(Object.values(cells)); + if (completo !== null && total?.n != null && completo !== total.n) return fail('El total del escenario difiere de sus categorías.'); + return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario, + den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null }; + }); + // Compare only fully published sums. Never derive a hidden value by subtraction. + if (escenarios.length) { + for (const c of cats) { + const total = suma(escenarios.map(s => s.celdas[c.id])); + if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.'); + } + } else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.'); + if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.'); + return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO], + sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta, + total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size, + notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] }; +} +const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo); +const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id])); +export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string { + return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta + : sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL'; +} +/** Same state machine as the deliverable, with guards for unrelated/stale events. */ +export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number): Seleccion { + 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 ? {} : { grupo: g }; + } + if (traza !== 'categorias') return sel; + const c = m.categorias[indice]; + if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel; + return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id }; +} +export function porcentaje(s: Escenario, categoria: string): number | null { + const n = s.celdas[categoria]?.n; + return s.den !== null && s.den > 0 && n != null ? 100 * n / s.den : null; +} +/** Three pies share one square plot area; SIN_DATO never enters their values. */ +export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { + if (m.total === null || m.total === 0) return { data: [], layout: {} }; + const p = c2Theme(tema); + const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0); + const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0); + const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total; + const rotulos = (values: number[], labels: string[], pct: boolean) => { + const total = values.reduce((s, n) => s + n, 0); + return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `
${(100 * v / total).toFixed(0)} %` : '')); + }; + const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text', + insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' }; + const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes · %{customdata[1]} % del total con resultado' }; + const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]); + return { data: [ + { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, + text: [`${miles(centro)}
${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text }, + marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '' }, + { ...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 } } }, + { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, + labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true), + textfont: { size: 11 }, customdata: custom(exterior), + marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, + ], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, + config: { displayModeBar: false } }; +} +/** Selection never changes the original denominator or renormalizes a subset. */ +export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { + const p = c2Theme(tema); + const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id); + const y = m.escenarios.map(s => escapar(s.etiqueta)); + const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0)); + return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => { + const x = m.escenarios.map(s => porcentaje(s, c.id)); + return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x, + marker: { color: c.color, line: { color: p.background, width: 1 } }, + text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', + customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]), + hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }; + }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), + paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, + margin: { t: 24, l: 150, r: 36, b: 90 }, showlegend: false, + yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true }, + xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid, + range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 100] }, + annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false, + font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' + : sel.grupo || sel.categoria ? `${sumas[i]!.toFixed(1)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${s.den})` : '' })), + }, config: { displayModeBar: false } }; +} diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 7652d05..495b9ff 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -108,7 +108,9 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => { choose(); http.expectNone(r => r.url.includes('/figuras/')); cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); }); - fixture.detectChanges(); flushFigures(periods[1], items.length); http.expectNone(() => true); + // EU7 now owns a coordinated C2 view. This temporal fixture publishes only + // placeholder f/g figures, so that card must stop as incompatible, without GET. + fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true); }); it('KPI secundarios sin datos no retroceden a otro periodo', () => { request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); @@ -126,9 +128,10 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => { choose(); const applied = page.filters!.applied; page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true); - cards()[0].setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1); - cards()[0].selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1); - expect(cards()[0].selectedFigure).toBe('g'); http.expectNone(() => true); + const card = cards().find(card => !card.isEu7)!; + card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1); + card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1); + expect(card.selectedFigure).toBe('g'); http.expectNone(() => true); expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready'); }); it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => { From db9ab0d1a72303653728881ff7590bbd636e1b40 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 23 Oct 2026 21:18:43 -0600 Subject: [PATCH 32/51] feat(indicadores): ajustar indicadores CaCu y presentacion EU7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Actualiza los indicadores de oportunidad y clínicos de CaCu, incorpora el KPI no disponible, prioriza EU7, independiza dos figuras mediante Todos con reporte y añade el selector de prioridad no disponible en Seguimiento. Integra además los totales por escenario en las barras de EU7 y elimina el listado inferior redundante. --- .../indicadores/cacu-seguimiento.spec.ts | 16 ++ .../indicadores/indicador-catalog-card.ts | 3 +- .../indicadores/indicador-eu7-escenario.html | 1 - .../indicador-eu7-escenario.spec.ts | 3 + .../indicadores/indicador-eu7-escenario.ts | 1 - .../indicadores/indicador-figure-panel.ts | 3 +- .../indicadores/indicador-kpi-panel.spec.ts | 47 +++-- .../indicadores-cacu-final.spec.ts | 196 ++++++++++++++++++ .../indicadores-eu7-escenario.spec.ts | 3 + .../indicadores/indicadores-eu7-escenario.ts | 8 +- .../indicadores-figure-selection.ts | 19 ++ .../indicadores-initial-integration.spec.ts | 24 +-- .../indicadores/indicadores-kpi.spec.ts | 9 +- .../features/indicadores/indicadores-kpi.ts | 1 - .../indicadores-numeric-summary.ts | 15 +- .../indicadores/indicadores-page.html | 13 +- .../features/indicadores/indicadores-page.ts | 12 +- .../indicadores-periodos-integration.spec.ts | 10 +- .../indicadores/indicadores-tracking.html | 3 + 19 files changed, 325 insertions(+), 62 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-cacu-final.spec.ts create mode 100644 src/app/features/indicadores/indicadores-figure-selection.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index 42c509c..f4650bb 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -16,6 +16,22 @@ 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', () => { + respond(); + const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement; + expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad'); + expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']); + const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo); + expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order); + fixture.componentInstance.apply(); + let req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']); + req.flush(fixtureData); fixture.detectChanges(); + fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']); + expect(req.request.params.get('page')).toBe('2'); + req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } }); + }); it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => { fixture.detectChanges(); http.expectNone(()=>true); respond(); const root:HTMLElement=fixture.nativeElement; diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index c4d2f43..eb2ef4a 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -55,7 +55,7 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; @for (figure of displayFigures; track panelIdentity(figure)) {
@if (isDual) {

{{ figureDisplayName(figure, indicador.figuras) }}

} - +
} @@ -144,6 +144,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { @Input({ required: true }) indicador!: Indicador; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; + @Input() independentPeriods = false; @Input() pinned = false; @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; readonly pinChanged = output(); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html index 373332c..8eede8b 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.html +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -72,7 +72,6 @@ @if (m.escenarios.length && barsFigure) { } - @for (s of m.escenarios; track s.id) {

{{ s.etiqueta }}: {{ scenarioText(s) }}.

} } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts index afef467..56ff0ae 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -46,6 +46,9 @@ 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); + const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement; + expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1); + expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682'); const general = data.general; const original = structuredClone(applied); const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf).find(b => b.textContent!.includes('Anormal'))!; anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.ts b/src/app/features/indicadores/indicador-eu7-escenario.ts index fa4c25d..0b38357 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.ts @@ -65,7 +65,6 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { } 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) + ' %'; } - scenarioText(s: Escenario) { return s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' : `${s.den} pacientes con resultado`; } toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } ngOnChanges(changes: SimpleChanges) { diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index edf3992..e1bf9ae 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -25,7 +25,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';

{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}

-

Filtro general aplicado: {{ appliedSummary }}

+

{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}

@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) { { function requests() { return http.match(r => r.url.endsWith('/datos')); } 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: index === 1 && 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 }] }; + { periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] }; } function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') { const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] }; @@ -53,12 +53,13 @@ describe('KPI integración con autoridad global', () => { expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]); expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.'); }); - it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => { - load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true); + it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => { + load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true); for (const r of req) { expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.has('tema')).toBe(false); } - req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges(); - expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']); - expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private'); + req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); + expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta']); + panels()[1].retry(); requests()[0].flush(response(1)); fixture.detectChanges(); + expect(panels()[1].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private'); expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2'))); }); @@ -67,10 +68,10 @@ describe('KPI integración con autoridad global', () => { const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true); fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0); - expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); + expect(panels().map(p => p.result().value)).toEqual([5, 7]); expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); - apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3); + apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(2); next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2'))); apply(['2025-S2']); http.expectNone(() => true); }); @@ -89,7 +90,7 @@ describe('KPI integración con autoridad global', () => { 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); - const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1))); + const req = requests(); expect(req).toHaveLength(1); req.forEach((r,i) => r.flush(response(i+1))); }); it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => { load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges(); @@ -99,18 +100,18 @@ describe('KPI integración con autoridad global', () => { try { page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges(); expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i])); - expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7].slice(0, count)); + expect(panels().map(p => p.result().value)).toEqual([5, 7].slice(0, count)); expect(page.filters).toBe(state); expect(state).toEqual(snapshot); const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null; if (count) { - expect(grid!.children).toHaveLength(count); - expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count)); + expect(grid!.children).toHaveLength(count + 1); + expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 1)); } else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); http.expectNone(() => true); page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges(); const added = requests(); expect(added).toHaveLength(0); added.forEach((r, i) => r.flush(response(count + i))); - expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot); + expect(panels()).toHaveLength(2); expect(state).toEqual(snapshot); } finally { page.kpisByDomain.cacu = definitions; } }); it('retirar un ID del catálogo conserva los otros KPI y los filtros', () => { @@ -118,7 +119,7 @@ describe('KPI integración con autoridad global', () => { const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters); page.catalog.set(page.catalog().slice(1)); fixture.detectChanges(); expect(panels()).toEqual(before.slice(1)); expect(page.filters).toEqual(filters); - expect(panels()).toHaveLength(2); http.expectNone(() => true); + expect(panels()).toHaveLength(1); http.expectNone(() => true); }); it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => { const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges(); @@ -138,7 +139,7 @@ describe('KPI integración con autoridad global', () => { load('cacu'); const before = panels(); const data = response(1); if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1; - if (scenario === 'nulo') data.filas[0]['valor'] = null; + 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); @@ -150,22 +151,22 @@ describe('KPI integración con autoridad global', () => { fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] }))); http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges(); - expect(panels()).toHaveLength(3); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true); + expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); }); it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => { for (const domain of ['cacu', 'cama'] as const) { load(domain); - const req = requests(); expect(req).toHaveLength(3); + const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length); req.forEach((r, i) => r.flush(response(i, domain))); fixture.detectChanges(); const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')]; expect(cards).toHaveLength(3); - expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', '40.0', '7']); - expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', '%', 'días (mediana)']); - expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(['Disponible', 'Disponible', 'Disponible']); + 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.map(card => card.textContent)).toEqual(expect.arrayContaining([ - expect.stringContaining('2025-S1'), expect.stringContaining('2 de 5'), + expect.stringContaining('2025-S1'), expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`), ])); expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); @@ -193,7 +194,7 @@ describe('KPI integración con autoridad global', () => { } load('cacu', false, ['2025-S1'], true); expect(fixture.componentInstance.initialPeriodBlocked).toBe(false); - expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true); + expect(panels().map(p => p.result().value)).toEqual([5, 7]); http.expectNone(() => true); }); it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => { load('cacu', false, ['2025-S2', '2025-S1'], true); @@ -213,7 +214,7 @@ describe('KPI integración con autoridad global', () => { expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true); fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' }; fixture.componentInstance.applyFilters(); fixture.detectChanges(); - const latest = requests(); expect(latest).toHaveLength(3); + const latest = requests(); expect(latest).toHaveLength(2); latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true); }); diff --git a/src/app/features/indicadores/indicadores-cacu-final.spec.ts b/src/app/features/indicadores/indicadores-cacu-final.spec.ts new file mode 100644 index 0000000..a0135e1 --- /dev/null +++ b/src/app/features/indicadores/indicadores-cacu-final.spec.ts @@ -0,0 +1,196 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { ActivatedRoute, provideRouter } from '@angular/router'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +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'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub {} +const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({ + id, titulo, contrato, tipos_periodo: ['semestre', 'mes'], + figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1', +}); +const catalog = [ + item('cacu_eu13', 'Tasa de confirmació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'), + item('cacu_eu7', 'Distribución de resultados citológicos', 'C2'), +]; +const periods = ['2025-S1', '2025-S2']; +const multi: PlotlyFigure = { data: [{ type: 'scatter', x: periods, y: [null, 25], + customdata: [[null, 0, 1], [1, 4, 0]], text: ['Suprimido', '1 de 4'], mode: 'markers' }], layout: {} }; + +describe('CaCu: oportunidad y selección independiente de todos los reportes', () => { + let fixture: ReturnType>; + let page: IndicadoresPage, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), + { provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }, + provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu'); + fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + http = TestBed.inject(HttpTestingController); + http.expectOne('/cacu/indicadores').flush(structuredClone(catalog)); + // Real inventory and KPI consumers: only the two published KPI request data. + for (;;) { + const requests = http.match(r => r.url.endsWith('/periodos')); + if (!requests.length) break; + for (const r of requests) r.flush({ id: r.request.url.split('/')[3], + periodos: periods.map(periodo => ({ periodo, tipo: 'semestre' })) }); + } + fixture.detectChanges(); + const requests = http.match(r => r.url.endsWith('/datos')); + expect(requests.map(r => r.request.url)).toEqual([ + '/cacu/indicadores/cacu_eu7/datos', '/cacu/indicadores/cacu_dias_toma_diagnostico/datos', + ]); + for (const r of requests) { + const id = r.request.url.split('/')[3], contrato = id === 'cacu_eu7' ? 'C2' : 'C3r'; + r.flush({ id, contrato, tipo_periodo: 'semestre', periodos: ['2025-S2'], categorias: { A: {} }, + filas: [{ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 5, suprimido: 0, + mediana: 7, q1: 3, q3: 9, unidad: 'dias' }] }); + } + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); + const card = (id: string) => cards().find(c => c.indicador.id === id)!; + const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)) + .map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!; + function open(...ids: string[]) { ids.forEach(id => card(id).setVisible(true)); fixture.detectChanges(); } + function figure(id: string) { return http.expectOne('/cacu/indicadores/' + id + '/figuras/fig_c1_puntos?tema=claro'); } + function apply(tipo: 'mes' | 'semestre', selected: [string, ...string[]]) { + page.filters!.tipo = tipo; + 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', () => { + 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', + ]); + 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'); + 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', () => { + 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(); + 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); + }); + it('inicializa las dos figuras en Todos con reporte aunque el filtro general ya sea mensual; conserva carga diferida', () => { + apply('mes', ['2026-01']); + http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] })); + http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url)); + open('cacu_eu13', 'ind1'); + for (const id of ['cacu_eu13', 'ind1']) { + const r = figure(id); expect(r.request.params.has('periodos')).toBe(false); + expect(panel(id).applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }); + r.flush(multi); + } + expect(panel('cacu_eu13').applied).not.toBe(panel('ind1').applied); + fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('Selección independiente: Todos con reporte (semestres)'); + }); + it('Aplicar no altera selección, datos, representación, host ni GET de las independientes; las ordinarias sí cambian', () => { + open('cacu_eu13', 'ind1', 'ordinary'); + for (const id of ['cacu_eu13', 'ind1', 'ordinary']) figure(id).flush(multi); + fixture.detectChanges(); + const retained = ['cacu_eu13', 'ind1'].map(id => ({ id, card: card(id), panel: panel(id), + applied: panel(id).applied, result: panel(id).result() })); + const hosts = Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart')); + card('cacu_eu13').localSelection = { parent: 'own' }; + card('ind1').localSelection = { parent: 'different' }; + for (const [tipo, selected] of [['semestre', ['2025-S1']], ['mes', ['2026-01']]] as const) { + apply(tipo, [...selected]); + http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url)); + const r = http.expectOne(r => r.url.includes('/ordinary/figuras/')); + expect(r.request.params.get('periodos')).toBe(selected[0]); r.flush(multi); + http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], + contrato: 'C2', tipo_periodo: tipo, periodos: [], filas: [] })); + for (const old of retained) { + expect(card(old.id)).toBe(old.card); expect(panel(old.id)).toBe(old.panel); + expect(panel(old.id).applied).toBe(old.applied); expect(panel(old.id).result()).toBe(old.result); + expect(panel(old.id).result().figure).toEqual(multi); + } + } + expect(card('cacu_eu13').localSelection).toEqual({ parent: 'own' }); + expect(card('ind1').localSelection).toEqual({ parent: 'different' }); + expect(Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'))).toEqual(hosts); + expect(panel('ind1').result().figure!.data[0]['x']).toEqual(periods); + expect(panel('ind1').result().figure!.data[0]['y']).toEqual([null, 25]); + }); + it('resumen abierto reutiliza snapshots propios y no consulta los periodos del filtro general', () => { + open('cacu_eu13', 'ind1'); + figure('cacu_eu13').flush(multi); figure('ind1').flush(multi); + TestBed.inject(IndicadoresSnapshots).expanded.set(true); fixture.detectChanges(); + const requests = http.match(r => r.url.endsWith('/datos')); + expect(requests).toHaveLength(2); + for (const r of requests) { + expect(r.request.params.has('periodos')).toBe(false); + r.flush({ id: r.request.url.split('/')[3], contrato: 'C1', tipo_periodo: 'semestre', periodos: periods, + filas: [{ periodo: periods[0], grupo: 'principal', estrato: null, valor: 25, numerador: 1, denominador: 4, suprimido: 0 }, + { periodo: periods[1], grupo: 'principal', estrato: null, valor: 50, numerador: 5, denominador: 10, suprimido: 0 }] }); + } + 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'); + figure('cacu_eu13').flush({}, { status: 503, statusText: 'Unavailable' }); figure('ind1').flush(multi); + const other = panel('ind1').result(); + panel('cacu_eu13').requestFigure(); + const retry = figure('cacu_eu13'); expect(retry.request.params.has('periodos')).toBe(false); retry.flush({ data: [], layout: {} }); + expect(panel('ind1').result()).toBe(other); + page.catalog.update(items => items.map(i => i.id === 'cacu_eu13' ? { ...i, version: '2' } : i)); fixture.detectChanges(); + const revalidated = figure('cacu_eu13'); expect(revalidated.request.params.has('periodos')).toBe(false); revalidated.flush(multi); + expect(panel('ind1').result()).toBe(other); + }); + it('la política por ID solo afecta CaCu y ninguna otra gráfica', () => { + const general = page.filters!.applied; + for (const domain of ['tea', 'cama'] as const) for (const id of ['cacu_eu13', 'ind1', 'cacu_eu7']) { + expect(figureApplied(domain, id, general)).toBe(general); + } + expect(figureApplied('cacu', 'cacu_eu7', general)).toBe(general); + }); +}); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts index e12645c..49b17da 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -36,12 +36,15 @@ describe('EU7 modelo de presentación del entregable', () => { it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => { const m = model(), f = barras(m, {}, 'claro'); m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8)); + expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(m.escenarios.map(s => `${s.den}`)); const selected = barras(m, { grupo: 'ANORMAL' }, 'claro'); expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1))) .toEqual(['5.0', '24.3', '21.7', '7.8']); const category = barras(m, { categoria: 'LIEAG' }, 'claro'); expect(category.data).toHaveLength(1); expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); + expect((category.layout['annotations'] as { text: string }[]).map(a => a.text)) + .toEqual(m.escenarios.map(s => `${(100 * s.celdas['LIEAG'].n! / s.den!).toFixed(1)} % (${s.celdas['LIEAG'].n}/${s.den})`)); expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); }); it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => { diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index 0ca3531..3e8c505 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -225,12 +225,14 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }; }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, - margin: { t: 24, l: 150, r: 36, b: 90 }, showlegend: false, + margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false, yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true }, xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid, - range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 100] }, + range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112], + tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] }, annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false, font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' - : sel.grupo || sel.categoria ? `${sumas[i]!.toFixed(1)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${s.den})` : '' })), + : sel.grupo || sel.categoria ? `${sumas[i]!.toFixed(1)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` + : miles(s.den) })), }, config: { displayModeBar: false } }; } diff --git a/src/app/features/indicadores/indicadores-figure-selection.ts b/src/app/features/indicadores/indicadores-figure-selection.ts new file mode 100644 index 0000000..d1da340 --- /dev/null +++ b/src/app/features/indicadores/indicadores-figure-selection.ts @@ -0,0 +1,19 @@ +import { Dominio } from './indicadores.models'; +import { GlobalApplied } from './indicadores-memory'; + +// Presentation policy only. Each indicator owns a stable selection and revision; +// no global Apply can invalidate its figure or numeric snapshot. Omitting periodos +// delegates to the existing backend contract for all reported semesters. +const cacuSelections = new Map( + ['cacu_eu13', 'ind1'].map(id => [id, Object.freeze({ + tipo: 'semestre' as const, selection: Object.freeze({ mode: 'todos' as const }), revision: 0, + })]), +); + +export function independentFigurePeriods(domain: Dominio, id: string) { + return domain === 'cacu' && cacuSelections.has(id); +} + +export function figureApplied(domain: Dominio, id: string, general: GlobalApplied): GlobalApplied { + return domain === 'cacu' ? cacuSelections.get(id) ?? general : general; +} diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 495b9ff..308507f 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -33,7 +33,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); const inventory = http.match(r => r.url.endsWith('/periodos')); - expect(inventory).toHaveLength(4); // The anchor search shares the catalog inventory request. + expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request. inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) })); fixture.detectChanges(); }); @@ -41,14 +41,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid function data(index: number, period: string, value = 7) { const d = definitions[index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: [period], categorias: { A: {} }, filas: [{ - periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0, + periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0, valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] }; } function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } - function flushPanels(period: string, expected = 2) { + function flushPanels(period: string, expected = definitions.length - 1) { const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(expected); requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); @@ -101,7 +101,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[1]] }); expect(page.filters!.editors.semestre!.draft).toEqual(page.filters!.applied.selection); expect(pending(page.filters!)).toBe(false); expect(editor().selectedPeriods).toEqual([periods[1]]); - expect(panels()).toHaveLength(3); + expect(panels()).toHaveLength(definitions.length); expect(panels().every(p => p.applied === page.filters!.applied && !p.initialPresentation && p.temporalReference === periods[1])).toBe(true); expect(panels()[0].result().value).toBe(7); http.expectNone(() => true); }); @@ -114,13 +114,13 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid }); it('KPI secundarios sin datos no retroceden a otro periodo', () => { request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); - const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(2); + const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(definitions.length - 1); requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); }); fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true); }); it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => { choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true); - page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3); + page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] }); editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]); expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true); @@ -135,7 +135,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready'); }); it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => { - choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3); + choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length); page.changeDominio(otherDomain); http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges(); page.changeDominio('tea'); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); @@ -148,7 +148,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid }); it('Aplicar Todos durante búsqueda cancela y respeta la decisión manual', () => { const old = request(periods[0]); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false); - page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], 3); + page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], definitions.length); expect(page.filters!.applied.selection.mode).toBe('todos'); expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true); }); it('error HTTP queda visible, sin datos mezclados, con reintento funcional', () => { @@ -175,7 +175,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid expect(editor().selectedPeriods).toEqual([periods[2]]); expect(panels()).toHaveLength(0); http.expectNone(() => true); page.retryCatalog(); http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); expect(editor().selectedPeriods).toEqual([periods[2]]); expect(page.initialPeriodState()).toBe('manual'); http.expectNone(() => true); - page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3); + page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length); expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true); }); it('un ancla retirada del catálogo requiere selección manual y no consulta datos retirados', () => { @@ -189,7 +189,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0])); }); fixture.detectChanges(); - expect(panels()).toHaveLength(2); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true); + expect(panels()).toHaveLength(definitions.length - 1); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true); }); it('inicializa y restaura los tres dominios con periodos propios sin repetir datos resueltos', () => { choose(); @@ -205,8 +205,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges(); http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] })); const payload = (index: number) => { - const value = data(index, period); value.id = definitions[index].id; - value.filas[0].grupo = index === 1 && target !== 'tea' ? 'total' : 'TOTAL'; return value; + const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato; + value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value; }; http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges(); http.match(r => r.url.endsWith('/datos')).forEach(r => { diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index 0d1f655..9db24f4 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -1,14 +1,17 @@ -import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi'; +import { KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi'; import { GlobalApplied } from './indicadores-memory'; import { Dominio, IndicadorDatos } from './indicadores.models'; const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 }; const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 }; +// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI. +const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0], + { id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] }; function data(domain: Dominio, index: number, filas: Record[]): IndicadorDatos { - const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas }; + const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas }; } describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => { const c1Group = domain === 'tea' ? 'TOTAL' : 'total'; - const run = (index: number, rows: Record[]) => kpiResult(data(domain, index, rows), KPI_BY_DOMAIN[domain][index], domain, applied); + const run = (index: number, rows: Record[]) => kpiResult(data(domain, index, rows), definitions[domain][index], domain, applied); it('C2 suma categorías disjuntas del único TOTAL incluyendo SIN_DATO y cero', () => { expect(run(0, [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'SIN_DATO', n: 0 }]).value).toBe(5); expect(run(0, [{ ...total, categoria: 'A', n: 0 }]).value).toBe(0); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index b8bc560..12f08c4 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -14,7 +14,6 @@ export const KPI_BY_DOMAIN: Record = { ], cacu: [ { id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, - { id: 'cacu_eu13', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, { id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, ], cama: [ diff --git a/src/app/features/indicadores/indicadores-numeric-summary.ts b/src/app/features/indicadores/indicadores-numeric-summary.ts index ffc0566..6f51f9d 100644 --- a/src/app/features/indicadores/indicadores-numeric-summary.ts +++ b/src/app/features/indicadores/indicadores-numeric-summary.ts @@ -4,6 +4,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador import { KpiDefinition } from './indicadores-kpi'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { numericRows } from './indicadores-numeric-rows'; +import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; @Component({ selector: 'app-indicadores-numeric-summary', @@ -27,17 +28,17 @@ import { numericRows } from './indicadores-numeric-rows'; } } @for (item of catalog; track item.id) { - @let reading = snapshots.reading(dominio, item, applied); + @let reading = snapshots.reading(dominio, item, figureSelection(item)); @let compatible = compatibility(item); @if (compatible.compatible && reading?.status === 'ready' && reading?.data; as data) { @for (row of rows(data); track $index) { {{ item.titulo }}{{ row.period }}{{ row.group }} · {{ row.category }} {{ row.value }} {{ row.detail }}{{ row.state }} {{ data.notas?.join(' ') }} } @empty { - {{ item.titulo }}{{ period }}—Sin filas publicadas{{ data.notas?.join(' ') }} + {{ item.titulo }}{{ figurePeriod(item) }}—Sin filas publicadas{{ data.notas?.join(' ') }} } } @else { - {{ item.titulo }}{{ period }}—No disponible + {{ item.titulo }}{{ figurePeriod(item) }}—No disponible {{ !compatible.compatible ? compatible.reason : reading?.status === 'loading' ? 'Cargando…' : reading?.status === 'error' ? 'Error de consulta: ' + reading?.message : 'Pendiente: consulta la gráfica para cargar sus números.' }} @if (reading?.status === 'error') { } } @@ -75,7 +76,13 @@ export class IndicadoresNumericSummary implements OnDestroy { get period() { return describePeriods(this.applied.tipo, this.applied.selection); } key(item: Indicador) { return snapshotKey(this.dominio, item, this.applied); } find(id: string) { return this.catalog.find(item => item.id === id); } - compatibility(item: Indicador) { return filterCompatibility(this.applied, item.tipos_periodo); } + figureSelection(item: Indicador) { return figureApplied(this.dominio, item.id, this.applied); } + figurePeriod(item: Indicador) { + const selection = this.figureSelection(item); + return (independentFigurePeriods(this.dominio, item.id) ? 'Selección independiente: ' : '') + + describePeriods(selection.tipo, selection.selection); + } + compatibility(item: Indicador) { return filterCompatibility(this.figureSelection(item), item.tipos_periodo); } toggle(event: Event) { this.snapshots.expanded.set((event.target as HTMLDetailsElement).open); } ngOnDestroy() { this.snapshots.expanded.set(false); } } diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 33124c2..3910d6e 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -16,7 +16,7 @@ @if (!catalogLoading() && filters; as state) {

Filtros generales de {{ domainLabels[dominio] }}

-

La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.

+

{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}

@@ -40,19 +40,22 @@ @let kpis = availableKpis; @if (kpis.length && !initialPeriodBlocked) {
-

Indicadores destacados

-
+

{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}

+
@for (definition of kpis; track dominio + ':' + definition.id) { } + @if (dominio === 'cacu') { + + }
}
-

Indicadores gráficos

+

{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}

@if (!catalogLoading() && !catalogError() && catalog().length) {

{{ catalog().length }} indicadores publicados

} @@ -90,7 +93,7 @@ }
@for (item of searchResults().items; track cardIdentity(item)) { - }
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 6844565..8506a77 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -18,6 +18,8 @@ import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { KPI_BY_DOMAIN } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorKpiCard } from './indicador-kpi-card'; +import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; import { indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; @@ -30,7 +32,7 @@ type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -241,6 +243,8 @@ export class IndicadoresPage { dominio: Dominio = 'tea'; readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; readonly kpisByDomain = KPI_BY_DOMAIN; + figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); } + independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); } kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } private readonly catalogRequests = new Subject(); @@ -248,7 +252,11 @@ export class IndicadoresPage { readonly searchQuery = signal(''); readonly searchVisible = computed(() => this.catalog().length >= 5); readonly searchResults = computed(() => { - const items = this.catalog(); + const catalog = this.catalog(); + // Stable presentation priority; search matches and pins still take precedence. + const items = this.dominio === 'cacu' + ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] + : catalog; const query = this.normalizeSearch(this.searchQuery()); const prioritize = (group: Indicador[]) => [ ...group.filter(item => this.isPinned(item)), diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts index d68ff6e..b6de598 100644 --- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -34,7 +34,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { function data(index: number, domain: Dominio, period: string, suppressed = false): 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: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A', + periodo: period, grupo: d.contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0, }] }; } @@ -56,9 +56,9 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos')); const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges(); const requests = flushDatos(domain); - expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S1']); - expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S1', '2026-S1']); - expect(panels().map(p => p.result().value)).toEqual([4, '0.0', 0]); + expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1')); + expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1')); + expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]); expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] }); expect(fixture.componentInstance.filters!.applied.revision).toBe(1); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); @@ -89,7 +89,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador'); expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); fixture.componentInstance.applyFilters(); fixture.detectChanges(); - const single = flushDatos('cacu'); expect(single).toHaveLength(3); + const single = flushDatos('cacu'); expect(single).toHaveLength(2); expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true); control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true); fixture.componentInstance.applyFilters(); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 0fe4166..d85ef6a 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -17,6 +17,9 @@ @for (s of statuses; track s.codigo) { } + From e6be341ad92b99010024d020fd8d542513d83512 Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 24 Oct 2026 18:17:54 +0000 Subject: [PATCH 33/51] =?UTF-8?q?Redondeo=20=C3=BAnico=20de=20porcentajes?= =?UTF-8?q?=20y=20etiqueta=20de=20la=20=C3=BAltima=20citolog=C3=ADa=20sin?= =?UTF-8?q?=20resultado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - indicadores-format.ts: una regla para todo porcentaje mostrado. Una décima, medio hacia arriba; entre 0 y 0.1, la primera cifra significativa (0.04 %). De un conteo se calcula con enteros; de un valor publicado, sin sorpresas de coma flotante. La usan el resumen numérico (que mostraba el valor crudo, «0.6600660066 %»), los KPI, la dona, las barras y la tabla de EU7. - Seguimiento: la última citología sin Bethesda dice «Insatisfactoria» si su calidad lo es y «Sin resultado al corte» si no; antes las dos decían «No disponible», que queda para cuando no hay citología. CSO5.5 --- .../indicadores/cacu-seguimiento.spec.ts | 3 ++ .../indicadores/indicador-eu7-escenario.ts | 3 +- .../indicadores-eu7-escenario.spec.ts | 3 +- .../indicadores/indicadores-eu7-escenario.ts | 9 ++--- .../indicadores/indicadores-format.spec.ts | 24 ++++++++++++++ .../indicadores/indicadores-format.ts | 33 +++++++++++++++++++ .../features/indicadores/indicadores-kpi.ts | 3 +- .../indicadores/indicadores-numeric-rows.ts | 8 +++-- .../indicadores-numeric-summary.spec.ts | 4 +-- .../indicadores/indicadores-tracking.html | 2 +- .../indicadores/indicadores-tracking.ts | 7 +++- 11 files changed, 86 insertions(+), 13 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-format.spec.ts create mode 100644 src/app/features/indicadores/indicadores-format.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index f4650bb..8604caf 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -39,6 +39,9 @@ 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(); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.ts b/src/app/features/indicadores/indicador-eu7-escenario.ts index 0b38357..b6be0ba 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.ts @@ -8,6 +8,7 @@ import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './in import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { httpMessage } from './indicadores-http'; +import { percentText } from './indicadores-format'; import { stratifiedCapabilities } from './indicadores-stratified'; import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; @@ -64,7 +65,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { { escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]); } 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) { diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts index 49b17da..fd35bd1 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -1,6 +1,7 @@ import fixture from './fixtures/eu7-c2-ejemplos.json'; import { IndicadorDatos } from './indicadores.models'; import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario'; +import { percentNumber } from './indicadores-format'; function eu7Datos() { return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos }); @@ -44,7 +45,7 @@ describe('EU7 modelo de presentación del entregable', () => { expect(category.data).toHaveLength(1); expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); expect((category.layout['annotations'] as { text: string }[]).map(a => a.text)) - .toEqual(m.escenarios.map(s => `${(100 * s.celdas['LIEAG'].n! / s.den!).toFixed(1)} % (${s.celdas['LIEAG'].n}/${s.den})`)); + .toEqual(m.escenarios.map(s => `${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} % (${s.celdas['LIEAG'].n}/${s.den})`)); expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); }); it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => { diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index 3e8c505..04eaaa5 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -1,5 +1,6 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Theme } from './indicadores-c2-palette'; +import { percentNumber, shareText } from './indicadores-format'; // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. // This boundary is intentionally specific to EU7. Unknown cells never become zero. @@ -189,12 +190,12 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total; const rotulos = (values: number[], labels: string[], pct: boolean) => { const total = values.reduce((s, n) => s + n, 0); - return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `
${(100 * v / total).toFixed(0)} %` : '')); + return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `
${shareText(v, total)}` : '')); }; const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text', insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' }; const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes · %{customdata[1]} % del total con resultado' }; - const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]); + const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]); return { data: [ { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, text: [`${miles(centro)}
${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text }, @@ -220,7 +221,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const x = m.escenarios.map(s => porcentaje(s, c.id)); return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x, marker: { color: c.color, line: { color: p.background, width: 1 } }, - text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', + text: x.map(v => v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]), hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }; }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), @@ -232,7 +233,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] }, annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false, font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' - : sel.grupo || sel.categoria ? `${sumas[i]!.toFixed(1)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` + : sel.grupo || sel.categoria ? `${percentNumber(sumas[i]!)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` : miles(s.den) })), }, config: { displayModeBar: false } }; } diff --git a/src/app/features/indicadores/indicadores-format.spec.ts b/src/app/features/indicadores/indicadores-format.spec.ts new file mode 100644 index 0000000..c904b7a --- /dev/null +++ b/src/app/features/indicadores/indicadores-format.spec.ts @@ -0,0 +1,24 @@ +import { percentNumber, percentText, roundPercent, sharePercent, shareText } from './indicadores-format'; + +describe('regla de redondeo de porcentajes', () => { + it('una décima, medio hacia arriba, calculada con enteros', () => { + expect(sharePercent(2, 303)).toBe(0.7); + expect(sharePercent(1, 8)).toBe(12.5); + expect(sharePercent(1, 3)).toBe(33.3); + expect(sharePercent(2, 3)).toBe(66.7); + expect(shareText(0, 9)).toBe('0.0 %'); + expect(shareText(5, 5)).toBe('100.0 %'); + }); + it('entre 0 y 0.1, la primera cifra significativa', () => { + expect(shareText(1, 2000)).toBe('0.05 %'); + expect(shareText(1, 1600)).toBe('0.06 %'); + expect(percentText(0.0432)).toBe('0.04 %'); + }); + it('un porcentaje publicado redondea igual, sin sorpresas de coma flotante', () => { + expect(roundPercent(0.6600660066)).toBe(0.7); + expect(roundPercent(12.25)).toBe(12.3); + expect(roundPercent(1.005 * 10)).toBe(10.1); + expect(percentNumber(100)).toBe('100.0'); + expect(percentText(null)).toBe('No disponible'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-format.ts b/src/app/features/indicadores/indicadores-format.ts new file mode 100644 index 0000000..dbd30ef --- /dev/null +++ b/src/app/features/indicadores/indicadores-format.ts @@ -0,0 +1,33 @@ +// One rounding rule for every percentage shown: one decimal, half up; between 0 and 0.1 +// the first significant digit (0.04 %, not 0.0 %). Integer counts round exactly, without +// binary floating-point surprises (1.005 → 1.0 with toFixed). + +/** The percentage of `k` in `n`, rounded by the rule, computed from integers. */ +export function sharePercent(k: number, n: number): number { + if (k > 0 && 1000 * k < n) return Number((100 * k / n).toPrecision(1)); + return Math.floor((2000 * k + n) / (2 * n)) / 10; +} + +/** A published percentage (0 to 100), rounded by the rule. */ +export function roundPercent(value: number): number { + if (value > 0 && value < 0.1) return Number(value.toPrecision(1)); + // Snap to 9 decimals first so 12.25 published as 12.2499999999 still rounds up. + return Math.floor(Math.round(value * 1e9) / 1e8 + 0.5) / 10; +} + +/** Text of a rounded percentage: «12.3», «0.04», «100.0». */ +export function percentNumber(value: number): string { + const rounded = roundPercent(value); + return rounded > 0 && rounded < 0.1 ? String(rounded) : rounded.toFixed(1); +} + +/** «12.3 %» from a published percentage, or the fallback when there is none. */ +export function percentText(value: number | null | undefined, fallback = 'No disponible'): string { + return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback; +} + +/** «12.3 %» from a count over its denominator. */ +export function shareText(k: number, n: number): string { + const value = sharePercent(k, n); + return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`; +} diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 12f08c4..3c93d98 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -1,5 +1,6 @@ import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; +import { percentNumber } from './indicadores-format'; export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; } // Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML @@ -72,7 +73,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; - return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) }; + return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) }; } if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; diff --git a/src/app/features/indicadores/indicadores-numeric-rows.ts b/src/app/features/indicadores/indicadores-numeric-rows.ts index 94cfd39..8e83824 100644 --- a/src/app/features/indicadores/indicadores-numeric-rows.ts +++ b/src/app/features/indicadores/indicadores-numeric-rows.ts @@ -1,4 +1,5 @@ import { IndicadorDatos } from './indicadores.models'; +import { percentText } from './indicadores-format'; export interface NumericRow { period: string; group: string; category: string; value: string; detail: string; state: string; } const record = (value: unknown): value is Record => value !== null && typeof value === 'object' && !Array.isArray(value); @@ -6,6 +7,9 @@ function number(value: unknown, suffix = ''): string { if (value === null) return 'Sin valor (nulo)'; return typeof value === 'number' && Number.isFinite(value) ? `${value}${suffix}` : 'No disponible'; } +function percent(value: unknown): string { + return typeof value === 'number' ? percentText(value) : number(value); +} function label(dictionary: unknown, key: unknown, fallback: string): string { const entry = record(dictionary) && typeof key === 'string' ? dictionary[key] : undefined; return typeof entry === 'string' ? entry : record(entry) && typeof entry['etiqueta'] === 'string' ? entry['etiqueta'] : fallback; @@ -27,8 +31,8 @@ export function numericRows(data: IndicadorDatos): NumericRow[] { let primary: unknown; if (data.contrato === 'C1') { primary = row['valor']; - return { ...base, value: number(primary, ' %'), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', - detail: `Intervalo publicado: ${number(row['ic_bajo'])} a ${number(row['ic_alto'])} %. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` }; + return { ...base, value: percent(primary), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', + detail: `Intervalo publicado: ${percent(row['ic_bajo'])} a ${percent(row['ic_alto'])}. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` }; } if (data.contrato === 'C2') { primary = row['n']; diff --git a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts index da4f8b6..e5fd277 100644 --- a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts +++ b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts @@ -37,8 +37,8 @@ describe('MD-19 lecturas y celdas numéricas', () => { }); it('C1 conserva cero, intervalo publicado y poblaciones sin recalcular Wilson', () => { const row = numericRows(data('C1'))[0]; - expect(row.value).toBe('0 %'); expect(row.state).toBe('Disponible'); - expect(row.detail).toBe('Intervalo publicado: 0 a 16.1 %. Numerador: 0; denominador: 20.'); + expect(row.value).toBe('0.0 %'); expect(row.state).toBe('Disponible'); + expect(row.detail).toBe('Intervalo publicado: 0.0 % a 16.1 %. Numerador: 0; denominador: 20.'); }); it('C2 conserva categorías, grupos y conteos; no suma poblaciones superpuestas', () => { const sample = data(); sample['grupos'] = { other: 'Otra población' }; sample.filas.push({ ...sample.filas[0], grupo: 'other', n: 11 }); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index d85ef6a..2eded43 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -37,7 +37,7 @@ @for (item of response.items; track item.id_seudonimo) { {{ item.id_seudonimo }}{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} - @if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } + @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible } {{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }} diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index b0dba78..f0115e8 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -77,5 +77,10 @@ export class IndicadoresTracking implements OnChanges { if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return; this.load({ ...this.applied, page }); } - cytologyLabel(code: string | null) { return code === null ? 'No disponible' : this.categories[code]?.etiqueta ?? code; } + // The shown cytology is the patient's latest in the window. Without a Bethesda result it is either + // unsatisfactory (`cacu.calidad_insatisfactoria` in the kit) or not yet reported at the cut-off. + cytologyLabel(c: { bethesda: string | null; calidad: string | null }) { + if (c.bethesda !== null) return this.categories[c.bethesda]?.etiqueta ?? c.bethesda; + return c.calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte'; + } } From 03e51c07cc598455c114d55b527208771363f7bd Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 24 Oct 2026 21:04:57 +0000 Subject: [PATCH 34/51] =?UTF-8?q?feat(indicadores):=20panel=20de=20tasa=20?= =?UTF-8?q?de=20confirmaci=C3=B3n=20histopatol=C3=B3gica,=20tiempos=20pare?= =?UTF-8?q?ados=20y=20ficha=20t=C3=A9cnica?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agrega el panel de tasa de confirmación histopatológica (cacu_confirmacion_citologia): tasas por resultado citológico de alto grado con su intervalo de Wilson a la izquierda, dona del grado de biopsia a la derecha y tabla de contingencia; la vista base es «LIEAG o más» y las pacientes sin biopsia aún no entran al denominador. Une en una sola figura los tiempos de toma a resultado (pedido por id, oculto en el catálogo) y de toma a diagnóstico. La pestaña Datos y definiciones muestra la ficha técnica y las reglas del kit en tablas; las notas de cada figura pasan a su Cómo leer, las tarjetas dejan solo valor, n y periodo, y el Cómo leer de EU7 muestra solo lo que publica el kit. Las transiciones animadas quedan fuera, como entrega aparte para el diseñador. CSO5.5 --- .../indicadores/indicador-catalog-card.ts | 19 +- .../indicador-confirmacion-citologia.html | 75 ++++++ .../indicador-confirmacion-citologia.scss | 37 +++ .../indicador-confirmacion-citologia.ts | 140 ++++++++++ .../indicadores/indicador-eu7-escenario.html | 31 +-- .../indicadores/indicador-eu7-escenario.scss | 4 + .../indicador-eu7-escenario.spec.ts | 30 +++ .../indicadores/indicador-eu7-escenario.ts | 12 + .../indicadores/indicador-figure-card.html | 12 +- .../indicadores/indicador-figure-card.scss | 5 +- .../indicadores/indicador-figure-card.spec.ts | 20 +- .../indicadores/indicador-figure-card.ts | 26 +- .../indicadores/indicador-kpi-panel.spec.ts | 5 +- .../indicadores/indicador-metadata.scss | 14 +- .../indicadores/indicador-metadata.spec.ts | 34 ++- .../indicadores/indicador-metadata.ts | 52 +++- .../indicador-tiempos-pareados.html | 41 +++ .../indicador-tiempos-pareados.scss | 17 ++ .../indicadores/indicador-tiempos-pareados.ts | 131 ++++++++++ .../indicadores-c2-general-selection.spec.ts | 2 +- .../indicadores-cacu-final.spec.ts | 4 +- ...indicadores-confirmacion-citologia.spec.ts | 225 ++++++++++++++++ .../indicadores-confirmacion-citologia.ts | 244 ++++++++++++++++++ .../indicadores/indicadores-definitions.html | 6 +- .../indicadores/indicadores-definitions.ts | 13 +- .../indicadores-initial-integration.spec.ts | 16 +- .../indicadores-kpi-cama-real.spec.ts | 2 +- .../indicadores/indicadores-kpi.spec.ts | 4 +- .../features/indicadores/indicadores-kpi.ts | 4 +- .../indicadores/indicadores-methodology.ts | 17 +- .../indicadores-tiempos-pareados.spec.ts | 164 ++++++++++++ .../indicadores-tiempos-pareados.ts | 120 +++++++++ .../indicadores/indicadores.models.ts | 10 +- .../indicadores/indicadores.service.spec.ts | 26 ++ .../indicadores/indicadores.service.ts | 9 +- 35 files changed, 1465 insertions(+), 106 deletions(-) create mode 100644 src/app/features/indicadores/indicador-confirmacion-citologia.html create mode 100644 src/app/features/indicadores/indicador-confirmacion-citologia.scss create mode 100644 src/app/features/indicadores/indicador-confirmacion-citologia.ts create mode 100644 src/app/features/indicadores/indicador-tiempos-pareados.html create mode 100644 src/app/features/indicadores/indicador-tiempos-pareados.scss create mode 100644 src/app/features/indicadores/indicador-tiempos-pareados.ts create mode 100644 src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts create mode 100644 src/app/features/indicadores/indicadores-confirmacion-citologia.ts create mode 100644 src/app/features/indicadores/indicadores-tiempos-pareados.spec.ts create mode 100644 src/app/features/indicadores/indicadores-tiempos-pareados.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index eb2ef4a..ff1077f 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -17,11 +17,15 @@ import { filterCompatibility } from './indicadores-memory'; import { DonutSelection } from './indicadores-donut-drilldown'; import { IndicadoresService } from './indicadores.service'; import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; +import { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; +import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; +import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; +import { parTiempos } from './indicadores-tiempos-pareados'; @Component({ selector: 'app-indicador-catalog-card', - host: { '[class.dual-card]': 'isDual || isEu7' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario], + host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' }, + imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia], template: `
@@ -40,6 +44,14 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
+ } @else if (isConfirmacion) { +
+ +
+ } @else if (tiempos; as par) { +
+ +
} @else if (selectedFigure) { @if (!pair.length || otherFigures.length) { @@ -121,6 +133,9 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { } get pair() { return dualFigures(this.indicador); } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } + get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } + // Connected time pairs replace the diagnosis card with one coordinated box plot. + get tiempos() { return parTiempos(this.dominio, this.indicador.id); } get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.html b/src/app/features/indicadores/indicador-confirmacion-citologia.html new file mode 100644 index 0000000..cb58d3f --- /dev/null +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.html @@ -0,0 +1,75 @@ +
+

Filtro general aplicado: {{ appliedSummary }}

+ + @if (helpOpen) { +
+ @if (metadata) { + @for (guide of readingGuide; track guide.figura) { +
+

{{ guide.nombre }}

+ @if (guide.descripcion) {

{{ guide.descripcion }}

} + @if (guide.como_leer.length) {
    @for (line of guide.como_leer; track $index) {
  • {{ line }}
  • }
} +
+ } @empty {

El servicio no publica instrucciones de lectura para estas figuras.

} + } @else {

Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

} +
+ } + @switch (status()) { + @case ('deferred') {

La vista se cargará al acercarse a esta región.

} + @case ('loading') {

Cargando el mismo periodo para tasas y dona…

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + } + @if (status() === 'ready' || status() === 'empty') { + @if (periods.length > 1) { + + } + @if (model; as m) { +

{{ m.periodo }} · Selección: {{ selectionLabel }} · {{ reading }}

+ @if (status() === 'empty') {

No hay citologías de alto grado publicadas para este periodo.

} + @else { +
+ +
+ @for (g of m.grupos; track g.id; let i = $index) { + + } +
+
+ @for (c of m.grados; track c.id; let i = $index) { + + } +
+
+
+

Por resultado de la citología · {{ m.periodo }}

+ @if (ratesFigure) { + + } +
    + @for (t of rates; track t.fila.id) { @if (t.k === null) {
  • {{ t.fila.etiqueta }}: {{ estadoTasa(t) }}
  • } } +
+
+

Resultado de la biopsia · {{ m.periodo }}

+ @if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) { + + } @else {

{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}

} +
+
+ } + @for (note of m.notas; track $index) {

{{ note }}

} +
+ + @for (g of m.grados; track g.id) { }@for (a of m.aparte; track a.id) { } + @for (fila of m.filas; track fila.id) { + @for (g of m.grados; track g.id) { }@for (a of m.aparte; track a.id) { } + } +
Tabla de contingencia · {{ m.periodo }} · mujeres
Citología{{ g.etiqueta }}Con biopsia{{ a.etiqueta }}
{{ fila.etiqueta }}{{ cellText(fila.celdas[g.id]) }}{{ denText(fila.den, fila.estado) }}{{ cellText(fila.aparte[a.id]) }}
+
+ } + } +
diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.scss b/src/app/features/indicadores/indicador-confirmacion-citologia.scss new file mode 100644 index 0000000..c8a2798 --- /dev/null +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.scss @@ -0,0 +1,37 @@ +:host { display: block; min-width: 0; } +.confirmacion { min-width: 0; padding-top: var(--issste-space-3); } +p, h3, summary { overflow-wrap: anywhere; } +.applied-summary, .note { color: var(--issste-text-secondary); } +.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +.selection-status { font-weight: 600; } +.legend { display: grid; gap: .6rem; margin-block: 1rem; } +.keys { display: flex; flex-wrap: wrap; gap: .5rem; } +.legend > button { justify-self: start; } +button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border); + border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; } +.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; } +button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; } +button:disabled { opacity: .5; cursor: default; } +button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; } +.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; } +.figure { min-width: 0; border-top: 1px solid var(--issste-border); } +h3 { font-size: 1rem; line-height: 1.5; } +app-plotly-chart { --plot-height: 440px; } +.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; } +.periods span { text-align: center; } +.periods button { min-width: 44px; font-size: 1.5rem; } +summary { cursor: pointer; padding-block: .75rem; } +.table-scroll { overflow: auto; max-height: 28rem; } +table { border-collapse: collapse; width: 100%; margin-block: 1rem; } +th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } +caption { text-align: start; font-weight: 600; } +.reading-guide h3 { margin: 0 0 .25rem; } +.reading-guide + .reading-guide { margin-top: 1rem; } +.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; } +.reading-guide li + li { margin-top: .25rem; } +app-plotly-chart { --plot-height: 360px; } +.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); } +.rate-states:empty { display: none; } +/* Rates on the left, donut on the right (the reverse of EU7). */ +@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } } diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.ts b/src/app/features/indicadores/indicador-confirmacion-citologia.ts new file mode 100644 index 0000000..4a55021 --- /dev/null +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.ts @@ -0,0 +1,140 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION, + lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta, + Celda, tasas } from './indicadores-confirmacion-citologia'; + +// Figures of the kit whose "Cómo leer" describes this coordinated view. +const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const; + +@Component({ + selector: 'app-indicador-confirmacion-citologia', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicador-confirmacion-citologia.html', + styleUrl: './indicador-confirmacion-citologia.scss', +}) +export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); + message = ''; + selection?: SeleccionConfirmacion; + periods: string[] = []; + periodIndex = 0; + model?: ModeloConfirmacion; + donutFigure?: PlotlyFigure; + ratesFigure?: PlotlyFigure; + helpOpen = false; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + private pages: ModeloConfirmacion[] = []; + + get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } + get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } + get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } + get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } + get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; } + readonly estadoTasa = estadoTasa; + cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } + denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); } + get readingGuide() { + const details = this.metadata?.figuras_detalle ?? []; + return FIGURAS.flatMap(([figura, nombre]) => { + const detail = details.find(item => item.figura === figura); + const descripcion = detail?.descripcion?.trim() ?? ''; + const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); + return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; + }); + } + toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + ngOnChanges(changes: SimpleChanges) { + const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA }) + + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]); + if (key !== this.key) { + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; + this.clear(); + if (!this.visible) { this.status.set('deferred'); return; } + this.load(); + } else if (this.visible && !this.loaded) this.load(); + else if (this.model && changes['tema']) this.draw(); + } + retry() { if (this.visible) this.load(); } + private clear() { + this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined; + this.donutFigure = undefined; this.ratesFigure = undefined; + } + private load() { + this.subscription?.unsubscribe(); + this.loaded = true; this.clear(); + const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); + if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.'; + this.status.set('incompatible'); return; + } + const key = this.key; + const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, + { estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({ + next: datos => { + if (key !== this.key) return; + try { + this.periods = periodosConfirmacion(datos, this.applied.tipo, periods); + this.pages = this.periods.map(p => modeloConfirmacion(datos, p)); + // The most recent period first, as the prototype; navigation goes back. + this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod(); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.clear(); + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' + : error instanceof ConfirmacionIncompatible ? error.message : httpMessage(error); + this.status.set(error instanceof ConfirmacionIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); + } + private activatePeriod() { + this.model = this.pages[this.periodIndex]; + this.selection = this.model ? seleccionBase(this.model) : undefined; + this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty'); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.activatePeriod(); + } + select(trace: string, index = 0) { + if (!this.model || !this.selection || this.status() !== 'ready') return; + this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw(); + } + plotClicked(event: unknown) { + const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; + if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); + } + private draw() { + if (!this.model || !this.selection) return; + this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema); + this.ratesFigure = figuraTasas(this.model, this.selection, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html index 8eede8b..73ac50e 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.html +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -3,29 +3,14 @@ @if (helpOpen) {
-

El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.

-

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.

-

El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.

-

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.

-

Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.

- @if (metadata; as info) { - @if (info.descripcion) {

{{ info.descripcion }}

} - @if (info.ficha; as ficha) { - @if (ficha.pregunta) {

{{ ficha.pregunta }}

} - @if (ficha.definicion) {

{{ ficha.definicion }}

} - @if (ficha.unidad) {

Unidad: {{ ficha.unidad }}

} - @if (ficha.nota) {

{{ ficha.nota }}

} - } -
Metadatos publicados de las figuras originales -

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.

- @for (detail of info.figuras_detalle; track detail.figura) { - @if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') { -

{{ detail.descripcion }}

- @for (line of detail.como_leer; track $index) {

{{ line }}

} - } - } - @for (reference of info.referencias; track $index) {

{{ reference.etiqueta }} {{ reference.ref }}

} -
+ @if (metadata) { + @for (guide of readingGuide; track guide.figura) { +
+

{{ guide.nombre }}

+ @if (guide.descripcion) {

{{ guide.descripcion }}

} + @if (guide.como_leer.length) {
    @for (line of guide.como_leer; track $index) {
  • {{ line }}
  • }
} +
+ } @empty {

El servicio no publica instrucciones de lectura para estas figuras.

} } @else {

Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

}
} diff --git a/src/app/features/indicadores/indicador-eu7-escenario.scss b/src/app/features/indicadores/indicador-eu7-escenario.scss index 79a0c71..d197919 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.scss +++ b/src/app/features/indicadores/indicador-eu7-escenario.scss @@ -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; } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts index 56ff0ae..0120d8f 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -136,6 +136,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); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.ts b/src/app/features/indicadores/indicador-eu7-escenario.ts index b6be0ba..395e8d6 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.ts @@ -13,6 +13,8 @@ import { stratifiedCapabilities } from './indicadores-stratified'; import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; +const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const; + @Component({ selector: 'app-indicador-eu7-escenario', imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], @@ -64,6 +66,16 @@ 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 ?? []; + return EU7_FIGURES.flatMap(([figura, nombre]) => { + const detail = details.find(item => item.figura === figura); + const descripcion = detail?.descripcion?.trim() ?? ''; + const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); + return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; + }); + } cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } percentText(value: number | null) { return percentText(value); } toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index c2813dc..a267295 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -13,6 +13,12 @@ @for (line of interpretation; track $index) {
  • {{ line }}
  • }

    {{ periodInterpretation }}

    + @if (state.status === 'ready' && state.footnotes?.length) { +

    Notas de la figura

    +
    + @for (note of state.footnotes; track $index) {

    {{ note }}

    } +
    + }
    } @@ -92,11 +98,7 @@ }
    @if (state.categoryLabels?.length) { diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index 7b66cf7..03f1b6a 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -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; diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 0392a29..7bddb83 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -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', '', 'ID_'.repeat(150)]; + const notes = ['Nota de la ficha\nFuente: A & B · Fecha de corte: 2025-08-01\nLeyenda', '', '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: {} }; diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 101a918..1163b14 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -10,7 +10,7 @@ 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'; // The panel owns requests; the card receives the original and its presentation copy. @@ -143,23 +143,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; } } diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index db7b833..2622045 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -13,11 +13,14 @@ describe('KPI integración con autoridad global', () => { let fixture: ReturnType>; 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. diff --git a/src/app/features/indicadores/indicador-metadata.scss b/src/app/features/indicadores/indicador-metadata.scss index 9834ece..92d2cf1 100644 --- a/src/app/features/indicadores/indicador-metadata.scss +++ b/src/app/features/indicadores/indicador-metadata.scss @@ -2,13 +2,15 @@ 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; } +.rules-table code { overflow-wrap: anywhere; } +.rules-table td:nth-child(2) { min-width: 8rem; } @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; } } diff --git a/src/app/features/indicadores/indicador-metadata.spec.ts b/src/app/features/indicadores/indicador-metadata.spec.ts index 4c8b357..c767271 100644 --- a/src/app/features/indicadores/indicador-metadata.spec.ts +++ b/src/app/features/indicadores/indicador-metadata.spec.ts @@ -21,7 +21,7 @@ describe('Metadatos metodológicos opcionales', () => { expect(text).toContain('Guía '); 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,7 +32,35 @@ 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 las reglas con valor legible, estado y fuente', () => { + 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 para poder calcular.' }, + { clave: 'cacu.diagnostico.cie', valor: ['Z014', 'R87'], estado: 'confirmado', fuente: null }, + ], + }); + 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']); + const rules = fixture.nativeElement.querySelector('table.rules-table') as HTMLTableElement; + expect([...rules.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Clave', 'Valor', 'Estado', 'Fuente']); + const rows = [...rules.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell => cell.textContent)); + expect(rows).toEqual([ + ['cacu.horizontes.toma_diagnostico_dias', '180', 'Provisional', 'Arbitrario para poder calcular.'], + ['cacu.diagnostico.cie', 'Z014, R87', 'Confirmado', '—'], + ]); + expect(text).toContain('Reglas'); expect(text).not.toContain('no está disponible'); + http.verify(); fixture.destroy(); + }); + + it('muestra sólo reglas cuando no hay ficha', () => { + const { fixture, http, text } = render({ parametros: [{ clave: 'comun.umbral_supresion', valor: 5, estado: 'provisional' }] }); + expect(text).toContain('comun.umbral_supresion'); expect(text).not.toContain('Ficha técnica'); expect(text).not.toContain('no está disponible'); http.verify(); fixture.destroy(); }); @@ -56,7 +84,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(); }); diff --git a/src/app/features/indicadores/indicador-metadata.ts b/src/app/features/indicadores/indicador-metadata.ts index 4f0de55..ed887da 100644 --- a/src/app/features/indicadores/indicador-metadata.ts +++ b/src/app/features/indicadores/indicador-metadata.ts @@ -4,6 +4,21 @@ import { catchError, of, Subject, switchMap } from 'rxjs'; import { Dominio, IndicadorMetadatos } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; +const RULE_STATES: Record = { provisional: 'Provisional', confirmado: 'Confirmado' }; + +// Readable rule value: lists separated by commas, objects by their label when they carry one. +export function ruleValue(value: unknown): string { + if (value === null || value === undefined) return 'Sin definir'; + if (Array.isArray(value)) return value.length ? value.map(ruleValue).join(', ') : 'Lista vacía'; + if (typeof value === 'boolean') return value ? 'Sí' : 'No'; + if (typeof value === 'number') return value.toLocaleString('es-MX'); + if (typeof value === 'object') { + const label = (value as Record)['etiqueta']; + return typeof label === 'string' && label.trim() ? label : JSON.stringify(value); + } + return String(value); +} + @Component({ selector: 'app-indicador-metadata', styleUrl: './indicador-metadata.scss', @@ -17,10 +32,27 @@ import { IndicadoresService } from './indicadores.service'; } @if (fichaFields.length) {
    -

    Ficha metodológica

    -
    @for (field of fichaFields; track field.key) { -
    {{ field.label }}
    - }
    +

    Ficha técnica

    +
    + + @for (field of fichaFields; track field.key) { + + } +
    {{ field.label }}
    +
    +
    + } + @if (rules.length) { +
    +

    Reglas

    +
    + + + @for (rule of rules; track rule.clave) { + + } +
    ClaveValorEstadoFuente
    {{ rule.clave }}{{ rule.valor }}{{ rule.estado }}
    +
    } @if (references.length) { @@ -47,7 +79,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; } @@ -56,9 +88,17 @@ export class IndicadorMetadata implements OnChanges { const ficha = this.metadata?.ficha; return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : []; } + get rules() { + return (this.metadata?.parametros ?? []).map(rule => ({ + clave: rule.clave, + valor: ruleValue(rule.valor), + estado: RULE_STATES[rule.estado] ?? rule.estado, + fuente: this.hasText(rule.fuente) ? rule.fuente.trim() : '—', + })); + } get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); } get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); } - get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); } + get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.rules.length || this.references.length || this.populations.length); } constructor() { this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); }); } diff --git a/src/app/features/indicadores/indicador-tiempos-pareados.html b/src/app/features/indicadores/indicador-tiempos-pareados.html new file mode 100644 index 0000000..6040717 --- /dev/null +++ b/src/app/features/indicadores/indicador-tiempos-pareados.html @@ -0,0 +1,41 @@ +
    +

    Filtro general aplicado: {{ appliedSummary }}

    + + @if (helpOpen) { +
    + @for (guide of readingGuide; track guide.clave) { +
    +

    {{ guide.nombre }}

    + @if (guide.descripcion) {

    {{ guide.descripcion }}

    } + @if (guide.como_leer.length) {
      @for (line of guide.como_leer; track $index) {
    • {{ line }}
    • }
    } +
    + } +

    {{ caveat }}

    + @if (metadataPending) {

    Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

    } +
    + } + @switch (status()) { + @case ('deferred') {

    La vista se cargará al acercarse a esta región.

    } + @case ('loading') {

    Cargando los mismos periodos para los dos tiempos…

    } + @case ('error') {

    {{ message }}

    } + @case ('incompatible') {

    {{ message }}

    } + } + @if (model; as m) { +

    Días desde la toma: resultado y diagnóstico

    + @if (status() === 'empty') {

    No hay cajas publicadas para estos periodos.

    } + @else if (figure) { + + } + @for (note of m.notas; track $index) {

    {{ note }}

    } +
    Valores publicados y cajas no disponibles +
    + + @for (clave of claves; track clave) { } + @for (periodo of m.periodos; track periodo) { + @for (clave of claves; track clave) { } + } +
    Q1, mediana y Q3 en días por periodo
    Periodo{{ par.etiquetas[clave] }}
    {{ periodo }}{{ cajaTexto(m.cajas[clave][periodo]) }}
    +
    +
    + } +
    diff --git a/src/app/features/indicadores/indicador-tiempos-pareados.scss b/src/app/features/indicadores/indicador-tiempos-pareados.scss new file mode 100644 index 0000000..39b677b --- /dev/null +++ b/src/app/features/indicadores/indicador-tiempos-pareados.scss @@ -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; } diff --git a/src/app/features/indicadores/indicador-tiempos-pareados.ts b/src/app/features/indicadores/indicador-tiempos-pareados.ts new file mode 100644 index 0000000..ac2c4ac --- /dev/null +++ b/src/app/features/indicadores/indicador-tiempos-pareados.ts @@ -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(); + 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 = { 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(); } +} diff --git a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts index 26ca678..c51149c 100644 --- a/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-general-selection.spec.ts @@ -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']] }, diff --git a/src/app/features/indicadores/indicadores-cacu-final.spec.ts b/src/app/features/indicadores/indicadores-cacu-final.spec.ts index a0135e1..f0f908e 100644 --- a/src/app/features/indicadores/indicadores-cacu-final.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-final.spec.ts @@ -23,7 +23,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'), @@ -91,7 +91,7 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', ( 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'); + expect(root.querySelector('.kpi-section')?.textContent).not.toContain('detección histopatológica'); expect(card('cacu_eu13')).toBeDefined(); http.expectNone(() => true); }); diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts new file mode 100644 index 0000000..53da8d4 --- /dev/null +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts @@ -0,0 +1,225 @@ +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, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion, + periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { figure = input(); label = input(); showNotes = input(); plotClick = output(); } + +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 = { + '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(estadoTasa)).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']); + expect(m.filas[0].etiqueta).toBe('Carcinoma in situ'); + (d['totales_estrato'] as Record[])[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(['91.7 %
    11/12', '70.7 %
    41/58', '28.9 %
    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', '70.7 %
    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(['63
    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>; + 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); 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); + }); +}); diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts new file mode 100644 index 0000000..5c389e6 --- /dev/null +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts @@ -0,0 +1,244 @@ +import { 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; + +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; + // SIN_BIOPSIA and SIN_DATO cells, when the response publishes those categories. + aparte: Record; + // 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; conBiopsia: number | null; + aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; +} +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 => !!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, '>'); +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): 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[]): string[] { + if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA + || !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): ModeloConfirmacion { + periodosConfirmacion(datos, datos.tipo_periodo); + 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 LIEAG ("LIEAG o más"): the true positives. + const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.'); + if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.'); + const index = new Map>(); + 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 de citología 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 de citología inválidos.'); + const filas = FILAS_CITOLOGIA.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[]).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 ?? [])] }; +} + +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)?.grados ?? []; +} +export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string { + return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta; +} +/** 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) return 'Verdaderos positivos (valor predictivo positivo)'; + if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión'; + if (!sel.categoria) return 'Sin confirmación de alto grado'; + 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): string { + return t.fila.den === 0 ? 'Sin mujeres 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)!.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), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]), + hovertemplate: '%{y}
    %{customdata[0]} (%{customdata[1]}/%{customdata[2]})
    IC 95 %: %{customdata[3]}–%{customdata[4]} %', + }], 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) : `${shareText(t.k, t.fila.den!)}
    ${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}
    %{customdata[0]} mujeres con biopsia · %{customdata[1]}' }; + 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: [`${miles(k)}
    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) + '' }, + { ...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 } }; +} diff --git a/src/app/features/indicadores/indicadores-definitions.html b/src/app/features/indicadores/indicadores-definitions.html index 4a2ee18..26e6a2e 100644 --- a/src/app/features/indicadores/indicadores-definitions.html +++ b/src/app/features/indicadores/indicadores-definitions.html @@ -29,10 +29,6 @@ @if (item.tipos_periodo.length) {
      @for (tipo of item.tipos_periodo; track tipo) {
    • {{ periodNames[tipo] }}
    • }
    } @else {

    Pendiente de información.

    } -

    Cómo interpretar este indicador

    - @if (interpretation(item).length) { -
      @for (line of interpretation(item); track $index) {
    • {{ line }}
    • }
    - } @if (opened.has(dominio + ':' + item.id)) { } @else { @@ -52,5 +48,5 @@
  • Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.
  • 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.
  • -

    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.

    +

    Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. El botón «Cómo leer» de cada gráfica explica cómo interpretarla e incluye sus notas.

    diff --git a/src/app/features/indicadores/indicadores-definitions.ts b/src/app/features/indicadores/indicadores-definitions.ts index 011cae5..d2afd31 100644 --- a/src/app/features/indicadores/indicadores-definitions.ts +++ b/src/app/features/indicadores/indicadores-definitions.ts @@ -2,7 +2,7 @@ import { Component, Input, output } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { Dominio, Indicador, TipoPeriodo } from './indicadores.models'; import { figureDisplayName } from './indicadores-figure-labels'; -import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; +import { PERIOD_INTERPRETATION } from './indicadores-methodology'; import { IndicadorMetadata } from './indicador-metadata'; @Component({ @@ -24,15 +24,4 @@ export class IndicadoresDefinitions { readonly figureDisplayName = figureDisplayName; readonly periodInterpretation = PERIOD_INTERPRETATION; get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; } - interpretation(item: Indicador) { - if (!item.contrato) return []; - const lines = contractInterpretation(item.contrato, this.dominio); - // Catalog metadata does not describe the traces. Keep the shared C2 guidance - // independent of bars/sectors; the actual figure retains its full explanation. - return lines.filter(line => - !line.includes('Los valores nulos o suprimidos') && - !line.includes('Los puntos suprimidos') && - !line.includes('No hay una explicación específica disponible'), - ).slice(item.contrato === 'C2' ? 1 : 0); - } } diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 308507f..5fa68c5 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -22,7 +22,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const definitions = KPI_BY_DOMAIN[domain]; const otherDomain = domain === 'cacu' ? 'cama' : 'cacu'; const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })), - { id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }]; + // Two figures, so every domain keeps an ordinary card whose representation can change. + { id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f', 'g'] }]; beforeEach(() => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); @@ -108,9 +109,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => { choose(); http.expectNone(r => r.url.includes('/figuras/')); cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); }); - // EU7 now owns a coordinated C2 view. This temporal fixture publishes only - // placeholder f/g figures, so that card must stop as incompatible, without GET. - fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true); + // EU7 and the CaCu paired times own coordinated views. This temporal fixture publishes + // only placeholder f/g figures, so EU7 stops as incompatible without GET; the paired times + // ask /datos for the same shared period, including the partner hidden from the catalog. + fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length); + const tiempos = http.match(r => r.url.endsWith('/datos')); + expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(domain === 'cacu'); + for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); } + http.expectNone(() => true); }); it('KPI secundarios sin datos no retroceden a otro periodo', () => { request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); @@ -128,7 +134,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => { choose(); const applied = page.filters!.applied; page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true); - const card = cards().find(card => !card.isEu7)!; + const card = cards().find(card => !card.isEu7 && !card.tiempos)!; card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1); card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1); expect(card.selectedFigure).toBe('g'); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts index a7675bc..93285fd 100644 --- a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts @@ -140,6 +140,6 @@ describe('KPI de CaMa con respuestas reales de WebApi', () => { }); it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => { expect(result(2).state).toBe('Disponible'); - expect(result(2).info).toContain('El horizonte de 180 días es provisional.'); + expect(result(2).info).toMatch(/^[\d.,]+ mastografías; Q1 a Q3: [\d.]+ a [\d.]+ días\.$/); }); }); diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index 9db24f4..edd3d15 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -21,10 +21,10 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => { expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6'); expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0'); }); - it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => { + it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => { const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]); expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días'); - if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional'); + expect(result.info).not.toContain('provisional'); }); it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => { expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' }); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 3c93d98..106e49b 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -32,8 +32,8 @@ const C1_INFO: Record strin }; const C3R_INFO: Record string> = { tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`, - cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, - cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`, + cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días.`, + cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`, }; export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; } const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); diff --git a/src/app/features/indicadores/indicadores-methodology.ts b/src/app/features/indicadores/indicadores-methodology.ts index 53b5f87..1d2fccf 100644 --- a/src/app/features/indicadores/indicadores-methodology.ts +++ b/src/app/features/indicadores/indicadores-methodology.ts @@ -1,7 +1,7 @@ import { Dominio, IndicadorMetadatos } from './indicadores.models'; -// Existing WebApp explanations, shared by figures and the definitions section. -// These are editorial guidance, not additional metadata supplied by WebApi. +// Editorial fallback for a figure whose metadata publishes no `como_leer` +// (metadata not loaded yet, failed, or an older kit). Not WebApi metadata. const CONTRACT_INTERPRETATIONS: Readonly> = { C1: [ 'El punto representa la proporción observada.', @@ -17,14 +17,15 @@ const CONTRACT_INTERPRETATIONS: Readonly> = { }; export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.'; -export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined { - const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId); - if (!detail) return undefined; - const instructions = detail.como_leer ?? []; - return instructions.some(line => line.trim().length > 0) ? instructions : undefined; +// "Cómo leer" of a figure: the kit's `como_leer` when it publishes one, otherwise +// the generic guidance of the figure's contract. +export function figureInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string, + contract: string | undefined, domain: Dominio, pie = false): readonly string[] { + const instructions = metadata?.figuras_detalle?.find(item => item.figura === figureId)?.como_leer ?? []; + return instructions.some(line => line.trim().length > 0) ? instructions : contractInterpretation(contract, domain, pie); } -export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] { +function contractInterpretation(contract: string | undefined, domain: Dominio, pie: boolean): readonly string[] { if (contract === 'C2') return [ pie ? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.' diff --git a/src/app/features/indicadores/indicadores-tiempos-pareados.spec.ts b/src/app/features/indicadores/indicadores-tiempos-pareados.spec.ts new file mode 100644 index 0000000..98a331e --- /dev/null +++ b/src/app/features/indicadores/indicadores-tiempos-pareados.spec.ts @@ -0,0 +1,164 @@ +import { Component, input } 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 { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; +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 { figuraTiempos, modeloTiempos, PARES_TIEMPOS, parTiempos, TiemposIncompatibles } from './indicadores-tiempos-pareados'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { figure = input(); label = input(); showNotes = input(); } + +const par = PARES_TIEMPOS.find(p => p.dominio === 'cacu')!; +const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C3r', version: '1', figuras: ['fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] }); +const diagnostico = item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico'); +const reporte = item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado'); +const row = (periodo: string, n: number | null, q1: number | null, mediana: number | null, q3: number | null, suprimido = 0) => + ({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' }); +function datos(id: string, filas: Record[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos { + return { id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' }; +} +const lab = () => datos(reporte.id, [row('2025-S1', 120, 7, 12, 20), row('2025-S2', 98, 6, 10, 18)]); +const dx = () => datos(diagnostico.id, [row('2025-S1', 3, null, null, null, 1), row('2025-S2', 40, 30, 52, 90)]); + +describe('Tiempos pareados: modelo y figura', () => { + it('una caja por indicador y periodo; suprimidos y nulos nunca se dibujan como cero', () => { + const m = modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre'); + expect(m.periodos).toEqual(['2025-S1', '2025-S2']); + expect(m.cajas.diagnostico['2025-S1']).toEqual({ estado: 'Suprimido' }); + expect(m.cajas.reporte['2025-S2']).toEqual({ estado: 'Publicado', n: 98, q1: 6, mediana: 10, q3: 18 }); + const f = figuraTiempos(m, par, 'claro'); + expect(f.layout['boxmode']).toBe('group'); + expect(f.data.map(t => t['name'])).toEqual(['Toma → resultado (laboratorio)', 'Toma → diagnóstico']); + expect(f.data.map(t => t['type'])).toEqual(['box', 'box']); + expect(f.data[0]['marker']).not.toEqual(f.data[1]['marker']); + expect(f.data[0]['x']).toEqual(['2025-S1', '2025-S2']); + expect(f.data[1]['x']).toEqual(['2025-S2']); + expect(f.data[1]).toMatchObject({ q1: [30], median: [52], q3: [90], lowerfence: [30], upperfence: [90] }); + expect(f.data[1]['customdata']).toEqual([['40', '30', '52', '90']]); + expect(f.data[1]['hovertemplate']).toContain('n = %{customdata[0]} citologías'); + expect(f.data[1]['hovertemplate']).toContain('Mediana: %{customdata[2]} días'); + expect(JSON.stringify(f.data)).not.toContain('null'); + expect(figuraTiempos(m, par, 'oscuro').layout['paper_bgcolor']).toBe('#081839'); + }); + it('cuartiles incompletos o desordenados quedan no disponibles', () => { + const d = datos(diagnostico.id, [row('2025-S1', 4, 5, 3, 9), row('2025-S2', 0, 0, 0, 0)]); + const m = modeloTiempos(par, { reporte: lab(), diagnostico: d }, 'semestre'); + expect(m.cajas.diagnostico['2025-S1'].estado).toBe('No disponible'); + expect(m.cajas.diagnostico['2025-S2'].estado).toBe('No disponible'); + }); + it('rechaza datos de otro indicador, contrato, periodo o con dos totales por periodo', () => { + expect(() => modeloTiempos(par, { reporte: dx(), diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles); + expect(() => modeloTiempos(par, { reporte: { ...lab(), contrato: 'C1' }, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles); + expect(() => modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre', ['2025-S2'])).toThrow(TiemposIncompatibles); + const twice = datos(reporte.id, [row('2025-S1', 1, 1, 1, 1), row('2025-S1', 2, 2, 2, 2)]); + expect(() => modeloTiempos(par, { reporte: twice, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles); + }); + it('el par de CaMa existe pero solo CaCu está conectado', () => { + expect(parTiempos('cacu', 'cacu_dias_toma_diagnostico')).toBe(par); + expect(parTiempos('cacu', 'cacu_eu_tiempo_reporte')).toBeUndefined(); + expect(PARES_TIEMPOS.some(p => p.dominio === 'cama' && p.diagnostico === 'cama_dias_toma_diagnostico')).toBe(true); + expect(parTiempos('cama', 'cama_dias_toma_diagnostico')).toBeUndefined(); + }); +}); + +describe('Tiempos pareados: componente', () => { + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, revision: 1 }; + let f: ReturnType>; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorTiemposPareados, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + f = TestBed.createComponent(IndicadorTiemposPareados); + f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('par', par); + f.componentRef.setInput('indicador', diagnostico); + f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); + }); + afterEach(() => { f.destroy(); http.verify(); }); + function flush(a = lab(), b = dx()) { + const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos'); + const d = http.expectOne(req => req.url === '/cacu/indicadores/cacu_dias_toma_diagnostico/datos'); + expect(r.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + expect(d.request.params.get('periodos')).toBe(r.request.params.get('periodos')); + r.flush(a); d.flush(b); f.detectChanges(); + } + it('carga diferida; dos GET de los mismos periodos; una gráfica y tabla con supresión', () => { + 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'); + const charts = f.debugElement.queryAll(By.directive(ChartStub)); + expect(charts).toHaveLength(1); + expect((charts[0].componentInstance as ChartStub).figure()).toBe(f.componentInstance.figure); + const text = f.nativeElement.querySelector('table').textContent as string; + expect(text).toContain('Suprimido'); expect(text).toContain('mediana 52'); + f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); + expect(f.componentInstance.figure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); + }); + it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => { + f.detectChanges(); + flush(datos(reporte.id, [row('2025-S1', 2, null, null, null, 1)]), datos(diagnostico.id, [])); + expect(f.componentInstance.status()).toBe('empty'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + expect(f.nativeElement.textContent).toContain('No hay cajas publicadas'); + }); + it('con filtro incompatible u otro indicador no hay GET', () => { + f.componentRef.setInput('indicador', { ...diagnostico, tipos_periodo: ['mes'] }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + f.componentRef.setInput('indicador', { ...diagnostico, contrato: 'C1' }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + }); + it('la pareja oculta del catálogo se pide por id; un 404 se anuncia como error, sin cajas', () => { + f.detectChanges(); + http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos' && req.params.get('periodos') === '2025-S1,2025-S2').flush({}, { status: 404, statusText: 'Not Found' }); + http.match(req => req.url.includes('cacu_dias_toma_diagnostico')); + f.detectChanges(); + expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('error HTTP se anuncia y el reintento vuelve a pedir', () => { + f.detectChanges(); + http.expectOne(req => req.url.includes('cacu_eu_tiempo_reporte')).flush({}, { status: 500, statusText: 'Error' }); + http.match(req => req.url.includes('cacu_dias_toma_diagnostico')); + f.detectChanges(); expect(f.componentInstance.status()).toBe('error'); + f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready'); + }); + it('«Cómo leer» muestra el como_leer de las dos figuras y la advertencia de poblaciones distintas', () => { + 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('Metadatos publicados pendientes'); + http.expectOne('/cacu/indicadores/cacu_eu_tiempo_reporte/metadatos').flush({ ficha: { nota: 'No va' }, + figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: null, como_leer: ['Caja del laboratorio.'] }] }); + f.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: 'Caja de diagnóstico.', como_leer: ['Lee el diagnóstico.'] }] }); + f.detectChanges(); + const help = f.nativeElement.querySelector('.methodology') as HTMLElement; + expect([...help.querySelectorAll('.reading-guide h3')].map(h => h.textContent)).toEqual(['Toma → resultado (laboratorio)', 'Toma → diagnóstico']); + expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Caja del laboratorio.', 'Lee el diagnóstico.']); + expect(help.querySelector('.caveat')!.textContent).toContain('no es el tiempo del tramo intermedio'); + expect(help.textContent).not.toContain('No va'); expect(help.textContent).not.toContain('pendientes'); + }); + it('la tarjeta de CaCu sustituye el diagnóstico por la vista pareada; las demás quedan igual', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const card = TestBed.createComponent(IndicadorCatalogCard); + card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', diagnostico); + card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges(); + const view = card.debugElement.query(By.directive(IndicadorTiemposPareados)); + expect(view).not.toBeNull(); + expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0); + for (const [domain, indicator] of [['cacu', reporte], ['cama', { ...diagnostico, id: 'cama_dias_toma_diagnostico' }]] as const) { + card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', indicator); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorTiemposPareados))).toHaveLength(0); + expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(1); + } + card.destroy(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-tiempos-pareados.ts b/src/app/features/indicadores/indicadores-tiempos-pareados.ts new file mode 100644 index 0000000..9fb6e38 --- /dev/null +++ b/src/app/features/indicadores/indicadores-tiempos-pareados.ts @@ -0,0 +1,120 @@ +import { Dominio, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models'; +import { C2_PALETTE, c2Theme } from './indicadores-c2-palette'; + +// Two C3r indicators that share the sample date (toma) and differ in their end +// event: the lab result and the diagnosis note. They are drawn side by side per +// period so the slower stretch is visible. C3r publishes only Q1, median and Q3: +// no individual observations, so boxes have no whiskers and no violin is possible. +export interface ParTiempos { + dominio: Dominio; + reporte: string; + diagnostico: string; + estudios: string; + etiquetas: { reporte: string; diagnostico: string }; + // Only connected pairs replace the diagnosis card in the catalog. + conectado: boolean; +} +export const PARES_TIEMPOS: readonly ParTiempos[] = [ + { dominio: 'cacu', reporte: 'cacu_eu_tiempo_reporte', diagnostico: 'cacu_dias_toma_diagnostico', estudios: 'citologías', + etiquetas: { reporte: 'Toma → resultado (laboratorio)', diagnostico: 'Toma → diagnóstico' }, conectado: true }, + { dominio: 'cama', reporte: 'cama_eu38a', diagnostico: 'cama_dias_toma_diagnostico', estudios: 'mastografías', + etiquetas: { reporte: 'Toma → resultado', diagnostico: 'Toma → diagnóstico' }, conectado: false }, +]; +export function parTiempos(dominio: Dominio, id: string): ParTiempos | undefined { + return PARES_TIEMPOS.find(par => par.conectado && par.dominio === dominio && par.diagnostico === id); +} +export const FIGURA_C3R = 'fig_c3r_caja'; + +export type Clave = 'reporte' | 'diagnostico'; +export const CLAVES: readonly Clave[] = ['reporte', 'diagnostico']; +export interface Caja { + estado: 'Publicado' | 'Suprimido' | 'No disponible'; + n?: number; q1?: number; mediana?: number; q3?: number; +} +export interface ModeloTiempos { periodos: string[]; cajas: Record>; notas: string[]; } +export class TiemposIncompatibles extends Error {} + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0; +const fail = (message: string): never => { throw new TiemposIncompatibles(message); }; + +function caja(fila: Record | undefined): Caja { + if (!fila) return { estado: 'No disponible' }; + if (fila['suprimido'] === 1) return { estado: 'Suprimido' }; + const { n, q1, mediana, q3 } = fila; + // Null quantiles are not zeros: without a complete published box nothing is drawn. + if (fila['suprimido'] !== 0 || !conteo(n) || n === 0 || !finito(q1) || !finito(mediana) || !finito(q3) + || q1 < 0 || q1 > mediana || mediana > q3) return { estado: 'No disponible' }; + return { estado: 'Publicado', n, q1, mediana, q3 }; +} + +/** Two immutable C3r /datos payloads -> boxes per period, without mixing groups or strata. */ +export function modeloTiempos(par: ParTiempos, datos: Record, tipo: TipoPeriodo, + solicitados?: readonly string[]): ModeloTiempos { + const cajas = { reporte: {}, diagnostico: {} } as Record>; + for (const clave of CLAVES) { + const d = datos[clave]; + if (d.id !== par[clave] || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) + || new Set(d.periodos).size !== d.periodos.length + || (solicitados && d.periodos.some(p => !solicitados.includes(p)))) { + fail('Los datos de tiempos no corresponden al indicador o al periodo aplicado.'); + } + for (const fila of d.filas) { + if (!registro(fila) || typeof fila['periodo'] !== 'string' || !d.periodos.includes(fila['periodo'])) fail('Fila C3r fuera de los periodos publicados.'); + if (fila['grupo'] !== 'TOTAL' || fila['estrato'] != null) continue; + if (fila['unidad'] !== undefined && fila['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.'); + const periodo = fila['periodo'] as string; + if (cajas[clave][periodo]) fail('Más de una fila total por periodo.'); + cajas[clave][periodo] = caja(fila); + } + for (const periodo of d.periodos) cajas[clave][periodo] ??= { estado: 'No disponible' }; + } + const periodos = solicitados ? [...solicitados] + : [...new Set([...datos.reporte.periodos, ...datos.diagnostico.periodos])].sort(); + for (const clave of CLAVES) for (const periodo of periodos) cajas[clave][periodo] ??= { estado: 'No disponible' }; + return { periodos, cajas, notas: [...new Set([...(datos.reporte.notas ?? []), ...(datos.diagnostico.notas ?? [])])] }; +} + +export function hayCajas(m: ModeloTiempos): boolean { + return CLAVES.some(clave => m.periodos.some(p => m.cajas[clave][p].estado === 'Publicado')); +} + +const COLORES: Record = { reporte: C2_PALETTE.series[0], diagnostico: C2_PALETTE.series[2] }; +function rgba(hex: string, alfa: number): string { + const v = parseInt(hex.slice(1), 16); + return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; +} +const dias = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 }); + +/** Grouped boxes from published quartiles; whiskers equal the box (fences are unknown). */ +export function figuraTiempos(m: ModeloTiempos, par: ParTiempos, tema: Tema): PlotlyFigure { + const p = c2Theme(tema); + const data = CLAVES.map(clave => { + const periodos = m.periodos.filter(periodo => m.cajas[clave][periodo].estado === 'Publicado'); + const cajas = periodos.map(periodo => m.cajas[clave][periodo]); + return { + type: 'box', name: par.etiquetas[clave], legendgroup: clave, x: periodos, + q1: cajas.map(c => c.q1), median: cajas.map(c => c.mediana), q3: cajas.map(c => c.q3), + lowerfence: cajas.map(c => c.q1), upperfence: cajas.map(c => c.q3), + marker: { color: COLORES[clave] }, line: { color: COLORES[clave], width: 2 }, fillcolor: rgba(COLORES[clave], .35), + customdata: cajas.map(c => [c.n!.toLocaleString('es-MX'), dias(c.q1!), dias(c.mediana!), dias(c.q3!)]), + hoveron: 'boxes', + hovertemplate: `${par.etiquetas[clave]}
    %{x}
    n = %{customdata[0]} ${par.estudios}` + + '
    Q1: %{customdata[1]} días
    Mediana: %{customdata[2]} días
    Q3: %{customdata[3]} días', + }; + }); + return { data, layout: { + boxmode: 'group', autosize: true, height: 440, showlegend: true, + legend: { orientation: 'h', x: 0, y: 1.02, xanchor: 'left', yanchor: 'bottom' }, + paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, + margin: { t: 48, l: 64, r: 16, b: 56 }, + xaxis: { type: 'category', categoryorder: 'array', categoryarray: m.periodos, title: { text: 'Periodo' } }, + yaxis: { title: { text: 'días' }, rangemode: 'tozero', gridcolor: p.grid, zeroline: false }, + }, config: { displayModeBar: false } }; +} + +export function cajaTexto(c: Caja): string { + return c.estado !== 'Publicado' ? c.estado + : `n = ${c.n!.toLocaleString('es-MX')} · Q1 ${dias(c.q1!)} · mediana ${dias(c.mediana!)} · Q3 ${dias(c.q3!)} días`; +} diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index aa083d2..4b76b63 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -17,7 +17,7 @@ export interface Indicador { tipos_periodo: TipoPeriodo[]; filtros?: IndicadorFiltro[]; } -export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento'; +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado'; export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; } @@ -40,9 +40,17 @@ export interface IndicadorFiguraDetalle { descripcion: string | null; como_leer: string[] | null; } +// A rule the kit used to compute the indicator (horizon, code lists, thresholds). +export interface IndicadorParametro { + clave: string; + valor: unknown; + estado: string; + fuente?: string | null; +} export interface IndicadorMetadatos { descripcion?: string | null; ficha?: IndicadorFicha | null; + parametros?: IndicadorParametro[] | null; referencias?: { tipo: string; etiqueta: string; ref: string | null }[] | null; poblaciones?: { grupo: string; codigo: string; descripcion: string }[] | null; figuras_detalle?: IndicadorFiguraDetalle[] | null; diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 615f775..ffaf934 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -48,6 +48,32 @@ describe('IndicadoresService HTTP', () => { expect(error).toBeInstanceOf(Error); }); + it('acepta parámetros publicados con valores de cualquier tipo y fuente opcional', () => { + const parametros = [ + { clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario para poder calcular.' }, + { clave: 'cacu.diagnostico.cie', valor: ['Z014', 'R87'], estado: 'provisional', fuente: null }, + { clave: 'comun.umbral_supresion', valor: 5, estado: 'confirmado' }, + ]; + let value: unknown, nulo: unknown; + service.metadatos('cacu', 'p').subscribe(v => value = v); + http.expectOne('/cacu/indicadores/p/metadatos').flush({ parametros }); + service.metadatos('cacu', 'n').subscribe(v => nulo = v); + http.expectOne('/cacu/indicadores/n/metadatos').flush({ parametros: null }); + expect(value).toMatchObject({ parametros }); expect(nulo).toMatchObject({ parametros: null }); + }); + it.each([ + { parametros: 'incorrecto' }, + { parametros: [{ clave: '', valor: 1, estado: 'provisional' }] }, + { parametros: [{ clave: 'a', estado: 'provisional' }] }, + { parametros: [{ clave: 'a', valor: 1, estado: 1 }] }, + { parametros: [{ clave: 'a', valor: 1, estado: 'confirmado', fuente: 2 }] }, + ])('rechaza parámetros mal formados $parametros', payload => { + let error: unknown; + service.metadatos('cacu', 'i').subscribe({ error: value => error = value }); + http.expectOne('/cacu/indicadores/i/metadatos').flush(payload); + expect(error).toBeInstanceOf(Error); + }); + it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => { service.catalogo(dominio).subscribe(items => { expect(items).toEqual(syntheticCatalogs[dominio]); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index 48d783d..8992c02 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -40,6 +40,13 @@ export class IndicadoresService { if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos'); } } + const parameters = value['parametros']; + if (parameters !== undefined && parameters !== null && (!Array.isArray(parameters) || !parameters.every(v => record(v) + && typeof v['clave'] === 'string' && v['clave'].trim().length > 0 && Object.hasOwn(v, 'valor') + && typeof v['estado'] === 'string' + && (v['fuente'] === undefined || v['fuente'] === null || typeof v['fuente'] === 'string')))) { + throw new Error('Metadatos inválidos'); + } for (const field of ['referencias', 'poblaciones']) { const list = value[field]; if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias' @@ -66,7 +73,7 @@ export class IndicadoresService { } let params = new HttpParams(); if (scope.estrato) { - if (!['grupo_edad', 'estatus_seguimiento'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); + if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); params = params.set('estrato', scope.estrato); } if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(',')); From 12a039890353363ecac82eba4c85b78fea0f6468 Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 24 Oct 2026 22:11:33 +0000 Subject: [PATCH 35/51] refactor(indicadores): quitar la tabla de reglas de datos y definiciones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Las reglas de cálculo que publica el kit en `parametros` (clave, valor, estado y fuente) irán en un apéndice o manual técnico aparte, no en la pestaña «Datos y definiciones». Se quita la tabla «Reglas» y su formato de valores, y la pestaña conserva la ficha técnica, las referencias y las poblaciones. También se retiran el tipo y la validación estricta de `parametros` en el servicio: ya nadie los usa y una lista mal formada bloqueaba los metadatos completos. Si el servidor envía `parametros`, se ignoran. CSO5.5 --- .../indicadores/indicador-metadata.scss | 2 - .../indicadores/indicador-metadata.spec.ts | 22 +++-------- .../indicadores/indicador-metadata.ts | 38 +------------------ .../indicadores/indicadores.models.ts | 8 ---- .../indicadores/indicadores.service.spec.ts | 27 ++----------- .../indicadores/indicadores.service.ts | 7 ---- 6 files changed, 11 insertions(+), 93 deletions(-) diff --git a/src/app/features/indicadores/indicador-metadata.scss b/src/app/features/indicadores/indicador-metadata.scss index 92d2cf1..241f185 100644 --- a/src/app/features/indicadores/indicador-metadata.scss +++ b/src/app/features/indicadores/indicador-metadata.scss @@ -9,8 +9,6 @@ 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; } -.rules-table code { overflow-wrap: anywhere; } -.rules-table td:nth-child(2) { min-width: 8rem; } @media (max-width: 36rem) { .ficha-table th { width: 6rem; } } diff --git a/src/app/features/indicadores/indicador-metadata.spec.ts b/src/app/features/indicadores/indicador-metadata.spec.ts index c767271..2de1889 100644 --- a/src/app/features/indicadores/indicador-metadata.spec.ts +++ b/src/app/features/indicadores/indicador-metadata.spec.ts @@ -37,31 +37,21 @@ describe('Metadatos metodológicos opcionales', () => { http.verify(); fixture.destroy(); }); - it('presenta la ficha en una tabla y las reglas con valor legible, estado y fuente', () => { + 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 para poder calcular.' }, - { clave: 'cacu.diagnostico.cie', valor: ['Z014', 'R87'], estado: 'confirmado', fuente: null }, - ], + 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']); - const rules = fixture.nativeElement.querySelector('table.rules-table') as HTMLTableElement; - expect([...rules.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Clave', 'Valor', 'Estado', 'Fuente']); - const rows = [...rules.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell => cell.textContent)); - expect(rows).toEqual([ - ['cacu.horizontes.toma_diagnostico_dias', '180', 'Provisional', 'Arbitrario para poder calcular.'], - ['cacu.diagnostico.cie', 'Z014, R87', 'Confirmado', '—'], - ]); - expect(text).toContain('Reglas'); expect(text).not.toContain('no está disponible'); + 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('muestra sólo reglas cuando no hay ficha', () => { + 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('comun.umbral_supresion'); expect(text).not.toContain('Ficha técnica'); - expect(text).not.toContain('no está disponible'); + expect(text).toContain('no está disponible'); expect(text).not.toContain('comun.umbral_supresion'); http.verify(); fixture.destroy(); }); diff --git a/src/app/features/indicadores/indicador-metadata.ts b/src/app/features/indicadores/indicador-metadata.ts index ed887da..d2d0bc0 100644 --- a/src/app/features/indicadores/indicador-metadata.ts +++ b/src/app/features/indicadores/indicador-metadata.ts @@ -4,21 +4,6 @@ import { catchError, of, Subject, switchMap } from 'rxjs'; import { Dominio, IndicadorMetadatos } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -const RULE_STATES: Record = { provisional: 'Provisional', confirmado: 'Confirmado' }; - -// Readable rule value: lists separated by commas, objects by their label when they carry one. -export function ruleValue(value: unknown): string { - if (value === null || value === undefined) return 'Sin definir'; - if (Array.isArray(value)) return value.length ? value.map(ruleValue).join(', ') : 'Lista vacía'; - if (typeof value === 'boolean') return value ? 'Sí' : 'No'; - if (typeof value === 'number') return value.toLocaleString('es-MX'); - if (typeof value === 'object') { - const label = (value as Record)['etiqueta']; - return typeof label === 'string' && label.trim() ? label : JSON.stringify(value); - } - return String(value); -} - @Component({ selector: 'app-indicador-metadata', styleUrl: './indicador-metadata.scss', @@ -42,19 +27,6 @@ export function ruleValue(value: unknown): string {
    } - @if (rules.length) { -
    -

    Reglas

    -
    - - - @for (rule of rules; track rule.clave) { - - } -
    ClaveValorEstadoFuente
    {{ rule.clave }}{{ rule.valor }}{{ rule.estado }}
    -
    -
    - } @if (references.length) {

    Referencias

    @@ -88,17 +60,9 @@ export class IndicadorMetadata implements OnChanges { const ficha = this.metadata?.ficha; return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : []; } - get rules() { - return (this.metadata?.parametros ?? []).map(rule => ({ - clave: rule.clave, - valor: ruleValue(rule.valor), - estado: RULE_STATES[rule.estado] ?? rule.estado, - fuente: this.hasText(rule.fuente) ? rule.fuente.trim() : '—', - })); - } get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); } get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); } - get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.rules.length || this.references.length || this.populations.length); } + get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); } constructor() { this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); }); } diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 4b76b63..f40a8d4 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -40,17 +40,9 @@ export interface IndicadorFiguraDetalle { descripcion: string | null; como_leer: string[] | null; } -// A rule the kit used to compute the indicator (horizon, code lists, thresholds). -export interface IndicadorParametro { - clave: string; - valor: unknown; - estado: string; - fuente?: string | null; -} export interface IndicadorMetadatos { descripcion?: string | null; ficha?: IndicadorFicha | null; - parametros?: IndicadorParametro[] | null; referencias?: { tipo: string; etiqueta: string; ref: string | null }[] | null; poblaciones?: { grupo: string; codigo: string; descripcion: string }[] | null; figuras_detalle?: IndicadorFiguraDetalle[] | null; diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index ffaf934..81baa21 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -48,30 +48,11 @@ describe('IndicadoresService HTTP', () => { expect(error).toBeInstanceOf(Error); }); - it('acepta parámetros publicados con valores de cualquier tipo y fuente opcional', () => { - const parametros = [ - { clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario para poder calcular.' }, - { clave: 'cacu.diagnostico.cie', valor: ['Z014', 'R87'], estado: 'provisional', fuente: null }, - { clave: 'comun.umbral_supresion', valor: 5, estado: 'confirmado' }, - ]; - let value: unknown, nulo: unknown; + it('ignora parametros: ni los valida ni bloquea los metadatos aunque vengan mal formados', () => { + let value: unknown; service.metadatos('cacu', 'p').subscribe(v => value = v); - http.expectOne('/cacu/indicadores/p/metadatos').flush({ parametros }); - service.metadatos('cacu', 'n').subscribe(v => nulo = v); - http.expectOne('/cacu/indicadores/n/metadatos').flush({ parametros: null }); - expect(value).toMatchObject({ parametros }); expect(nulo).toMatchObject({ parametros: null }); - }); - it.each([ - { parametros: 'incorrecto' }, - { parametros: [{ clave: '', valor: 1, estado: 'provisional' }] }, - { parametros: [{ clave: 'a', estado: 'provisional' }] }, - { parametros: [{ clave: 'a', valor: 1, estado: 1 }] }, - { parametros: [{ clave: 'a', valor: 1, estado: 'confirmado', fuente: 2 }] }, - ])('rechaza parámetros mal formados $parametros', payload => { - let error: unknown; - service.metadatos('cacu', 'i').subscribe({ error: value => error = value }); - http.expectOne('/cacu/indicadores/i/metadatos').flush(payload); - expect(error).toBeInstanceOf(Error); + http.expectOne('/cacu/indicadores/p/metadatos').flush({ descripcion: 'Descripción', parametros: 'incorrecto' }); + expect(value).toMatchObject({ descripcion: 'Descripción' }); }); it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => { diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index 8992c02..025e81a 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -40,13 +40,6 @@ export class IndicadoresService { if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos'); } } - const parameters = value['parametros']; - if (parameters !== undefined && parameters !== null && (!Array.isArray(parameters) || !parameters.every(v => record(v) - && typeof v['clave'] === 'string' && v['clave'].trim().length > 0 && Object.hasOwn(v, 'valor') - && typeof v['estado'] === 'string' - && (v['fuente'] === undefined || v['fuente'] === null || typeof v['fuente'] === 'string')))) { - throw new Error('Metadatos inválidos'); - } for (const field of ['referencias', 'poblaciones']) { const list = value[field]; if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias' From 6f3e7e22f916db91f1df5043098125816882b5db Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 25 Oct 2026 01:04:14 +0000 Subject: [PATCH 36/51] fix(indicadores): decir intervalo de tiempo en lugar de granularidad MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El filtro general y sus mensajes de compatibilidad nombran «Intervalo de tiempo» (semestre o mes) en lugar de «Granularidad», que no es un término clínico. Cambian la etiqueta del selector y los cinco mensajes que la mencionan; las pruebas que citaban esos textos se ajustan. CSO5.5 --- src/app/features/indicadores/indicador-figure-card.spec.ts | 4 ++-- src/app/features/indicadores/indicador-kpi-initial.spec.ts | 2 +- src/app/features/indicadores/indicador-period-filters.html | 6 +++--- .../features/indicadores/indicadores-global-filters.spec.ts | 2 +- .../features/indicadores/indicadores-initial-period.spec.ts | 2 +- src/app/features/indicadores/indicadores-memory.spec.ts | 2 +- src/app/features/indicadores/indicadores-memory.ts | 6 +++--- src/app/features/indicadores/indicadores.service.spec.ts | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 7bddb83..4199b1a 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -292,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(); diff --git a/src/app/features/indicadores/indicador-kpi-initial.spec.ts b/src/app/features/indicadores/indicador-kpi-initial.spec.ts index c712fd5..829a22f 100644 --- a/src/app/features/indicadores/indicador-kpi-initial.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-initial.spec.ts @@ -33,7 +33,7 @@ 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')); diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html index 7a12fe8..2b83d2d 100644 --- a/src/app/features/indicadores/indicador-period-filters.html +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -1,9 +1,9 @@
    @if (state.tipo === 'mes') {

    Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.

    } -@if (!types.includes(state.tipo)) {

    La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.

    } +@if (!types.includes(state.tipo)) {

    El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.

    }
    @if (types.length > 1 || !types.includes(state.tipo)) { - Granularidad + Intervalo de tiempo @for (tipo of types; track tipo) { {{ tipo === 'mes' ? 'Mes' : 'Semestre' }} } @@ -36,7 +36,7 @@ @else if (availability.status === 'error') {

    No se pudo completar la consulta de periodos disponibles.

    - } @else if (!options.length) {

    Sin reportes disponibles para esta granularidad.

    } + } @else if (!options.length) {

    Sin reportes disponibles para este intervalo de tiempo.

    } @if (entry.draft.mode === 'explicit' && unavailableSelection.length) {

    La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.

    } } @if (!availability && entry.draft.mode !== 'todos') { diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts index 9750138..ac69008 100644 --- a/src/app/features/indicadores/indicadores-global-filters.spec.ts +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -114,7 +114,7 @@ describe('D.2 integración de autoridad global y consumidores', () => { expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined(); http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false); - expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('granularidad mes'); + expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de tiempo mes'); expect((host as HTMLElement).parentElement!.hidden).toBe(true); r.flush({ data: [], layout: {} }); expect(fixture.nativeElement.textContent).not.toContain('Todos los meses'); diff --git a/src/app/features/indicadores/indicadores-initial-period.spec.ts b/src/app/features/indicadores/indicadores-initial-period.spec.ts index d27810c..3284c83 100644 --- a/src/app/features/indicadores/indicadores-initial-period.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-period.spec.ts @@ -74,7 +74,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma const run = start(); http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush('', { status: 404, statusText: 'Missing' }); expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true); }); - it.each(['semestre', 'mes'] as const)('busca únicamente la granularidad activa %s, sin mezclar tipos ni usar un mes más reciente', tipo => { + it.each(['semestre', 'mes'] as const)('busca únicamente el intervalo de tiempo activo %s, sin mezclar tipos ni usar un mes más reciente', tipo => { const run = start(tipo); inventory(['2026-12', '2025-10', '2026-S1', '2025-S2']); const expected = tipo === 'mes' ? '2026-12' : '2026-S1'; request(expected).flush(data(expected)); expect(run.selected()).toEqual({ periodo: expected, tipo }); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts index 8ef623b..12de7c8 100644 --- a/src/app/features/indicadores/indicadores-memory.spec.ts +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -68,7 +68,7 @@ describe('D.2 memoria global por dominio', () => { it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => { expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false); }); - it('adapter no transforma ni recorta y requiere primera granularidad para Todos', () => { + it('adapter no transforma ni recorta y requiere el primer intervalo de tiempo para Todos', () => { const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 }; const snapshot = JSON.stringify(applied); expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index 7c0c764..1a1ac43 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason: export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility { if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' }; if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' }; - if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite la granularidad ' + applied.tipo + ' del filtro general.' }; + if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de tiempo ' + applied.tipo + ' del filtro general.' }; const mode = applied.selection.mode; if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos' - ? 'Todos con reporte requiere semestre como primera granularidad publicada. Para meses elige periodos explícitos.' - : 'Los periodos del filtro general no son válidos para esta granularidad.' }; + ? 'Todos con reporte requiere semestre como primer intervalo de tiempo publicado. Para meses elige periodos explícitos.' + : 'Los periodos del filtro general no son válidos para este intervalo de tiempo.' }; return { compatible: true }; } export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean { diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 81baa21..790a960 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -142,7 +142,7 @@ describe('UX-04 validación defensiva HTTP', () => { describe('contrato datos exclusivo de KPI', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); - it('envía sólo periodos explícitos sin granularidad ni tema y conserva filas y notas', () => { + it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => { const http = TestBed.inject(HttpTestingController); let result: unknown; TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v); const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos'); From 04d529392e57702c586b5654dbc2179dd077975f Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 25 Oct 2026 01:19:07 +0000 Subject: [PATCH 37/51] =?UTF-8?q?refactor(indicadores):=20quitar=20el=20re?= =?UTF-8?q?sumen=20de=20indicadores=20del=20final=20de=20la=20p=C3=A1gina?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La tabla de resumen repetía en formato largo los valores de todas las figuras; cada figura ya trae su propia tabla de valores. Se quitan el componente indicadores-numeric-summary y sus filas (indicadores-numeric-rows), y las pruebas que dependían de ellos. CSO5.5 --- .../indicadores-c2-adapter.spec.ts | 2 - .../indicadores-cacu-final.spec.ts | 8 - .../indicadores/indicadores-numeric-rows.ts | 54 ----- .../indicadores-numeric-summary.spec.ts | 222 ------------------ .../indicadores-numeric-summary.ts | 88 ------- .../indicadores/indicadores-page.html | 3 - .../indicadores/indicadores-page.spec.ts | 5 +- .../features/indicadores/indicadores-page.ts | 3 +- 8 files changed, 3 insertions(+), 382 deletions(-) delete mode 100644 src/app/features/indicadores/indicadores-numeric-rows.ts delete mode 100644 src/app/features/indicadores/indicadores-numeric-summary.spec.ts delete mode 100644 src/app/features/indicadores/indicadores-numeric-summary.ts diff --git a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts index 56524b2..267e61a 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts @@ -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'] }; @@ -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); diff --git a/src/app/features/indicadores/indicadores-cacu-final.spec.ts b/src/app/features/indicadores/indicadores-cacu-final.spec.ts index f0f908e..f294bc1 100644 --- a/src/app/features/indicadores/indicadores-cacu-final.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-final.spec.ts @@ -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'; @@ -167,13 +166,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'); diff --git a/src/app/features/indicadores/indicadores-numeric-rows.ts b/src/app/features/indicadores/indicadores-numeric-rows.ts deleted file mode 100644 index 8e83824..0000000 --- a/src/app/features/indicadores/indicadores-numeric-rows.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { IndicadorDatos } from './indicadores.models'; -import { percentText } from './indicadores-format'; - -export interface NumericRow { period: string; group: string; category: string; value: string; detail: string; state: string; } -const record = (value: unknown): value is Record => value !== null && typeof value === 'object' && !Array.isArray(value); -function number(value: unknown, suffix = ''): string { - if (value === null) return 'Sin valor (nulo)'; - return typeof value === 'number' && Number.isFinite(value) ? `${value}${suffix}` : 'No disponible'; -} -function percent(value: unknown): string { - return typeof value === 'number' ? percentText(value) : number(value); -} -function label(dictionary: unknown, key: unknown, fallback: string): string { - const entry = record(dictionary) && typeof key === 'string' ? dictionary[key] : undefined; - return typeof entry === 'string' ? entry : record(entry) && typeof entry['etiqueta'] === 'string' ? entry['etiqueta'] : fallback; -} -// Read published cells individually. No totals, reconstruction, statistical -// computation or conversion of missing/suppressed values into zero. -export function numericRows(data: IndicadorDatos): NumericRow[] { - return data.filas.map(row => { - const group = row['grupo']; - const groupName = group === 'TOTAL' || group === 'total' ? 'Total' - : label(data['grupos'], group, 'Grupo sin etiqueta publicada'); - const stratum = row['estrato']; - const base = { period: typeof row['periodo'] === 'string' ? row['periodo'] : 'Periodo no disponible', - group: stratum == null ? groupName : `${groupName} · ${label(data['valores_estrato'], stratum, 'Estrato sin etiqueta publicada')}`, - category: label(data['categorias'], row['categoria'], row['categoria'] == null ? '—' : 'Categoría sin etiqueta publicada'), - value: 'No disponible', detail: '', state: 'Disponible' }; - if (row['suprimido'] === 1 || row['suprimido'] === true) return { ...base, value: 'Dato suprimido', state: 'Dato suprimido' }; - if (row['suprimido'] !== 0 && row['suprimido'] !== false) return { ...base, state: 'Estado de supresión no disponible' }; - let primary: unknown; - if (data.contrato === 'C1') { - primary = row['valor']; - return { ...base, value: percent(primary), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', - detail: `Intervalo publicado: ${percent(row['ic_bajo'])} a ${percent(row['ic_alto'])}. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` }; - } - if (data.contrato === 'C2') { - primary = row['n']; - const category = record(data['categorias']) ? data['categorias'][String(row['categoria'])] : undefined; - const parent = record(category) ? label(data['grupos_de_categoria'], category['grupo'], '') : ''; - const unit = typeof row['unidad'] === 'string' ? row['unidad'] : typeof data['unidad'] === 'string' ? data['unidad'] : ''; - return { ...base, category: [parent, base.category].filter(Boolean).join(' · '), value: number(primary), - state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', - detail: [unit && `Unidad: ${unit}.`, Object.hasOwn(row, 'denominador') && `Denominador publicado: ${number(row['denominador'])}.`].filter(Boolean).join(' ') }; - } - if (data.contrato === 'C3r') { - primary = row['mediana']; - const unit = row['unidad'] === 'dias' ? 'días' : typeof row['unidad'] === 'string' ? row['unidad'] : 'Unidad no disponible'; - return { ...base, value: `Mediana: ${number(primary)} · ${unit}`, state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible', - detail: `Q1: ${number(row['q1'])}; Q3: ${number(row['q3'])}; n: ${number(row['n'])}.` }; - } - return { ...base, state: 'Resumen no disponible para este indicador' }; - }); -} diff --git a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts b/src/app/features/indicadores/indicadores-numeric-summary.spec.ts deleted file mode 100644 index e5fd277..0000000 --- a/src/app/features/indicadores/indicadores-numeric-summary.spec.ts +++ /dev/null @@ -1,222 +0,0 @@ -import { Component } from '@angular/core'; -import { TestBed } from '@angular/core/testing'; -import { provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { By } from '@angular/platform-browser'; -import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { IndicadorFigurePanel } from './indicador-figure-panel'; -import { IndicadorFigureCard } from './indicador-figure-card'; -import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; -import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; -import { IndicadoresKpiQueries } from './indicadores-kpi-queries'; -import { IndicadoresNumericSummary } from './indicadores-numeric-summary'; -import { Indicador, IndicadorDatos } from './indicadores.models'; -import { numericRows } from './indicadores-numeric-rows'; -import { dualFigures } from './indicadores-dual-figures'; -import { c2Fixture } from './indicadores-c2-adapter.testing'; - -const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; -const item: Indicador = { id: 'future_indicator', titulo: 'Distribución publicada', contrato: 'C2', - figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre'], version: '2.0' }; -// Representative MD-19 wire shapes: published C1 interval, C2 counts/category -// metadata and C3r quartiles. Only test data; never served as dashboard indicators. -function data(contract = 'C2'): IndicadorDatos { - return { id: item.id, contrato: contract, tipo_periodo: 'semestre', periodos: ['2025-S2'], version: '2.0', - categorias: { A: { etiqueta: 'Categoría publicada', grupo: 'g' } }, grupos_de_categoria: { g: 'Grupo de categorías' }, - filas: [{ periodo: '2025-S2', grupo: 'TOTAL', categoria: 'A', suprimido: 0, n: 0, - valor: 0, numerador: 0, denominador: 20, ic_bajo: 0, ic_alto: 16.1, mediana: 4, q1: 2, q3: 7, unidad: 'dias' }] }; -} - -describe('MD-19 lecturas y celdas numéricas', () => { - it.each(['new_name', 'any_future_id'])('descubre doble representación de %s sin IDs de indicador', id => { - expect(dualFigures({ ...item, id })).toEqual(['fig_c2_donas', 'fig_c2_barras']); - expect(dualFigures({ ...item, id, contrato: 'C1' })).toEqual([]); - expect(dualFigures({ ...item, id, figuras: ['fig_c2_donas'] })).toEqual([]); - expect(dualFigures({ ...item, id, figuras: ['future_donut', 'future_bar'] })).toEqual([]); - }); - it('C1 conserva cero, intervalo publicado y poblaciones sin recalcular Wilson', () => { - const row = numericRows(data('C1'))[0]; - expect(row.value).toBe('0.0 %'); expect(row.state).toBe('Disponible'); - expect(row.detail).toBe('Intervalo publicado: 0.0 % a 16.1 %. Numerador: 0; denominador: 20.'); - }); - it('C2 conserva categorías, grupos y conteos; no suma poblaciones superpuestas', () => { - const sample = data(); sample['grupos'] = { other: 'Otra población' }; sample.filas.push({ ...sample.filas[0], grupo: 'other', n: 11 }); - const rows = numericRows(sample); - expect(rows).toHaveLength(2); expect(rows.map(r => r.value)).toEqual(['0', '11']); - expect(rows[0].category).toBe('Grupo de categorías · Categoría publicada'); - expect(rows[1].group).toBe('Otra población'); - }); - it('C3r sólo muestra mediana, Q1, Q3, n y unidad publicados', () => { - const row = numericRows(data('C3r'))[0]; - expect(row.value).toBe('Mediana: 4 · días'); expect(row.detail).toBe('Q1: 2; Q3: 7; n: 0.'); - expect(JSON.stringify(row)).not.toMatch(/bigote|extremo|min|max/); - }); - it.each(['C1', 'C2', 'C3r'])('%s nunca revela valores de una fila suprimida ni reconstruye totales', contract => { - const sample = data(contract); sample.filas[0]['suprimido'] = 1; - const row = numericRows(sample)[0]; expect(row.value).toBe('Dato suprimido'); expect(row.detail).toBe(''); - expect(row.state).toBe('Dato suprimido'); - }); - it('distingue null, ausencia, NaN, cero y supresión desconocida', () => { - const sample = data(); - sample.filas = [null, undefined, NaN, 0].map(n => ({ periodo: '2025-S2', grupo: 'TOTAL', n, suprimido: 0 })); - expect(numericRows(sample).map(r => r.value)).toEqual(['Sin valor (nulo)', 'No disponible', 'No disponible', '0']); - delete sample.filas[0]['suprimido']; expect(numericRows(sample)[0].value).toBe('No disponible'); - expect(numericRows(sample)[0].state).toContain('supresión no disponible'); - }); -}); - -describe('snapshots compartidos y resumen accesible', () => { - let http: HttpTestingController, snapshots: IndicadoresSnapshots; - beforeEach(() => { - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); - http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots); - }); - afterEach(() => http.verify()); - const request = () => http.expectOne(r => r.url.endsWith('/datos')); - it('deduplica datos simultáneos de KPI, panel y tabla, y reutiliza payload terminado', () => { - const queries = TestBed.inject(IndicadoresKpiQueries); - const values: IndicadorDatos[] = []; - queries.datos('tea', item.id, applied.tipo, '2025-S2', item.version).subscribe(value => values.push(value)); - snapshots.read('tea', item, applied).subscribe(); - snapshots.datos('tea', item.id, applied.tipo, ['2025-S2'], item.version).subscribe(value => values.push(value)); - request().flush(data()); expect(values).toHaveLength(2); expect(values[0]).toBe(values[1]); - snapshots.read('tea', item, { ...applied, revision: 2 }).subscribe(); http.expectNone(() => true); - expect(snapshots.numeric().get(snapshotKey('tea', item, { ...applied, revision: 2 }))?.status).toBe('ready'); - }); - it('incluye dominio, versión, tipo, selección y revisión en identidad', () => { - const keys = [snapshotKey('tea', item, applied), snapshotKey('cama', item, applied), - snapshotKey('tea', { ...item, version: '3.0' }, applied), snapshotKey('tea', item, { ...applied, revision: 2 }), - snapshotKey('tea', item, { ...applied, tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01'] } }), - snapshotKey('tea', item, { ...applied, selection: { mode: 'todos' } })]; - expect(new Set(keys).size).toBe(keys.length); - }); - it('registra la identidad de versión publicada aunque el catálogo no la exponga', () => { - const unversioned = { ...item, version: undefined }; - snapshots.read('tea', unversioned, applied).subscribe(); request().flush(data()); - const alias = snapshots.numeric().get(snapshotKey('tea', unversioned, applied)); - expect(alias?.sourceKey).toBe(snapshotKey('tea', item, applied)); - expect(snapshots.numeric().get(alias!.sourceKey!)).toBe(alias); - }); - it('reutiliza en la tabla los detalles de datos consultados por un KPI, sin activar figuras', () => { - TestBed.inject(IndicadoresKpiQueries).datos('tea', item.id, 'semestre', '2025-S2', item.version).subscribe(); - request().flush(data()); - expect(snapshots.reading('tea', item, applied)?.data).toEqual(data()); http.expectNone(() => true); - }); - it('cancelar una lectura compartida conserva al otro consumidor; cancelar todos aborta HTTP', () => { - const a = snapshots.read('tea', item, applied).subscribe(), b = snapshots.read('tea', item, applied).subscribe(); - const pending = request(); a.unsubscribe(); expect(pending.cancelled).toBe(false); - b.unsubscribe(); expect(pending.cancelled).toBe(true); - snapshots.read('tea', item, applied).subscribe(); request().flush(data()); - }); - it.each([404, 503])('conserva error HTTP %s y permite reintento sin cachear el error', status => { - snapshots.read('tea', item, applied).subscribe(); request().flush({}, { status, statusText: 'Failure' }); - expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error'); - snapshots.read('tea', item, applied).subscribe(); request().flush(data()); - expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready'); - }); - it.each(['period', 'contract', 'version', 'row'])('rechaza respuesta incompatible por %s', kind => { - snapshots.read('tea', item, applied).subscribe(); const sample = data(); - if (kind === 'period') sample.periodos = ['2024-S1']; - if (kind === 'contract') sample.contrato = 'C1'; - if (kind === 'version') sample['version'] = '1.0'; - if (kind === 'row') sample.filas[0]['periodo'] = '2024-S1'; - request().flush(sample); expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error'); - }); - it('tabla reutiliza exactamente KPI, cambia periodo/dominio sin mostrar valores anteriores y respeta catálogo retirado', () => { - const fixture = TestBed.createComponent(IndicadoresNumericSummary); - fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied); - fixture.componentRef.setInput('kpis', [{ id: item.id, title: 'Destacado publicado', unit: '%', contrato: 'C1' }]); - snapshots.publishKpi('tea', item, applied, { value: '42.0', unit: '%', state: 'Disponible', period: '2025-S2', info: 'Nota publicada' }); - fixture.detectChanges(); let element = fixture.nativeElement as HTMLElement; - expect(element.querySelector('.kpi-reading')?.textContent?.replace(/\s+/g, ' ')).toContain('42.0 %'); - expect(element.querySelector('.kpi-reading')?.textContent).toContain('2025-S2'); - expect(element.querySelector('.kpi-reading')?.textContent).toContain('Nota publicada'); - expect(element.querySelector('caption')).toBeTruthy(); expect(element.querySelectorAll('thead th[scope="col"]')).toHaveLength(5); - expect(element.querySelector('.table-scroll')?.getAttribute('tabindex')).toBe('0'); http.expectNone(() => true); - fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); - fixture.detectChanges(); expect(element.textContent).not.toContain('42.0'); expect(element.textContent).toContain('2026-S1'); - fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); - expect(element.textContent).not.toContain('42.0'); - fixture.componentRef.setInput('catalog', []); fixture.detectChanges(); expect(element.querySelectorAll('tbody tr')).toHaveLength(0); - fixture.destroy(); - }); - it('tabla distingue carga, error y vacío publicado sin volver a consultar', () => { - const fixture = TestBed.createComponent(IndicadoresNumericSummary); - fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied); - snapshots.read('tea', item, applied).subscribe(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando…'); - request().flush({}, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); - expect(fixture.nativeElement.textContent).toContain('Error de consulta'); - snapshots.read('tea', item, applied).subscribe(); request().flush({ ...data(), filas: [] }); fixture.detectChanges(); - expect(fixture.nativeElement.textContent).toContain('Sin filas publicadas'); http.expectNone(() => true); fixture.destroy(); - }); -}); - -@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) -class ChartStub {} -describe('card doble, jerarquía y carga numérica diferida', () => { - let fixture: ReturnType>, http: HttpTestingController, snapshots: IndicadoresSnapshots; - beforeEach(() => { - TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); - TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); - http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots); - fixture = TestBed.createComponent(IndicadorCatalogCard); - fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', item); - fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); - }); - afterEach(() => { fixture.destroy(); http.verify(); }); - const panels = () => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(el => el.componentInstance as IndicadorFigurePanel); - function activate() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } - const figure = (id: string) => http.expectOne(r => r.url.endsWith('/figuras/' + id)); - it('dos paneles sin selector redundante, diferidos hasta activación y con mismo periodo aplicado', () => { - expect(panels()).toHaveLength(2); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); http.expectNone(() => true); - activate(); - const pending = http.expectOne(r => r.url.endsWith('/datos')); - expect(pending.request.params.get('periodos')).toBe('2025-S2'); pending.flush({ ...c2Fixture(), id: item.id }); - expect(panels().every(p => p.result().source === 'datos')).toBe(true); - expect(fixture.nativeElement.classList.contains('dual-card')).toBe(true); - expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']); - http.expectNone(() => true); - }); - it('drill-down filtra la presentación de barras y restaurar recupera la distribución sin alterar JSON ni consultar', () => { - activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges(); - const bars = structuredClone(panels()[1].result().figure); - const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard); - const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result(); - const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf].find(button => button.textContent?.trim() === 'G2')!; - parentButton.click(); fixture.detectChanges(); expect(cards[0].activeParent).toBe('G2'); - expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B', 'C']); - expect(panels()[1].result().figure).toBe(barState.figure); expect(panels()[1].result().figure).toEqual(bars); - cards[0].selectCategory('B'); fixture.detectChanges(); - expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B']); - (fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges(); - expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); - expect(panels()[1].result().presentationFigure).toEqual(barState.presentationFigure); http.expectNone(() => true); - }); - it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => { - snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true); - activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges(); - expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready'); - snapshots.expanded.set(false); fixture.detectChanges(); snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true); - }); - it('cambio de periodo cancela ambas figuras y números; fuera de vista difiere el siguiente aplicado', () => { - snapshots.expanded.set(true); activate(); const old = [http.expectOne(r => r.url.endsWith('/datos'))]; - fixture.componentInstance.setVisible(false); fixture.detectChanges(); - fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges(); - expect(old.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().status === 'deferred')).toBe(true); - http.expectNone(() => true); - activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...data(), periodos: ['2026-S1'], filas: [] }); - for (const id of ['fig_c2_donas', 'fig_c2_barras']) { - const pending = figure(id); expect(pending.request.params.get('periodos')).toBe('2026-S1'); pending.flush({ data: [], layout: {} }); - } - }); - it('conserva preferencias y opciones adicionales; desaparece representación retirada y hace fallback', () => { - const memory = TestBed.inject(IndicadoresMemory); memory.rememberFigure('tea', item.id, 'fig_c2_barras'); - fixture.componentRef.setInput('indicador', { ...item, figuras: [...item.figuras, 'future_representation'] }); fixture.detectChanges(); - expect(fixture.componentInstance.isDual).toBe(true); expect(memory.figure('tea', item.id)).toBe('fig_c2_barras'); - fixture.componentInstance.selectFigure('future_representation'); fixture.detectChanges(); - expect(fixture.componentInstance.displayFigures).toEqual(['future_representation']); - fixture.componentRef.setInput('indicador', { ...item, figuras: ['fig_c2_donas'] }); fixture.detectChanges(); - expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas']); expect(fixture.nativeElement.querySelector('mat-select')).toBeTruthy(); http.expectNone(() => true); - }); -}); diff --git a/src/app/features/indicadores/indicadores-numeric-summary.ts b/src/app/features/indicadores/indicadores-numeric-summary.ts deleted file mode 100644 index 6f51f9d..0000000 --- a/src/app/features/indicadores/indicadores-numeric-summary.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Component, inject, Input, OnDestroy } from '@angular/core'; -import { Dominio, Indicador } from './indicadores.models'; -import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; -import { KpiDefinition } from './indicadores-kpi'; -import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; -import { numericRows } from './indicadores-numeric-rows'; -import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; - -@Component({ - selector: 'app-indicadores-numeric-summary', - template: ` -
    -

    Resumen de indicadores

    -

    Valores publicados para {{ period }}. Los detalles se cargan al consultar las gráficas correspondientes. Cada fila conserva su periodo y población; no se suman grupos ni periodos.

    -
    - - - - - @for (definition of kpis; track definition.id) { - @let item = find(definition.id); - @if (item) { - @let kpi = snapshots.kpis().get(key(item)); - - - - - } - } - @for (item of catalog; track item.id) { - @let reading = snapshots.reading(dominio, item, figureSelection(item)); - @let compatible = compatibility(item); - @if (compatible.compatible && reading?.status === 'ready' && reading?.data; as data) { - @for (row of rows(data); track $index) { - - - } @empty { - - } - } @else { - - - } - } - -
    Resultados de indicadores destacados y gráficas consultadas
    IndicadorPeriodoGrupo / categoríaResultadoEstado y notas
    {{ definition.title }} Destacado{{ kpi?.period ?? period }}—{{ kpi?.value ?? 'No disponible' }} @if (kpi?.value !== undefined) { {{ kpi?.unit }} }{{ kpi?.state ?? 'Pendiente de lectura' }} {{ kpi?.info }} {{ kpi?.notes?.join(' ') }}
    {{ item.titulo }}{{ row.period }}{{ row.group }} · {{ row.category }}{{ row.value }} {{ row.detail }}{{ row.state }} {{ data.notas?.join(' ') }}
    {{ item.titulo }}{{ figurePeriod(item) }}—Sin filas publicadas{{ data.notas?.join(' ') }}
    {{ item.titulo }}{{ figurePeriod(item) }}—No disponible{{ !compatible.compatible ? compatible.reason : reading?.status === 'loading' ? 'Cargando…' : reading?.status === 'error' ? 'Error de consulta: ' + reading?.message : 'Pendiente: consulta la gráfica para cargar sus números.' }} - @if (reading?.status === 'error') { }
    -
    -
    `, - styles: ` - :host { display: block; min-width: 0; margin-top: var(--issste-space-6); } - details { border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); padding: 1rem; } - summary { cursor: pointer; min-height: 44px; align-content: center; } - h2 { display: inline; font-family: var(--issste-font-heading); font-size: 1.5rem; } - p, td, th { overflow-wrap: anywhere; } - p, .kind, .detail { color: var(--issste-text-secondary); } - .kind, .detail { display: block; font-weight: normal; } - .table-scroll { overflow-x: auto; max-height: 32rem; } - table { width: 100%; border-collapse: collapse; font-size: .9rem; } - caption { text-align: left; padding: .5rem; } - th, td { padding: .65rem; border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; min-width: 6rem; } - thead { background: var(--issste-surface); position: sticky; top: 0; } - button { min-height: 44px; font: inherit; color: var(--issste-text); background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } - :focus-visible { outline: 2px solid var(--issste-text); outline-offset: -2px; } - @media (max-width: 550px) { details { padding: .5rem; } th, td { padding: .5rem; } } - `, -}) -export class IndicadoresNumericSummary implements OnDestroy { - @Input({ required: true }) dominio!: Dominio; - @Input({ required: true }) catalog: readonly Indicador[] = []; - @Input({ required: true }) applied!: GlobalApplied; - @Input() kpis: readonly KpiDefinition[] = []; - readonly snapshots = inject(IndicadoresSnapshots); - readonly rows = numericRows; - readonly increment = (value: number) => value + 1; - get period() { return describePeriods(this.applied.tipo, this.applied.selection); } - key(item: Indicador) { return snapshotKey(this.dominio, item, this.applied); } - find(id: string) { return this.catalog.find(item => item.id === id); } - figureSelection(item: Indicador) { return figureApplied(this.dominio, item.id, this.applied); } - figurePeriod(item: Indicador) { - const selection = this.figureSelection(item); - return (independentFigurePeriods(this.dominio, item.id) ? 'Selección independiente: ' : '') - + describePeriods(selection.tipo, selection.selection); - } - compatibility(item: Indicador) { return filterCompatibility(this.figureSelection(item), item.tipos_periodo); } - toggle(event: Event) { this.snapshots.expanded.set((event.target as HTMLDetailsElement).open); } - ngOnDestroy() { this.snapshots.expanded.set(false); } -} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 3910d6e..a7e3fc8 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -99,9 +99,6 @@
    }
    - @if (!initialPeriodBlocked && filters && !catalogLoading() && !catalogError() && catalog().length) { - - }
    diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 3331484..ed9be9a 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -74,9 +74,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true); const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf; expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']); - const summary = fixture.nativeElement.querySelector('app-indicadores-numeric-summary') as HTMLElement; - expect(sections[1].compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(summary.textContent).toContain('Resumen de indicadores'); + // Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página. + expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull(); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right'); toggle(0); toggle(1); flushAll(); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 8506a77..5cb6929 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -26,13 +26,12 @@ import { httpMessage } from './indicadores-http'; import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresTracking } from './indicadores-tracking'; -import { IndicadoresNumericSummary } from './indicadores-numeric-summary'; type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) From dcaf1a8832c1c0628fceb57ef89e69104d185c92 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 25 Oct 2026 01:37:53 +0000 Subject: [PATCH 38/51] fix(indicadores): quitar flechas, rayas y puntos medios de los textos de pantalla MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Los textos que ve una persona, visibles o en aria-label, ya no usan flechas ni rayas o puntos medios como separador: se separan con comas o se reescribe la frase (por ejemplo «Días de toma a resultado (laboratorio)», «Último dato visible, 2025-S1», «Dominio CaCu, investigación», «2025-S2, 1 de 3» o «Datos y definiciones de CaCu»). El pie que publica el kit cambia al mismo estilo, así que la validación del pie de TEA y la lectura de la fecha de corte reconocen el formato nuevo con comas y siguen aceptando el anterior para no romper con un kit previo. Se ajustan los fixtures sintéticos y las specs a los textos nuevos. CSO5.5 --- .../indicadores/indicador-catalog-card.ts | 2 +- .../indicador-confirmacion-citologia.html | 14 +++++++------- .../indicadores/indicador-eu7-escenario.html | 16 ++++++++-------- .../indicadores/indicador-figure-card.html | 6 +++--- .../indicadores/indicador-figure-card.spec.ts | 7 +++++-- .../indicadores/indicador-figure-card.ts | 5 ++++- .../indicadores/indicador-figure-panel.spec.ts | 2 +- .../indicadores/indicador-figure-panel.ts | 4 ++-- .../indicadores/indicador-kpi-initial.spec.ts | 4 ++-- .../features/indicadores/indicador-kpi-panel.ts | 2 +- .../indicadores/indicador-metadata.spec.ts | 2 +- .../features/indicadores/indicador-metadata.ts | 2 +- .../indicadores/indicador-period-filters.html | 2 +- .../indicadores/indicador-tiempos-pareados.html | 2 +- .../indicadores/indicadores-axis-labels.spec.ts | 2 +- .../indicadores/indicadores-c2-adapter.spec.ts | 2 +- .../indicadores/indicadores-c2-adapter.ts | 4 ++-- .../indicadores-c2-general-panel.spec.ts | 2 +- .../indicadores-c2-general-selection.spec.ts | 2 +- .../indicadores-c2-general-selection.ts | 2 +- .../indicadores-confirmacion-citologia.ts | 2 +- .../indicadores/indicadores-definitions.html | 2 +- .../indicadores-donut-periods.spec.ts | 2 +- .../indicadores/indicadores-eu7-escenario.ts | 2 +- .../features/indicadores/indicadores-page.html | 2 +- .../indicadores-plotly-lifecycle.spec.ts | 4 ++-- .../indicadores/indicadores-stratified.ts | 2 +- .../indicadores-tiempos-pareados.spec.ts | 4 ++-- .../indicadores/indicadores-tiempos-pareados.ts | 6 +++--- .../indicadores/indicadores-tracking.html | 4 ++-- .../indicadores-visual-profile.spec.ts | 13 ++++++++++++- .../indicadores/indicadores.presentation.ts | 5 ++++- .../indicadores.synthetic-fixtures.ts | 6 +++--- src/app/shared/plotly/plotly-chart.ts | 2 +- 34 files changed, 80 insertions(+), 60 deletions(-) diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index ff1077f..d0acb00 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -34,7 +34,7 @@ import { parTiempos } from './indicadores-tiempos-pareados'; diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.html b/src/app/features/indicadores/indicador-confirmacion-citologia.html index cb58d3f..e1b3b18 100644 --- a/src/app/features/indicadores/indicador-confirmacion-citologia.html +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.html @@ -24,12 +24,12 @@ @if (periods.length > 1) { } @if (model; as m) { -

    {{ m.periodo }} · Selección: {{ selectionLabel }} · {{ reading }}

    +

    {{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}

    @if (status() === 'empty') {

    No hay citologías de alto grado publicadas para este periodo.

    } @else {
    @@ -46,24 +46,24 @@
    -

    Por resultado de la citología · {{ m.periodo }}

    +

    Por resultado de la citología, {{ m.periodo }}

    @if (ratesFigure) { - + }
      @for (t of rates; track t.fila.id) { @if (t.k === null) {
    • {{ t.fila.etiqueta }}: {{ estadoTasa(t) }}
    • } }
    -

    Resultado de la biopsia · {{ m.periodo }}

    +

    Resultado de la biopsia, {{ m.periodo }}

    @if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) { - + } @else {

    {{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}

    }
    } @for (note of m.notas; track $index) {

    {{ note }}

    }
    - +
    Tabla de contingencia · {{ m.periodo }} · mujeres
    @for (g of m.grados; track g.id) { }@for (a of m.aparte; track a.id) { }@for (fila of m.filas; track fila.id) { @for (g of m.grados; track g.id) { }@for (a of m.aparte; track a.id) { } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html index 73ac50e..64e3dae 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.html +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -24,12 +24,12 @@ @if (periods.length > 1) { } @if (model; as m) { -

    {{ m.periodo }} · Selección: {{ selectionLabel }}

    +

    {{ m.periodo }}, selección: {{ selectionLabel }}

    @if (status() === 'empty') {

    No hay pacientes publicados para este periodo.

    } @else {
    @@ -46,16 +46,16 @@
    -

    Distribución de resultados · {{ m.periodo }}

    +

    Distribución de resultados, {{ m.periodo }}

    @if (m.total !== null && m.total > 0 && donutFigure) { - + } @else {

    {{ 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.' }}

    }

    {{ sinDatoNote }}

    -

    {{ selectionLabel }} por escenario clínico · {{ m.periodo }}

    +

    {{ selectionLabel }} por escenario clínico, {{ m.periodo }}

    Porcentaje del total válido de cada escenario; excluye «Sin dato».

    @if (m.escenarios.length && barsFigure) { - + }
    @@ -63,11 +63,11 @@ @for (note of m.notas; track $index) {

    {{ note }}

    }
    Valores publicados y celdas suprimidas
    -
    Tabla de contingencia de mujeres, {{ m.periodo }}
    Citología{{ g.etiqueta }}Con biopsia{{ a.etiqueta }}
    {{ fila.etiqueta }}{{ cellText(fila.celdas[g.id]) }}{{ denText(fila.den, fila.estado) }}{{ cellText(fila.aparte[a.id]) }}
    +
    Datos generales · {{ m.periodo }}
    @for (row of generalCells; track $index) { }
    Datos generales, {{ m.periodo }}
    CategoríaConteo
    {{ row.etiqueta }}{{ cellText(row.celda) }}
    - +
    Escenarios clínicos · {{ m.periodo }} · Porcentajes sin «Sin dato»
    @for (row of scenarioCells; track $index) { }
    Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»
    EscenarioCategoríaConteoDenominador válidoPorcentaje
    {{ row.escenario }}{{ row.categoria }}{{ cellText(row.celda) }}{{ row.den === null ? 'No disponible / no aplica' : row.den }}{{ percentText(row.pct) }}
    diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index a267295..817476f 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -1,8 +1,8 @@ - + @if (selected) {
    - +
    } } @for (note of m.notas; track $index) {

    {{ note }}

    } -
    Valores publicados y celdas suprimidas +
    Valores publicados
    diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index fa3bcb9..3d8d9aa 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -67,7 +67,7 @@ import { MatTooltipModule } from '@angular/material/tooltip'; @if (dimension && result().status === 'ready') { @if (hasSuppressedCells) {

    Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

    } @if (hasMissingCells) {

    Hay datos no disponibles; los espacios sin barra no representan un cero observado.

    } -
    Valores publicados y celdas suprimidas +
    Valores publicados
    Datos generales, {{ m.periodo }}
    CategoríaConteo
    @for (cell of cells; track $index) { }
    CategoríaEstratoConteo
    {{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}
    diff --git a/src/app/features/indicadores/indicador-tiempos-pareados.html b/src/app/features/indicadores/indicador-tiempos-pareados.html index 80639ae..25ea90e 100644 --- a/src/app/features/indicadores/indicador-tiempos-pareados.html +++ b/src/app/features/indicadores/indicador-tiempos-pareados.html @@ -27,7 +27,7 @@ } @for (note of m.notas; track $index) {

    {{ note }}

    } -
    Valores publicados y cajas no disponibles +
    Valores publicados
    @for (clave of claves; track clave) { } From 70aa739f97cdb411810dac67402a8ae4976822a2 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 25 Oct 2026 21:25:26 +0000 Subject: [PATCH 48/51] =?UTF-8?q?Bit=C3=A1cora:=20IND1=20ya=20no=20cita=20?= =?UTF-8?q?kpi=5Fcatalog.yaml=20en=20la=20ficha?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CSO5.5 --- docs/bitacora-textos.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/bitacora-textos.md b/docs/bitacora-textos.md index 551aa25..d339a35 100644 --- a/docs/bitacora-textos.md +++ b/docs/bitacora-textos.md @@ -9,6 +9,9 @@ y qué hay que mantener al día. Lo más reciente, arriba. disponibles», que confundía. Ahora dicen «Valores publicados». - La tabla de contingencia de citología y biopsia (Tasa de confirmación histopatológica) estaba siempre a la vista; ahora va plegada bajo «Valores publicados», como las demás. +- En el kit (IND1 0.3.2), la ficha de «Pacientes con citología anómala» ya no cita + `kpi_catalog.yaml` en sus referencias: era un archivo interno de trabajo. Las referencias de + las demás fichas de cáncer cervicouterino citan las guías europeas y se quedan. ## Pendientes (2026-10-25) From 1c0bdf6184e8b3509e2c6b3a2038c771ccda7e9a Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Tue, 27 Oct 2026 14:46:51 -0600 Subject: [PATCH 49/51] =?UTF-8?q?feat(indicadores):=20completar=20ficha=20?= =?UTF-8?q?CaCu=20y=20navegaci=C3=B3n=20cl=C3=ADnica?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores/cacu-seguimiento.spec.ts | 5 +- .../indicadores/indicador-catalog-card.ts | 2 +- .../indicadores/indicador-kpi-panel.spec.ts | 33 +- .../indicadores/indicador-kpi-panel.ts | 3 + .../indicadores-cacu-final.spec.ts | 14 +- .../indicadores-initial-integration.spec.ts | 26 +- .../indicadores-kpi-resultado.spec.ts | 138 ++++++ .../features/indicadores/indicadores-kpi.ts | 9 +- .../indicadores-navegacion-lateral.spec.ts | 432 ++++++++++++++++++ .../indicadores-navegacion-panel.html | 11 + .../indicadores-navegacion-panel.scss | 20 + .../indicadores-navegacion-panel.ts | 35 ++ .../indicadores/indicadores-page.html | 60 ++- .../indicadores/indicadores-page.scss | 11 + .../indicadores/indicadores-page.spec.ts | 17 + .../features/indicadores/indicadores-page.ts | 169 ++++++- .../indicadores-periodos-integration.spec.ts | 19 +- .../indicadores/indicadores-tracking.html | 13 +- .../indicadores/indicadores-tracking.scss | 5 + .../indicadores/indicadores-tracking.ts | 37 +- .../paciente-detalle/fecha-compuesta.html | 33 ++ .../paciente-detalle/fecha-compuesta.scss | 8 + .../paciente-detalle/fecha-compuesta.spec.ts | 222 +++++++++ .../paciente-detalle/fecha-compuesta.ts | 153 +++++++ .../paciente-detalle.fixtures.ts | 19 + .../paciente-detalle/paciente-detalle.html | 85 ++++ .../paciente-detalle.models.ts | 36 ++ .../paciente-detalle.provider.ts | 20 + .../paciente-detalle/paciente-detalle.scss | 36 ++ .../paciente-detalle/paciente-detalle.spec.ts | 273 +++++++++++ .../paciente-detalle.state.ts | 71 +++ .../paciente-detalle/paciente-detalle.ts | 53 +++ .../paciente-registro-dialog.html | 36 ++ .../paciente-registro-dialog.scss | 5 + .../paciente-registro-dialog.ts | 67 +++ .../paciente-registro-integracion.spec.ts | 289 ++++++++++++ .../paciente-registro.catalogos.ts | 53 +++ .../paciente-registro.models.ts | 24 + .../paciente-registro.spec.ts | 176 +++++++ .../paciente-registro.validation.ts | 34 ++ .../paciente-registros-sesion.ts | 45 ++ .../paciente-riesgo-tabla.html | 37 ++ .../paciente-riesgo-tabla.scss | 15 + .../paciente-detalle/paciente-riesgo-tabla.ts | 14 + .../paciente-riesgo.fixtures.ts | 16 + .../paciente-riesgo.models.ts | 23 + .../paciente-riesgo.provider.ts | 14 + .../paciente-detalle/paciente-riesgo.spec.ts | 95 ++++ .../paciente-detalle/paciente-riesgo.state.ts | 14 + src/styles.scss | 16 + 50 files changed, 2983 insertions(+), 58 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-kpi-resultado.spec.ts create mode 100644 src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts create mode 100644 src/app/features/indicadores/indicadores-navegacion-panel.html create mode 100644 src/app/features/indicadores/indicadores-navegacion-panel.scss create mode 100644 src/app/features/indicadores/indicadores-navegacion-panel.ts create mode 100644 src/app/features/indicadores/paciente-detalle/fecha-compuesta.html create mode 100644 src/app/features/indicadores/paciente-detalle/fecha-compuesta.scss create mode 100644 src/app/features/indicadores/paciente-detalle/fecha-compuesta.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/fecha-compuesta.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.fixtures.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.html create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.scss create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-detalle.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.scss create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro.catalogos.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registro.validation.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index 8604caf..f3c85c8 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -47,7 +47,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => { 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(); }); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index d0acb00..25e56cd 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -30,7 +30,7 @@ import { parTiempos } from './indicadores-tiempos-pareados';
    -

    {{ indicador.titulo }}

    +

    {{ indicador.titulo }}

    + } + + } + + diff --git a/src/app/features/indicadores/indicadores-navegacion-panel.scss b/src/app/features/indicadores/indicadores-navegacion-panel.scss new file mode 100644 index 0000000..58d57c6 --- /dev/null +++ b/src/app/features/indicadores/indicadores-navegacion-panel.scss @@ -0,0 +1,20 @@ +:host { display: block; width: min(20rem, calc(100vw - 1rem)); max-width: calc(100vw - 1rem); min-width: 0; color: var(--issste-text); } +.panel-shell { display: flex; flex-direction: column; width: 100%; max-height: min(58dvh, 32rem); min-height: 0; overflow: hidden; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: 0 8px 28px rgb(8 24 57 / 24%); opacity: 1; transform: scale(1); transform-origin: left center; transition: opacity 180ms ease, transform 180ms cubic-bezier(.2, .8, .2, 1); } +@starting-style { .panel-shell { opacity: 0; transform: scale(.97); } } +:host(.panel-closing) { pointer-events: none; } +:host(.panel-closing) .panel-shell { opacity: 0; transform: scale(.97); } +.panel-list { flex: 0 1 auto; min-height: 0; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; padding: .35rem .5rem; } +ul { list-style: none; margin: 0; padding: 0; } +li + li { margin-top: .1rem; } +li button { display: flex; width: 100%; min-height: 44px; height: auto; justify-content: flex-start; padding: .15rem .2rem; text-align: start; white-space: normal; line-height: 1.35; color: inherit; } +.option-label { display: block; width: 100%; min-width: 0; padding: .4rem; box-sizing: border-box; border-radius: .35rem; overflow-wrap: anywhere; transition: transform 180ms ease, background-color 180ms ease; } +button:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: -2px; } +.panel-list:has(button:focus-visible) button:not(:focus-visible) .option-label { transform: scale(.99); } +button:focus-visible .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); } +@media (hover: hover) and (pointer: fine) { + .panel-list:has(button:hover) button:not(:hover):not(:focus-visible) .option-label { transform: scale(.99); } + button:hover .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); } +} +@media (prefers-reduced-motion: reduce) { + .panel-shell, .option-label { transition: none; transform: none !important; } +} diff --git a/src/app/features/indicadores/indicadores-navegacion-panel.ts b/src/app/features/indicadores/indicadores-navegacion-panel.ts new file mode 100644 index 0000000..1470f7b --- /dev/null +++ b/src/app/features/indicadores/indicadores-navegacion-panel.ts @@ -0,0 +1,35 @@ +import { Component, ElementRef, Input, Signal, inject, output } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; + +export interface IndicadorNavegacionItem { + key: string; + titulo: string; +} + +@Component({ + selector: 'app-indicadores-navegacion-panel', + imports: [MatButtonModule], + host: { '[class.panel-closing]': 'closing', '[attr.inert]': "closing ? '' : null" }, + templateUrl: './indicadores-navegacion-panel.html', + styleUrl: './indicadores-navegacion-panel.scss', +}) +export class IndicadoresNavegacionPanel { + @Input({ required: true }) items!: Signal; + @Input() closing = false; + readonly selected = output(); + readonly closed = output(); + private readonly element = inject>(ElementRef); + focusFirstOption() { this.element.nativeElement.querySelector('.panel-list button')?.focus({ preventScroll: true }); } + containsFocus() { return this.element.nativeElement.contains(this.element.nativeElement.ownerDocument.activeElement); } + + onKeydown(event: KeyboardEvent) { + if (event.key !== 'Escape') return; + event.preventDefault(); + event.stopPropagation(); + this.closed.emit(); + } + + seleccionar(key: string) { + if (this.items().some(item => item.key === key)) this.selected.emit(key); + } +} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 66098d6..299fa6f 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -1,16 +1,44 @@
    - {{ domainTitles[dominio] }}, investigación -

    Indicadores

    -

    Explora los indicadores de {{ domainLabels[dominio] }}.

    -
    -
    - @for (section of sections; track section.id) { - + @if (fichaPacienteAbierta()) { +

    Ficha del paciente

    +

    Consulta individual de seguimiento de cáncer cervicouterino

    + } @else { + {{ domainTitles[dominio] }}, investigación +

    Indicadores

    +

    Explora los indicadores de {{ domainLabels[dominio] }}.

    } -
    + + @if (!fichaPacienteAbierta()) { +
    + @for (section of sections; track section.id) { + + } +
    + } + @if (showGraphicNavigation) { + + + + + }
    @if (!catalogLoading() && filters; as state) { @@ -37,16 +65,17 @@ } @else if (initialPeriodState() === 'manual') {

    La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.

    } - @let kpis = availableKpis; + @let kpis = opportunityKpis; @if (kpis.length && !initialPeriodBlocked) {

    {{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}

    -
    +
    @for (definition of kpis; track dominio + ':' + definition.id) { } @if (dominio === 'cacu') { + }
    @@ -93,7 +122,7 @@ }
    @for (item of searchResults().items; track cardIdentity(item)) { - }
    @@ -101,8 +130,9 @@
    -
    - +
    +
    diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index fec8c12..1f58810 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -32,6 +32,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } @container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } +// Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids. +.kpi-section[data-domain='cacu'] .kpi-grid { + grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr)); + align-items: stretch; +} + .section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1); border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border); background: var(--issste-surface); padding: var(--issste-space-2) var(--issste-space-2) 0; @@ -49,3 +55,8 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .section-panel { padding-block: var(--issste-space-6); } .section-panel[hidden] { display: none; } @media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } } +.graphic-navigation-trigger { transition: opacity 180ms ease; } +.graphic-navigation-trigger-expanded { opacity: 0; pointer-events: none; } +@media (prefers-reduced-motion: reduce) { + .graphic-navigation-trigger { transition: none; } +} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index ed9be9a..52b36f0 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -6,6 +6,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common import { provideRouter } from '@angular/router'; import { By } from '@angular/platform-browser'; import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresTracking } from './indicadores-tracking'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigureCard } from './indicador-figure-card'; @@ -51,6 +52,22 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { .toEqual([]); http.expectNone(r => r.url.endsWith('/datos')); }); + it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => { + load(); + expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores'); + expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3); + fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente'); + expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de cáncer cervicouterino'); + expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull(); + expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title'); + fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores'); + expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3); + expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento'); + expect(page.activeSection()).toBe('resumen'); + http.expectNone(() => true); + }); it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => { fixture.detectChanges(); expect(page.catalogLoading()).toBe(true); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index f22e6a3..846042e 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -10,28 +10,30 @@ import { MatInputModule } from '@angular/material/input'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { ConnectedPosition, Overlay, OverlayModule } from '@angular/cdk/overlay'; import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs'; import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; -import { indicatorIdentity } from './indicadores-identities'; +import { identityElementId, indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresTracking } from './indicadores-tracking'; +import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel'; type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -42,8 +44,14 @@ export class IndicadoresPage { { id: 'datos', label: 'Datos y definiciones' }, ]; readonly activeSection = signal('resumen'); + readonly fichaPacienteAbierta = signal(false); + setFichaPacienteAbierta(open: boolean) { + this.fichaPacienteAbierta.set(open); + if (open) this.closeGraphicNavigation(false, false); + } changeSection(section: DashboardSection) { if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return; + if (section !== 'resumen') this.closeGraphicNavigation(false, false); this.activeSection.set(section); // Retain views, filters and Plotly hosts; only visible regions authorize loading. if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false); @@ -64,6 +72,26 @@ export class IndicadoresPage { private readonly element = inject>(ElementRef); private readonly injector = inject(Injector); private readonly searchInput = viewChild>('searchInput'); + private readonly overlay = inject(Overlay); + readonly navigationScrollStrategy = this.overlay.scrollStrategies.reposition(); + readonly navigationPositions: ConnectedPosition[] = [ + { originX: 'start', originY: 'center', overlayX: 'start', overlayY: 'center' }, + { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top' }, + { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' }, + { originX: 'end', originY: 'center', overlayX: 'end', overlayY: 'center' }, + ]; + readonly navigationOpen = signal(false); + readonly navigationClosing = signal(false); + readonly navigationAttached = computed(() => this.navigationOpen() || this.navigationClosing()); + readonly navigationKeyboard = signal(false); + private readonly navigationPanel = viewChild(IndicadoresNavegacionPanel); + private navigationHoverTimer?: ReturnType; + private navigationAnimationTimer?: ReturnType; + private navigationPointerInside = false; + // Removing the overlay can generate pointerenter on the button under a stationary cursor. + private navigationHoverDismissed = false; + readonly navigationItems = computed(() => + this.searchResults().items.map(item => ({ key: indicatorIdentity(this.dominio, item.id), titulo: item.titulo }))); private readonly graphicCards = viewChildren(IndicadorCatalogCard); private readonly observedRegions = new Map(); private renderedCards: readonly IndicadorCatalogCard[] = []; @@ -246,8 +274,27 @@ export class IndicadoresPage { readonly kpisByDomain = KPI_BY_DOMAIN; figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); } independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); } - kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); } + kpiIndicator(id: string) { + const published = this.catalog().find(item => item.id === id); + if (published) return published; + // The lab partner is deliberately hidden from some catalogs, as in the paired figure. + // Reuse its established periodicity, without assigning the diagnosis version to lab data. + if (this.dominio === 'cacu' && id === CACU_RESULTADO_KPI.id) { + const diagnosis = this.catalog().find(item => item.id === 'cacu_dias_toma_diagnostico'); + if (diagnosis) return { id, titulo: CACU_RESULTADO_KPI.title, contrato: diagnosis.contrato, + figuras: [], tipos_periodo: diagnosis.tipos_periodo }; + } + return undefined; + } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } + get opportunityKpis() { + const definitions = this.availableKpis; + if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions; + // Keep the established KPI definitions and initial-period anchor intact. + const diagnosis = definitions.findIndex(item => item.id === 'cacu_dias_toma_diagnostico'); + return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI, + ...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)]; + } private readonly catalogRequests = new Subject(); readonly catalog = signal([]); readonly searchQuery = signal(''); @@ -303,8 +350,117 @@ export class IndicadoresPage { this.changeDetector.markForCheck(); } cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); } + cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); } + get showGraphicNavigation() { + return this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading() + && !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0; + } + toggleGraphicNavigation(event?: MouseEvent) { + if (!this.showGraphicNavigation) return; + if (this.navigationOpen()) this.closeGraphicNavigation(false); + else this.openGraphicNavigation(event?.detail === 0); + } + private openGraphicNavigation(keyboard = false) { + if (!this.showGraphicNavigation) return; + this.clearNavigationTimers(); + this.navigationHoverDismissed = false; + this.navigationKeyboard.set(keyboard); + this.navigationClosing.set(false); + this.navigationOpen.set(true); + if (keyboard) afterNextRender(() => { + if (this.navigationOpen() && this.navigationKeyboard()) this.navigationPanel()?.focusFirstOption(); + }, { injector: this.injector }); + } + navigationTriggerKeydown(event: KeyboardEvent) { + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); + this.openGraphicNavigation(true); + } + navigationPointerEnter(event: PointerEvent) { + if (this.navigationHoverDismissed || !this.navigationCanHover(event)) return; + this.navigationPointerInside = true; + if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer); + this.navigationHoverTimer = undefined; + if (!this.navigationOpen()) this.openGraphicNavigation(); + } + navigationPointerMove(event: PointerEvent) { + if (!this.navigationHoverDismissed || !this.navigationCanHover(event)) return; + this.navigationHoverDismissed = false; + this.navigationPointerEnter(event); + } + private navigationCanHover(event: PointerEvent) { + return event.pointerType === 'mouse' && this.document.defaultView?.matchMedia?.('(hover: hover) and (pointer: fine)').matches; + } + navigationPointerLeave(event: PointerEvent) { + if (!this.navigationCanHover(event)) return; + this.navigationPointerInside = false; + this.scheduleNavigationClose(); + } + navigationFocusOut() { this.scheduleNavigationClose(); } + private scheduleNavigationClose() { + if (!this.navigationOpen()) return; + if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer); + this.navigationHoverTimer = setTimeout(() => { + this.navigationHoverTimer = undefined; + if (!this.navigationPointerInside && !this.navigationPanel()?.containsFocus()) this.closeGraphicNavigation(false); + }, 230); + } + navigationOverlayKeydown(event: KeyboardEvent) { + if (event.key !== 'Escape') return; + event.preventDefault(); + this.closeGraphicNavigation(); + } + private clearNavigationTimers() { + if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer); + if (this.navigationAnimationTimer !== undefined) clearTimeout(this.navigationAnimationTimer); + this.navigationHoverTimer = this.navigationAnimationTimer = undefined; + } + closeGraphicNavigation(restoreFocus = true, animate = true) { + const wasOpen = this.navigationOpen(); + this.clearNavigationTimers(); + this.navigationHoverDismissed ||= wasOpen; + this.navigationPointerInside = false; + this.navigationKeyboard.set(false); + this.navigationOpen.set(false); + const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + this.navigationClosing.set(animate && wasOpen && !reducedMotion); + if (this.navigationClosing()) this.navigationAnimationTimer = setTimeout(() => { + this.navigationAnimationTimer = undefined; + this.navigationClosing.set(false); + }, 180); + if (wasOpen && restoreFocus && this.showGraphicNavigation) { + this.element.nativeElement.querySelector('.graphic-navigation-trigger')?.focus({ preventScroll: true }); + } + } + closeGraphicNavigationFromOutside(event: MouseEvent) { + const target = event.target; + const trigger = this.element.nativeElement.querySelector('.graphic-navigation-trigger'); + if (target instanceof Node && trigger?.contains(target)) return; + this.closeGraphicNavigation(false); + } + selectGraphicNavigation(key: string) { + if (!this.navigationItems().some(item => item.key === key)) { + this.closeGraphicNavigation(false); + return; + } + this.closeGraphicNavigation(false, false); + afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector }); + } + private scrollToIndicator(key: string) { + if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta() + || !this.navigationItems().some(item => item.key === key)) return; + const target = this.document.getElementById(identityElementId(key)); + const grid = this.element.nativeElement.querySelector('.catalog-grid'); + if (!target || !grid?.contains(target)) return; + const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' }); + target.querySelector('h2')?.focus({ preventScroll: true }); + } constructor() { - afterEveryRender(() => this.syncVisibility()); + afterEveryRender(() => { + this.syncVisibility(); + if (!this.showGraphicNavigation && (this.navigationAttached() || this.navigationHoverTimer !== undefined)) this.closeGraphicNavigation(false, false); + }); const browser = this.document.defaultView; if (typeof IntersectionObserver !== 'undefined') { browser?.addEventListener('scroll', this.viewportChanged, { passive: true }); @@ -313,6 +469,7 @@ export class IndicadoresPage { this.destroyRef.onDestroy(() => { this.filtersEdited(); this.visibilityDestroyed = true; + this.closeGraphicNavigation(false, false); this.clearVisibility(); this.sizeObserver?.disconnect(); this.sizeTargets.clear(); @@ -327,6 +484,7 @@ export class IndicadoresPage { return this.periodService.dominio(this.dominio, this.catalog()); }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { + this.closeGraphicNavigation(false, false); this.cancelInitialPeriod.next(); this.initialPeriodState.set('ready'); this.clearVisibility(); @@ -348,6 +506,7 @@ export class IndicadoresPage { } changeDominio(dominio: Dominio) { if (!isDominio(dominio) || dominio === this.dominio) return; + this.closeGraphicNavigation(false, false); this.activeSection.set('resumen'); this.searchQuery.set(''); this.filtersEdited(); diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts index f82cc9a..651d938 100644 --- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -6,7 +6,7 @@ import { By } from '@angular/platform-browser'; import { IndicadoresPage } from './indicadores-page'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorPeriodFilters } from './indicador-period-filters'; -import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; import { Dominio, IndicadorDatos } from './indicadores.models'; describe('P0.1 selección publicada y último periodo por KPI', () => { @@ -29,7 +29,18 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i]))); fixture.detectChanges(); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } + // 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(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos { const d = KPI_BY_DOMAIN[domain][index]; @@ -41,7 +52,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { function flushDatos(domain: Dominio, suppressed = false) { const resolved = []; for (;;) { - const requests = http.match(r => r.url.endsWith('/datos')); + const requests = originalRequests(); if (!requests.length) return resolved; resolved.push(...requests); requests.forEach(r => { @@ -65,7 +76,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { }); it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => { load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2'])); - const initial = http.match(r => r.url.endsWith('/datos')); + const initial = originalRequests(); fixture.componentInstance.applyFilters(); fixture.detectChanges(); expect(initial.every(r => r.cancelled)).toBe(true); const requests = flushDatos('cacu', true); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 6acee62..82e4f1d 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -1,3 +1,9 @@ +@if (pacienteDetalle.estado().tipo !== 'cerrado') { + +} +

    Seguimiento de {{ domainLabel }}

    @if (dominio !== 'cacu') {

    El seguimiento aún no está disponible.

    @@ -32,11 +38,11 @@
    Q1, mediana y Q3 en días por periodo
    Periodo{{ par.etiquetas[clave] }}
    - + @for (item of response.items; track item.id_seudonimo) { - - + + @@ -52,3 +58,4 @@ } } + diff --git a/src/app/features/indicadores/indicadores-tracking.scss b/src/app/features/indicadores/indicadores-tracking.scss index d11eaeb..a44f5d8 100644 --- a/src/app/features/indicadores/indicadores-tracking.scss +++ b/src/app/features/indicadores/indicadores-tracking.scss @@ -16,3 +16,8 @@ th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px th { background: var(--issste-background); font-weight: 600; } small { display: block; margin-top: .35rem; } nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; } +tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; } +tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); } +tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; } +.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; } +.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index f0115e8..0610727 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -1,16 +1,20 @@ -import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core'; +import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Injector, Input, OnChanges, output } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; -import { latestStudy, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { MatButtonModule } from '@angular/material/button'; +import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; +import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'; import { Dominio } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; @Component({ selector: 'app-indicadores-tracking', - imports: [FormsModule], + imports: [FormsModule, MatButtonModule, PacienteDetalleComponent], + providers: [PacienteDetalleState], templateUrl: './indicadores-tracking.html', styleUrl: './indicadores-tracking.scss', }) @@ -22,6 +26,10 @@ export class IndicadoresTracking implements OnChanges { private readonly indicators = inject(IndicadoresService); private readonly destroy = inject(DestroyRef); private readonly changeDetector = inject(ChangeDetectorRef); + private readonly injector = inject(Injector); + readonly pacienteDetalle = inject(PacienteDetalleState); + readonly fichaPacienteAbierta = output(); + private controlPaciente?: HTMLElement; private readonly requests = new Subject(); private initialized = false; private previousDomain?: Dominio; @@ -61,6 +69,8 @@ export class IndicadoresTracking implements OnChanges { } ngOnChanges() { if (this.previousDomain !== this.dominio) { + if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false); + this.pacienteDetalle.cerrar(); this.controlPaciente = undefined; this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined; this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft }; } @@ -77,6 +87,27 @@ export class IndicadoresTracking implements OnChanges { if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return; this.load({ ...this.applied, page }); } + abrirPaciente(paciente: SeguimientoPaciente, evento: Event) { + if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return; + evento.stopPropagation(); + if (evento.type === 'click' && evento.currentTarget instanceof HTMLButtonElement) { + if (evento.currentTarget.classList.contains('patient-link')) evento.preventDefault(); + this.controlPaciente = evento.currentTarget; + } else if (evento.type === 'click' && evento.currentTarget instanceof HTMLTableRowElement + && evento.target instanceof HTMLElement && !evento.target.closest('button, a, input, select, textarea')) this.controlPaciente = evento.currentTarget; + else if (evento.type === 'click' && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return; + else if (evento.type !== 'click') return; + this.pacienteDetalle.abrir(paciente, this.data.corte); + this.fichaPacienteAbierta.emit(true); + } + volverASeguimiento() { + this.pacienteDetalle.cerrar(); + this.fichaPacienteAbierta.emit(false); + const control = this.controlPaciente; + afterNextRender(() => { + if (control?.isConnected) control.focus({ preventScroll: true }); + }, { injector: this.injector }); + } // The shown cytology is the patient's latest in the window. Without a Bethesda result it is either // unsatisfactory (`cacu.calidad_insatisfactoria` in the kit) or not yet reported at the cut-off. cytologyLabel(c: { bethesda: string | null; calidad: string | null }) { diff --git a/src/app/features/indicadores/paciente-detalle/fecha-compuesta.html b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.html new file mode 100644 index 0000000..6ae0c46 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.html @@ -0,0 +1,33 @@ +
    +

    {{ etiqueta }}

    +
    + + Día + + + @for (dia of diasSugeridos; track dia) { {{ dia }} } + + + + Mes + + + @for (mes of mesesSugeridos; track mes) { {{ mes }} } + + + + Año + + + @for (anio of aniosSugeridos; track anio) { {{ anio }} } + + +
    + @if (mostrarError) {

    {{ mensajeError }}

    } +
    diff --git a/src/app/features/indicadores/paciente-detalle/fecha-compuesta.scss b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.scss new file mode 100644 index 0000000..9470ef1 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.scss @@ -0,0 +1,8 @@ +:host { display: block; min-width: 0; } +.etiqueta { margin: 0 0 .5rem; font-size: .875rem; font-weight: 500; } +.partes { display: grid; grid-template-columns: minmax(0, .8fr) minmax(0, 1.6fr) minmax(0, 1fr); gap: .5rem; } +mat-form-field { width: 100%; min-width: 0; } +.error { margin: .25rem 0 0; color: var(--mat-sys-error, #ba1a1a); font-size: .75rem; } +@media (max-width: 400px) { + .partes { grid-template-columns: minmax(0, 1fr); } +} diff --git a/src/app/features/indicadores/paciente-detalle/fecha-compuesta.spec.ts b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.spec.ts new file mode 100644 index 0000000..9b1d2e4 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.spec.ts @@ -0,0 +1,222 @@ +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; +import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; +import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing'; +import { MatInputHarness } from '@angular/material/input/testing'; +import { FechaCompuesta } from './fecha-compuesta'; + +@Component({ + imports: [ReactiveFormsModule, FechaCompuesta], + template: '', +}) +class FormularioFecha { + readonly fecha = new FormControl('', { nonNullable: true, validators: [Validators.required] }); +} + +describe('Fecha compuesta reutilizable', () => { + let fixture: ReturnType>; + let fecha: FormControl; + let control: FechaCompuesta; + let root: HTMLElement; + + beforeEach(() => { + fixture = TestBed.createComponent(FormularioFecha); + fecha = fixture.componentInstance.fecha; + root = fixture.nativeElement; + fixture.detectChanges(); + control = fixture.debugElement.query(By.directive(FechaCompuesta)).componentInstance; + }); + + async function escribir(parte: string, valor: string) { + const input = await TestbedHarnessEnvironment.loader(fixture).getHarness( + MatInputHarness.with({ selector: `[data-fecha="${parte}"]` })); + await input.setValue(valor); + } + async function capturar(dia: string, mes: string, anio: string) { + await escribir('dia', dia); await escribir('mes', mes); await escribir('anio', anio); + } + function entrada(parte: string) { return root.querySelector(`[data-fecha="${parte}"]`)!; } + function tecla(input: HTMLInputElement, key: string, keyCode: number) { + input.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true })); + fixture.detectChanges(); + } + + it('empieza vacío e inválido sin errores prematuros, con etiquetas y orden día-mes-año', () => { + expect(fecha.invalid).toBe(true); + expect(root.querySelector('.error')).toBeNull(); + expect(root.querySelector('[role="group"]')?.getAttribute('aria-labelledby')).toBe(control.id + '-titulo'); + expect(root.querySelector('#' + control.id + '-titulo')?.textContent).toContain('Fecha del estudio'); + expect(Array.from(root.querySelectorAll('input')).map(input => input.dataset['fecha'])).toEqual(['dia', 'mes', 'anio']); + for (const parte of ['dia', 'mes', 'anio']) { + const input = entrada(parte); + expect(input.required).toBe(true); + expect(input.tabIndex).toBe(0); + expect(root.querySelector(`label[for="${input.id}"]`)?.textContent).toMatch(/Día|Mes|Año/); + } + }); + + it('captura manualmente sin seleccionar sugerencias y conserva ISO sin conversión horaria', async () => { + await capturar('26', 'octubre', '2026'); + expect(fecha.valid).toBe(true); + expect(fecha.value).toBe('2026-10-26'); + await capturar('1', '01', '0001'); + expect(fecha.value).toBe('0001-01-01'); + await capturar('31', '12', '9999'); + expect(fecha.value).toBe('9999-12-31'); + }); + + it('ofrece doce meses y filtra nombres y números sin aceptar fragmentos ambiguos', async () => { + const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness( + MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' })); + await mes.focus(); + expect(await mes.getOptions()).toHaveLength(12); + await mes.enterText('ma'); + expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Marzo', 'Mayo']); + await escribir('dia', '15'); await escribir('anio', '2026'); + expect(fecha.value).toBe(''); + expect(fecha.invalid).toBe(true); + await mes.clear(); await mes.enterText('10'); + expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Octubre']); + expect(fecha.value).toBe('2026-10-15'); + for (const valor of ['13', '0', 'mes desconocido', 'mar']) { + await mes.clear(); await mes.enterText(valor); + expect(fecha.value, valor).toBe(''); + expect(fecha.invalid).toBe(true); + } + }); + + it('selecciona los tres componentes mediante autocompletado', async () => { + const loader = TestbedHarnessEnvironment.loader(fixture); + for (const [parte, valor] of [['anio', '2024'], ['mes', 'Febrero'], ['dia', '29']]) { + const input = await loader.getHarness(MatAutocompleteHarness.with({ selector: `[data-fecha="${parte}"]` })); + if (parte === 'anio') await input.enterText(valor); else await input.focus(); + await input.selectOption({ text: valor }); + } + expect(fecha.value).toBe('2024-02-29'); + expect(fecha.valid).toBe(true); + }); + + it('navega las sugerencias con flechas y Enter y cierra con Escape manteniendo el foco', async () => { + const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness( + MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' })); + await mes.enterText('ma'); + tecla(entrada('mes'), 'ArrowDown', 40); + tecla(entrada('mes'), 'ArrowDown', 40); + tecla(entrada('mes'), 'ArrowUp', 38); + expect(entrada('mes').getAttribute('aria-activedescendant')).toBeTruthy(); + tecla(entrada('mes'), 'Enter', 13); + await fixture.whenStable(); + expect(await mes.getValue()).toBe('Marzo'); + expect(await mes.isOpen()).toBe(false); + await mes.clear(); await mes.enterText('ab'); + tecla(entrada('mes'), 'Escape', 27); + await fixture.whenStable(); + expect(await mes.isOpen()).toBe(false); + expect(await mes.isFocused()).toBe(true); + expect(await mes.getValue()).toBe('ab'); + }); + + it.each([ + ['31', 'Abril', '2026'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2026'], + ['29', 'Febrero', '1900'], ['0', 'Enero', '2026'], ['32', 'Enero', '2026'], + ['1.5', 'Enero', '2026'], ['1', 'Enero', '0'], ['1', 'Enero', '10000'], + ['1', 'Enero', '-1'], ['1', 'Enero', '20e2'], + ])('rechaza fecha imposible o entrada inválida %s / %s / %s', async (dia, mes, anio) => { + await capturar(dia, mes, anio); + expect(fecha.value).toBe(''); + expect(fecha.invalid).toBe(true); + }); + + it.each(['2000', '2024'])('admite 29 de febrero en el año bisiesto %s', async anio => { + await capturar('29', 'Febrero', anio); + expect(fecha.value).toBe(`${anio}-02-29`); + expect(fecha.valid).toBe(true); + }); + + it('invalida el día al cambiar mes o año sin corregirlo silenciosamente ni conservar el ISO anterior', async () => { + await capturar('31', 'Marzo', '2024'); + expect(fecha.value).toBe('2024-03-31'); + await escribir('mes', 'Abril'); + expect(fecha.value).toBe(''); + expect(entrada('dia').value).toBe('31'); + expect(control.diasSugeridos).toHaveLength(30); + await capturar('29', 'Febrero', '2024'); + expect(control.diasSugeridos).toHaveLength(29); + await escribir('anio', '2025'); + expect(fecha.value).toBe(''); + expect(fecha.invalid).toBe(true); + expect(entrada('dia').value).toBe('29'); + expect(control.diasSugeridos).toHaveLength(28); + await escribir('anio', '2024'); + expect(fecha.value).toBe('2024-02-29'); + }); + + it.each(['dia', 'mes', 'anio'])('vaciar %s invalida inmediatamente una fecha previamente válida', async parte => { + await capturar('26', 'Octubre', '2026'); + await escribir(parte, ''); + expect(fecha.value).toBe(''); + expect(fecha.invalid).toBe(true); + }); + + it('muestra un único error asociado al salir del grupo o al solicitar validación', async () => { + const dia = entrada('dia'); + dia.focus(); + entrada('mes').focus(); + fixture.detectChanges(); + expect(fecha.touched).toBe(false); + expect(root.querySelector('.error')).toBeNull(); + root.querySelector('button')!.focus(); + fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + expect(fecha.touched).toBe(true); + expect(root.querySelectorAll('.error')).toHaveLength(1); + for (const input of root.querySelectorAll('input')) { + expect(input.getAttribute('aria-describedby')).toContain(control.id + '-error'); + expect(input.getAttribute('aria-required')).toBe('true'); + } + fecha.reset(''); fixture.detectChanges(); + expect(root.querySelector('.error')).toBeNull(); + fecha.markAllAsTouched(); fixture.detectChanges(); + expect(root.querySelector('.error')?.textContent).toContain('completa día, mes y año'); + await capturar('31', 'Abril', '2026'); + expect(root.querySelector('.error')?.textContent).toContain('ese día no existe'); + expect(dia.getAttribute('aria-invalid')).toBe('true'); + await escribir('dia', '30'); + expect(root.querySelector('.error')).toBeNull(); + }); + + it('acepta valores externos sin emitir cambios adicionales y no normaliza fechas inválidas', async () => { + const cambios = vi.fn(); + fecha.valueChanges.subscribe(cambios); + fecha.setValue('2024-02-29'); fixture.detectChanges(); + await fixture.whenStable(); + expect(cambios).toHaveBeenCalledExactlyOnceWith('2024-02-29'); + expect(entrada('dia').value).toBe('29'); + expect(entrada('mes').value).toBe('Febrero'); + expect(entrada('anio').value).toBe('2024'); + expect(fecha.valid).toBe(true); + for (const valor of ['2026-02-30', '2026-13-01', 'ayer', '2026-1-1', '2026-10-26T00:00:00Z']) { + fecha.setValue(valor); fixture.detectChanges(); + expect(fecha.value).toBe(valor); + expect(fecha.invalid).toBe(true); + } + fecha.reset(''); fixture.detectChanges(); + await fixture.whenStable(); + expect(Array.from(root.querySelectorAll('input')).every(input => input.value === '')).toBe(true); + }); + + it('propaga disabled y permite años históricos y futuros sin listas enormes', async () => { + fecha.disable(); fixture.detectChanges(); + expect(Array.from(root.querySelectorAll('input')).every(input => input.disabled)).toBe(true); + fecha.enable(); fixture.detectChanges(); + for (const anio of ['0001', '1500', '2100', '9999']) { + await capturar('1', 'Enero', anio); + expect(fecha.value).toBe(`${anio}-01-01`); + expect(fecha.valid).toBe(true); + expect(control.aniosSugeridos.length).toBeLessThanOrEqual(7); + expect(control.aniosSugeridos).toContain(anio); + expect(control.aniosSugeridos.every(opcion => Number(opcion) >= 1 && Number(opcion) <= 9999)).toBe(true); + } + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/fecha-compuesta.ts b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.ts new file mode 100644 index 0000000..16866f4 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/fecha-compuesta.ts @@ -0,0 +1,153 @@ +import { AfterViewInit, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, Input, OnInit, forwardRef, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgControl, ReactiveFormsModule, ValidationErrors, Validator } from '@angular/forms'; +import { MatAutocompleteModule } from '@angular/material/autocomplete'; +import { ErrorStateMatcher } from '@angular/material/core'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { esFechaReal } from './paciente-registro.validation'; + +const MESES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', + 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']; +let siguienteId = 0; + +/** Tres entradas editables; el formulario recibe exclusivamente ISO de calendario o vacío. */ +@Component({ + selector: 'app-fecha-compuesta', + imports: [ReactiveFormsModule, MatAutocompleteModule, MatFormFieldModule, MatInputModule], + templateUrl: './fecha-compuesta.html', + styleUrl: './fecha-compuesta.scss', + providers: [ + { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FechaCompuesta), multi: true }, + { provide: NG_VALIDATORS, useExisting: forwardRef(() => FechaCompuesta), multi: true }, + ], +}) +export class FechaCompuesta implements ControlValueAccessor, Validator, OnInit, AfterViewInit { + @Input() etiqueta = 'Fecha'; + readonly id = `fecha-compuesta-${siguienteId++}`; + readonly partes = new FormGroup({ + dia: new FormControl('', { nonNullable: true }), + mes: new FormControl('', { nonNullable: true }), + anio: new FormControl('', { nonNullable: true }), + }); + private readonly injector = inject(Injector); + private readonly host = inject>(ElementRef); + private readonly cdr = inject(ChangeDetectorRef); + private readonly destroy = inject(DestroyRef); + private ngControl: NgControl | null = null; + private visitado = false; + private entradaExternaInvalida = false; + private onChange: (valor: string) => void = () => {}; + private onTouched: () => void = () => {}; + readonly estadoError: ErrorStateMatcher = { isErrorState: () => this.mostrarError }; + + constructor() { + this.partes.valueChanges.pipe(takeUntilDestroyed(this.destroy)).subscribe(() => { + this.entradaExternaInvalida = false; + // Emitir también al invalidarse: nunca conservar la última fecha válida. + this.onChange(this.fechaIso); + this.cdr.markForCheck(); + }); + } + + ngOnInit() { + // Resolver después de crear los providers CVA/Validator evita una dependencia circular. + this.ngControl = this.injector.get(NgControl, null, { self: true }); + } + + ngAfterViewInit() { + // FormControlName ya está conectado al FormGroup al terminar de crear la vista. + // markAllAsTouched/reset del formulario también deben refrescar el grupo con OnPush. + this.ngControl?.control?.events.pipe(takeUntilDestroyed(this.destroy)) + .subscribe(() => this.cdr.markForCheck()); + } + + private numero(valor: string, digitos: number): number | null { + const texto = valor.trim(); + return new RegExp(`^\\d{1,${digitos}}$`).test(texto) ? Number(texto) : null; + } + + private get mesNumero(): number | null { + const texto = this.partes.controls.mes.value.trim().toLocaleLowerCase('es'); + const numero = this.numero(texto, 2); + if (numero !== null) return numero >= 1 && numero <= 12 ? numero : null; + const indice = MESES.findIndex(mes => mes.toLocaleLowerCase('es') === texto); + return indice >= 0 ? indice + 1 : null; + } + + get mesesSugeridos(): string[] { + const texto = this.partes.controls.mes.value.trim().toLocaleLowerCase('es'); + const numero = this.numero(texto, 2); + if (numero !== null) return numero >= 1 && numero <= 12 ? [MESES[numero - 1]] : []; + return MESES.filter(mes => mes.toLocaleLowerCase('es').includes(texto)); + } + + get diasSugeridos(): string[] { + const mes = String(this.mesNumero ?? 1).padStart(2, '0'); + const numeroAnio = this.numero(this.partes.controls.anio.value, 4); + // Sin año válido se ofrece el máximo de febrero; completar el año vuelve a validar. + const anio = String(numeroAnio || 2000).padStart(4, '0'); + return Array.from({ length: 31 }, (_, i) => String(i + 1)) + .filter(dia => esFechaReal(`${anio}-${mes}-${dia.padStart(2, '0')}`)); + } + + get aniosSugeridos(): string[] { + const escrito = this.numero(this.partes.controls.anio.value, 4); + const centro = escrito && escrito <= 9999 ? escrito : new Date().getFullYear(); + return Array.from({ length: 7 }, (_, i) => centro - 3 + i) + .filter(anio => anio >= 1 && anio <= 9999).map(anio => String(anio).padStart(4, '0')); + } + + private get fechaIso(): string { + const { dia, anio } = this.partes.getRawValue(); + const d = this.numero(dia, 2); + const m = this.mesNumero; + const a = this.numero(anio, 4); + if (d === null || m === null || a === null) return ''; + const fecha = `${String(a).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`; + return esFechaReal(fecha) ? fecha : ''; + } + + get mensajeError(): string { + if (this.entradaExternaInvalida) return 'Ingresa una fecha real de calendario.'; + const { dia, mes, anio } = this.partes.getRawValue(); + if (![dia, mes, anio].every(valor => valor.trim())) return 'Ingresa una fecha válida: completa día, mes y año.'; + if (this.mesNumero === null) return 'Escribe el nombre completo del mes o un número del 1 al 12.'; + const a = this.numero(anio, 4); + if (a === null || a < 1) return 'Ingresa un año entre 0001 y 9999.'; + if (!this.fechaIso) return 'Ingresa una fecha real: ese día no existe en el mes y año indicados.'; + return ''; + } + + get mostrarError(): boolean { + return !this.partes.disabled && !!this.mensajeError && (this.ngControl?.touched ?? this.visitado); + } + + salir(event: FocusEvent) { + if (!this.host.nativeElement.contains(event.relatedTarget as Node | null)) { + this.visitado = true; + this.onTouched(); + } + } + + writeValue(valor: unknown): void { + const coincidencia = typeof valor === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(valor) : null; + this.entradaExternaInvalida = !!valor && !esFechaReal(valor); + this.visitado = false; + this.partes.reset(coincidencia ? { + dia: coincidencia[3], mes: MESES[Number(coincidencia[2]) - 1] ?? coincidencia[2], anio: coincidencia[1], + } : { dia: '', mes: '', anio: '' }, { emitEvent: false }); + this.cdr.markForCheck(); + } + + registerOnChange(fn: (valor: string) => void): void { this.onChange = fn; } + registerOnTouched(fn: () => void): void { this.onTouched = fn; } + setDisabledState(deshabilitado: boolean): void { + if (deshabilitado) this.partes.disable({ emitEvent: false }); + else this.partes.enable({ emitEvent: false }); + this.cdr.markForCheck(); + } + validate(control: AbstractControl): ValidationErrors | null { + return esFechaReal(control.value) && this.fechaIso === control.value ? null : { fechaCompuesta: true }; + } +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.fixtures.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.fixtures.ts new file mode 100644 index 0000000..beeccd3 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.fixtures.ts @@ -0,0 +1,19 @@ +import { PacienteDetalle } from './paciente-detalle.models'; + +// Explicit demonstration identities only. Never derive a history from age, status or a hash. +export const PACIENTES_DETALLE_SINTETICOS: readonly PacienteDetalle[] = [ + { + id_seudonimo: 'P-4BC9B9E8F4', + origen: 'sintetico', + historial: [{ descripcion: 'Antecedente de tamizaje cervical (demostración)', fecha: '2025-06-12', notas: null }], + procedimientos: [], + pruebas: [{ nombre: 'Citología previa (demostración)', fecha: '2025-06-12', resultado: 'Negativa para lesión intraepitelial' }], + }, + { + id_seudonimo: 'P-2C9E494F5D', + origen: 'sintetico', + historial: null, + procedimientos: [{ nombre: 'Colposcopia (demostración)', fecha: '2026-06-10', resultado: null }], + pruebas: [{ nombre: 'Histopatología (demostración)', fecha: null, resultado: null }], + }, +]; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html new file mode 100644 index 0000000..d3d931a --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html @@ -0,0 +1,85 @@ +@if (estado.tipo !== 'cerrado') { + +
    +

    Paciente {{ estado.resumen.id_seudonimo }}

    +

    Fecha de corte: {{ estado.resumen.corte }}.

    +
    +
    Identificador seudónimo
    {{ estado.resumen.id_seudonimo }}
    +
    Grupo de edad
    {{ estado.resumen.grupoEdad ?? 'No disponible' }}
    +
    Estatus de seguimiento
    {{ estado.resumen.estatus ?? 'No disponible' }}
    +
    Días de toma a diagnóstico
    {{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}
    +
    Prioridad
    {{ estado.resumen.prioridad ?? 'No disponible' }}
    +
    +
    + @if (estado.tipo === 'cargando') {

    Cargando información…

    } + @if (estado.tipo === 'no-disponible') {

    Información no disponible.

    } + @if (estado.tipo === 'error') { } + @if (registrosTemporales.length) {

    Cambios sin guardar

    } +
    + +

    Historial médico relevante

    + +
    + + +
    +
    +
    Resultados disponibles por paciente
    Identificador seudónimoGrupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
    Identificador seudónimoGrupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
    {{ item.id_seudonimo }}{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }}
    {{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible } {{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
    + + + + @if (estado.tipo === 'disponible') { + @if (estado.detalle.historial; as historial) { + @for (item of historial; track $index) { + + } + @if (!historial.length && !temporales('condicion').length) { } + } @else if (!temporales('condicion').length) { } + } @else if (!temporales('condicion').length) { } + @for (item of temporales('condicion'); track item.id) { + + } + + @if (estado.tipo === 'disponible') { + @if (estado.detalle.procedimientos; as procedimientos) { + @for (item of procedimientos; track $index) { + + } + @if (!procedimientos.length && !temporales('procedimiento').length) { } + } @else if (!temporales('procedimiento').length) { } + } @else if (!temporales('procedimiento').length) { } + @for (item of temporales('procedimiento'); track item.id) { + + } + +
    RegistroFecha
    Condiciones
    {{ item.descripcion }}@if (item.notas) { {{ item.notas }} }{{ item.fecha ?? 'No disponible' }}
    Sin registros.
    Información no disponible.
    Información no disponible.
    {{ etiquetaRegistro(item) }}Agregado en esta sesión{{ item.fecha }}
    Procedimientos
    {{ item.nombre }}@if (item.resultado) { Resultado: {{ item.resultado }} }{{ item.fecha ?? 'No disponible' }}
    Sin registros.
    Información no disponible.
    Información no disponible.
    {{ etiquetaRegistro(item) }}Agregado en esta sesión{{ item.fecha }}
    +
    + + + +

    Pruebas y resultados

    + + +

    Últimos resultados

    +
      +
    • Última citología@if (estado.resumen.citologia; as c) { Fecha: {{ c.fecha }}Resultado: {{ etiquetaCitologia(c.resultado, c.calidad) }}Calidad: {{ c.calidad ?? 'No disponible' }} } @else { No disponible }
    • +
    • Último resultado de VPH@if (estado.resumen.vph; as v) { Fecha: {{ v.fecha }}Resultado: {{ v.resultado }}Genotipo 16/18: {{ v.genotipo16y18 === null ? 'No disponible' : v.genotipo16y18 ? 'Presente' : 'No detectado' }} } @else { No disponible }
    • +
    + @if (estado.tipo === 'disponible') { +

    Pruebas adicionales

    + @if (estado.detalle.pruebas; as pruebas) { +
      @for (item of pruebas; track $index) {
    • {{ item.nombre }}Fecha: {{ item.fecha ?? 'No disponible' }}Resultado: {{ item.resultado ?? 'No disponible' }}
    • } @empty {
    • Sin registros.
    • }
    + } @else {

    Información no disponible.

    } + } + @if (estado.tipo === 'disponible' || temporales('resultado').length) { +

    Resultados agregados

    +
      @for (item of temporales('resultado'); track item.id) {
    • {{ etiquetaRegistro(item) }}Fecha: {{ item.fecha }}Resultado: {{ etiquetaResultado(item) }}
    • } @empty {
    • Sin registros.
    • }
    + } +
    +
    + +

    Riesgos y recomendaciones

    + +
    + +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts new file mode 100644 index 0000000..fe7b778 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts @@ -0,0 +1,36 @@ +import { Observable } from 'rxjs'; + +/** Snapshot of the received row, independent of the Seguimiento transport contract. */ +export interface PacienteResumen { + id_seudonimo: string; + grupoEdad: string | null; + estatus: string | null; + corte: string; + origen: 'seguimiento-demostracion'; + citologia: { fecha: string; resultado: string | null; calidad: string | null } | null; + vph: { fecha: string; resultado: string; genotipo16y18: boolean | null } | null; + diasTomaDiagnostico: number | null; + prioridad: string | null; +} + +export interface AntecedenteDetalle { descripcion: string; fecha: string | null; notas?: string | null; } +export interface ProcedimientoDetalle { nombre: string; fecha: string | null; resultado?: string | null; } +export interface PruebaDetalle { nombre: string; fecha: string | null; resultado: string | null; } + +/** null = unavailable collection; [] = no entries supplied, never proof of clinical absence. */ +export interface PacienteDetalle { + id_seudonimo: string; + origen: 'sintetico'; + historial: AntecedenteDetalle[] | null; + procedimientos: ProcedimientoDetalle[] | null; + pruebas: PruebaDetalle[] | null; +} + +export interface PacienteDetalleProvider { + obtener(idSeudonimo: string): Observable; +} + +export type PacienteDetalleEstado = + | { tipo: 'cerrado' } + | { tipo: 'cargando' | 'no-disponible' | 'error'; resumen: PacienteResumen } + | { tipo: 'disponible'; resumen: PacienteResumen; detalle: PacienteDetalle }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts new file mode 100644 index 0000000..c7e6601 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts @@ -0,0 +1,20 @@ +import { Injectable, InjectionToken, inject } from '@angular/core'; +import { defer, of } from 'rxjs'; +import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; +import { PacienteDetalleProvider } from './paciente-detalle.models'; + +@Injectable({ providedIn: 'root' }) +export class PacienteDetalleMockProvider implements PacienteDetalleProvider { + obtener(idSeudonimo: string) { + return defer(() => { + const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo); + // Each read owns its data; consumers cannot mutate another selection or the fixtures. + return of(detalle ? structuredClone(detalle) : null); + }); + } +} + +export const PACIENTE_DETALLE_PROVIDER = new InjectionToken('PacienteDetalleProvider', { + providedIn: 'root', + factory: () => inject(PacienteDetalleMockProvider), +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.scss b/src/app/features/indicadores/paciente-detalle/paciente-detalle.scss new file mode 100644 index 0000000..c51cb4a --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.scss @@ -0,0 +1,36 @@ +:host { display: block; min-width: 0; color: var(--issste-text); overflow-wrap: anywhere; } +header { margin-block: 1.5rem; } +h2 { margin-block: .5rem 1rem; font-size: 1.65rem; } +h3 { margin-block: 0 1rem; font-size: 1.2rem; } +h4 { font: inherit; font-weight: 600; } +.back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; } +.back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; } +.availability { margin-block: .75rem; color: var(--issste-text-secondary); } +.pending-changes { margin-block: .75rem; color: var(--issste-text-secondary); font-size: .9rem; } +.summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; } +dt { color: var(--issste-text-secondary); font-size: .9rem; } +dd { margin: .4rem 0 0; font-weight: 600; } +.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "history tests" "risks risks"; gap: 1rem; align-items: start; } +mat-card { min-width: 0; background: var(--issste-surface); color: inherit; border-color: var(--issste-border); } +.history-card { grid-area: history; } +.tests-card { grid-area: tests; } +.risks-card { grid-area: risks; } +.history-actions { display: flex; flex-wrap: wrap; gap: .5rem; } +.history-table-scroll { width: 100%; min-width: 0; max-width: 100%; overflow-x: auto; margin-top: .75rem; border: 1px solid var(--issste-border); border-radius: .5rem; } +.history-table-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } +.history-table { width: 100%; min-width: 26rem; border-collapse: separate; border-spacing: 0; text-align: start; } +.history-table th, .history-table td { padding: .7rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); } +.history-table thead th { color: var(--issste-text-secondary); font-size: .9rem; font-weight: 600; } +.history-table thead th:last-child, .history-table td:last-child { width: 9rem; white-space: nowrap; } +.history-table .section-row th { text-align: start; background: color-mix(in srgb, var(--issste-surface), var(--issste-border) 24%); font-weight: 600; } +.history-table .empty-row { color: var(--issste-text-secondary); font-size: .9rem; } +.record-detail { display: block; margin-top: .35rem; color: var(--issste-text-secondary); font-size: .9rem; } +.risks-card mat-card-content { min-width: 0; } +ul { list-style: none; padding: 0; } +li { padding-block: .75rem; border-top: 1px solid var(--issste-border); } +li span { display: block; margin-top: .4rem; } +button { min-height: 44px; color: var(--issste-text); border-color: var(--issste-border); } +@media (max-width: 48rem) { + .detail-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "history" "tests" "risks"; } + .history-table { min-width: 22rem; } +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts new file mode 100644 index 0000000..b783757 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts @@ -0,0 +1,273 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Subject, of, throwError } from 'rxjs'; +import fixtureData from '../fixtures/cacu_seguimiento.json'; +import { seguimientoResponse } from '../cacu-seguimiento.service'; +import { IndicadoresTracking } from '../indicadores-tracking'; +import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; +import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.models'; +import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider'; +import { PacienteDetalleState } from './paciente-detalle.state'; + +const pacientes = seguimientoResponse(fixtureData).items; + +describe('Proveedor de detalle sintético', () => { + it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => { + const provider = TestBed.inject(PacienteDetalleMockProvider); + const id = pacientes[0].id_seudonimo; + provider.obtener(id).subscribe(detalle => expect(detalle?.id_seudonimo).toBe(id)); + for (const desconocido of ['001', '1', id.toLowerCase(), ` ${id}`, 'sin-ficha', 'toString']) { + provider.obtener(desconocido).subscribe(detalle => expect(detalle).toBeNull()); + } + }); + + it('aísla lecturas y conserva nulos, colecciones vacías y propiedades ausentes', () => { + const provider = TestBed.inject(PacienteDetalleMockProvider); + provider.obtener(pacientes[0].id_seudonimo).subscribe(detalle => { + expect(detalle?.procedimientos).toEqual([]); + expect(detalle?.historial?.[0].notas).toBeNull(); + detalle!.historial![0].descripcion = 'mutación local'; + }); + provider.obtener(pacientes[0].id_seudonimo).subscribe(detalle => { + expect(detalle?.historial?.[0].descripcion).not.toBe('mutación local'); + }); + provider.obtener(pacientes[1].id_seudonimo).subscribe(detalle => { + expect(detalle?.historial).toBeNull(); + expect(detalle?.procedimientos?.[0].resultado).toBeNull(); + expect(Object.hasOwn(detalle!.procedimientos![0], 'notas')).toBe(false); + expect(detalle?.pruebas?.[0].fecha).toBeNull(); + }); + }); +}); + +describe('Estado de selección del paciente', () => { + function setup(provider: PacienteDetalleProvider) { + TestBed.configureTestingModule({ providers: [PacienteDetalleState, { provide: PACIENTE_DETALLE_PROVIDER, useValue: provider }] }); + return TestBed.inject(PacienteDetalleState); + } + + it('entrega el seudónimo sin conversión y toma una instantánea independiente de la fila', () => { + const obtener = vi.fn(() => of(null)); + const state = setup({ obtener }); + const paciente = { ...pacientes[0], id_seudonimo: '001', ultimo_vph: { ...pacientes[0].ultimo_vph! }, dias_toma_diagnostico: 0 }; + state.abrir(paciente, fixtureData.corte); + expect(obtener).toHaveBeenCalledExactlyOnceWith('001'); + paciente.ultimo_vph.resultado = 'cambio posterior'; + const estado = state.estado(); + expect(estado.tipo).toBe('no-disponible'); + if (estado.tipo !== 'cerrado') { + expect(estado.resumen.id_seudonimo).toBe('001'); + expect(estado.resumen.vph?.resultado).toBe('NEGATIVO'); + expect(estado.resumen.vph?.genotipo16y18).toBeNull(); + expect(estado.resumen.diasTomaDiagnostico).toBe(0); + } + }); + + it('descarta respuestas tardías de otro paciente y al regresar a la lista', () => { + const a = new Subject(); + const b = new Subject(); + const state = setup({ obtener: id => id === pacientes[0].id_seudonimo ? a : b }); + state.abrir(pacientes[0], fixtureData.corte); + expect(state.estado().tipo).toBe('cargando'); + state.abrir(pacientes[1], fixtureData.corte); + a.next(PACIENTES_DETALLE_SINTETICOS[0]); + expect(state.estado().tipo).toBe('cargando'); + b.next(PACIENTES_DETALLE_SINTETICOS[1]); + let estado = state.estado(); + expect(estado.tipo).toBe('disponible'); + if (estado.tipo === 'disponible') expect(estado.detalle.id_seudonimo).toBe(pacientes[1].id_seudonimo); + state.abrir(pacientes[0], fixtureData.corte); + state.cerrar(); + a.next(PACIENTES_DETALLE_SINTETICOS[0]); + expect(state.estado()).toEqual({ tipo: 'cerrado' }); + }); + + it('no presenta detalles devueltos para un seudónimo distinto', () => { + const state = setup({ obtener: () => of(PACIENTES_DETALLE_SINTETICOS[1]) }); + state.abrir(pacientes[0], fixtureData.corte); + expect(state.estado().tipo).toBe('error'); + expect(state.estado()).not.toHaveProperty('detalle'); + }); + + it('mantiene el resumen ante un error del proveedor, sin exponer datos internos', () => { + const state = setup({ obtener: () => throwError(() => new Error('private')) }); + state.abrir(pacientes[0], fixtureData.corte); + expect(state.estado().tipo).toBe('error'); + expect(JSON.stringify(state.estado())).not.toContain('private'); + state.cerrar(); + expect(state.estado().tipo).toBe('cerrado'); + }); +}); + +describe('Ficha individual desde Seguimiento CaCu', () => { + let fixture: ReturnType>; + let http: HttpTestingController; + let root: HTMLElement; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresTracking); + root = fixture.nativeElement; + http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cacu'); + fixture.componentRef.setInput('domainLabel', 'CaCu'); + fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + http.expectOne(r => r.url === '/cacu/seguimiento').flush(fixtureData); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: { NORMAL: { etiqueta: 'Normal' } } }); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + + function accion(index = 0) { return root.querySelectorAll('tbody button.patient-link')[index]; } + function abrir(index = 0) { accion(index).click(); fixture.detectChanges(); return root.querySelector('app-paciente-detalle')!; } + function volver() { root.querySelector('app-paciente-detalle button')!.click(); fixture.detectChanges(); } + + it('abre por acción nativa accesible, enfoca la ficha y restaura el foco sin HTTP adicional', () => { + const button = accion(); + expect(button.type).toBe('button'); + expect(button.getAttribute('aria-label')).toBe(`Ver ficha del paciente ${pacientes[0].id_seudonimo}`); + const focus = vi.spyOn(button, 'focus'); + const detail = abrir(); + expect(detail.querySelector('h2')?.textContent).toContain(pacientes[0].id_seudonimo); + expect(detail.querySelector('h2')).toBe(document.activeElement); + expect(root.querySelector('form')!.closest('[hidden]')).not.toBeNull(); + expect(detail.textContent).not.toMatch(/Datos de demostración|información adicional sintética|solo existen en memoria|no representan un expediente clínico real/i); + expect(Array.from(detail.querySelectorAll('h3')).map(h => h.textContent)).toEqual([ + 'Historial médico relevante', 'Pruebas y resultados', 'Riesgos y recomendaciones', + ]); + expect(detail.querySelectorAll('.history-card')).toHaveLength(1); + expect(detail.querySelectorAll('.history-card table thead th')).toHaveLength(2); + expect(Array.from(detail.querySelectorAll('.history-card table thead th'), th => th.textContent?.trim())).toEqual(['Registro', 'Fecha']); + expect(Array.from(detail.querySelectorAll('.history-card .section-row th'), th => th.textContent?.trim())).toEqual(['Condiciones', 'Procedimientos']); + expect(detail.querySelector('.history-card button')?.textContent).toContain('Agregar condición'); + expect(Array.from(detail.querySelectorAll('.history-card button'), button => button.textContent?.trim())).toEqual(['Agregar condición', 'Agregar procedimiento']); + expect(detail.querySelector('.history-card')!.compareDocumentPosition(detail.querySelector('.tests-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(detail.querySelector('.tests-card')!.compareDocumentPosition(detail.querySelector('.risks-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(detail.textContent).toContain('Valores ilustrativos · Sin evaluación clínica'); + expect(detail.querySelectorAll('app-paciente-riesgo-tabla tbody tr')).toHaveLength(4); + volver(); + expect(root.querySelector('app-paciente-detalle')).toBeNull(); + expect(root.querySelector('form')!.closest('[hidden]')).toBeNull(); + expect(focus).toHaveBeenCalledWith({ preventScroll: true }); + http.expectNone(() => true); + }); + + it('abre desde otras celdas y devuelve el foco a la fila; mantiene el seudónimo enfocable', () => { + const row = root.querySelectorAll('tbody tr[data-paciente]')[1]; + const control = accion(1); + expect(control.tabIndex).toBe(0); + expect(control.getAttribute('aria-label')).toContain(pacientes[1].id_seudonimo); + row.cells[1].click(); + fixture.detectChanges(); + const estado = fixture.componentInstance.pacienteDetalle.estado(); + expect(estado.tipo).toBe('disponible'); + if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo); + volver(); + expect(row).toBe(document.activeElement); + http.expectNone(() => true); + expect(row.isConnected).toBe(true); + }); + + it('conserva filtros aplicados, borrador, página, filas y desplazamiento de tabla al volver', () => { + const component = fixture.componentInstance; + component.draft = { corte: '2026-09-30', meses: 6, estatus: 'VIGILANCIA', page: 1, page_size: 10 }; + component.apply(); + const response = { ...fixtureData, ventana: { ...fixtureData.ventana, meses: 6 }, filtros: { estatus: 'VIGILANCIA' } }; + http.expectOne(r => r.url === '/cacu/seguimiento').flush(response); + component.navigate(2); + http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...response, paginacion: { ...fixtureData.paginacion, page: 2 } }); + fixture.detectChanges(); + component.draft.meses = 12; + const table = root.querySelector('.tracking-table')!; + table.scrollLeft = 200; + const row = root.querySelector('tbody tr'); + abrir(); volver(); + expect(component.draft.meses).toBe(12); + expect(component.draft.estatus).toBe('VIGILANCIA'); + expect(component.data?.paginacion.page).toBe(2); + expect(root.querySelector('tbody tr')).toBe(row); + expect(root.querySelector('.tracking-table')).toBe(table); + expect(table.scrollLeft).toBe(200); + http.expectNone(() => true); + component.navigate(3); + const request = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(request.request.params.get('meses')).toBe('6'); + expect(request.request.params.get('estatus')).toBe('VIGILANCIA'); + expect(request.request.params.get('page')).toBe('3'); + request.flush({ ...response, paginacion: { ...fixtureData.paginacion, page: 3 } }); + }); + + it('muestra ausencia de ficha sin asignar a otro paciente los antecedentes anteriores', () => { + expect(abrir().textContent).toContain('Antecedente de tamizaje cervical'); + const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent; + volver(); + const detail = abrir(2); + expect(detail.textContent).toContain(pacientes[2].id_seudonimo); + expect(detail.textContent).toContain('Información no disponible'); + expect((detail.textContent.match(/Información no disponible/g) ?? [])).toHaveLength(3); + expect(detail.textContent).not.toContain('Antecedente de tamizaje cervical'); + expect(detail.textContent).not.toContain('Colposcopia (demostración)'); + expect(detail.textContent).toContain('Normal'); // Received study is still available. + expect(detail.textContent).not.toContain('ficha sintética'); + expect(detail.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa); + expect(detail.querySelectorAll('app-paciente-riesgo-tabla [aria-selected]')).toHaveLength(0); + http.expectNone(() => true); + }); + + it('organiza condiciones y procedimientos en una sola tabla y conserva los datos iniciales', () => { + let detail = abrir(); + const historial = detail.querySelector('.history-card table')!; + expect(historial.querySelectorAll('.section-row')).toHaveLength(2); + expect(Array.from(historial.querySelectorAll('tbody tr'), row => row.textContent?.trim()).join(' ')).toContain('Antecedente de tamizaje cervical (demostración)'); + expect(Array.from(historial.querySelectorAll('tbody tr'), row => row.textContent?.trim()).join(' ')).toContain('2025-06-12'); + expect(historial.querySelectorAll('[data-registro-temporal]')).toHaveLength(0); + volver(); + + detail = abrir(1); + const rows = Array.from(detail.querySelectorAll('.history-card table tbody tr')); + const procedure = rows.find(row => row.textContent?.includes('Colposcopia (demostración)'))!; + expect(procedure.textContent).toContain('2026-06-10'); + expect(procedure.previousElementSibling?.querySelector('th')?.textContent).toBe('Procedimientos'); + expect(detail.querySelectorAll('.history-card')).toHaveLength(1); + http.expectNone(() => true); + }); + + it('distingue fuentes, nulos, falsos, ceros y listas sin registros sin inferir condiciones', () => { + let detail = abrir(); + expect(detail.textContent).toContain('Últimos resultados'); + expect(detail.textContent).toContain('Pruebas adicionales'); + expect(detail.textContent).toContain('Genotipo 16/18: No disponible'); + expect(detail.textContent).toContain('Sin registros'); + volver(); + detail = abrir(1); + expect(detail.textContent).toContain('Información no disponible'); + expect(detail.textContent).toContain('Resultado: No disponible'); + expect(detail.textContent).not.toContain('Antecedente de tamizaje cervical'); + volver(); + detail = abrir(5); + expect(detail.textContent).toContain('Genotipo 16/18: No detectado'); + expect(detail.textContent).toContain('Insatisfactoria'); + expect(detail.textContent).not.toMatch(/undefined|null/); + http.expectNone(() => true); + }); + + it('conserva la selección al cambiar de pestaña y la limpia al cambiar de dominio', () => { + abrir(); + fixture.componentRef.setInput('active', false); fixture.detectChanges(); + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + expect(root.querySelector('app-paciente-detalle h2')?.textContent).toContain(pacientes[0].id_seudonimo); + fixture.componentRef.setInput('dominio', 'tea'); fixture.detectChanges(); + expect(root.querySelector('app-paciente-detalle')).toBeNull(); + expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado'); + expect(root.querySelector('tbody button')).toBeNull(); + http.expectNone(() => true); + }); + + it('no selecciona filas ajenas a la respuesta vigente', () => { + fixture.componentInstance.abrirPaciente({ ...pacientes[0] }, { currentTarget: accion() } as unknown as Event); + expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado'); + http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts new file mode 100644 index 0000000..e223be2 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts @@ -0,0 +1,71 @@ +import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Subject, catchError, defer, map, of, switchMap } from 'rxjs'; +import { SeguimientoPaciente } from '../cacu-seguimiento.models'; +import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models'; +import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider'; +import { AltaRegistroTemporal } from './paciente-registro.models'; +import { PacienteRegistrosSesion } from './paciente-registros-sesion'; + +/** Selección por instancia de Seguimiento; las altas temporales viven aparte en la sesión Angular. */ +@Injectable() +export class PacienteDetalleState { + private readonly provider = inject(PACIENTE_DETALLE_PROVIDER); + private readonly sesion = inject(PacienteRegistrosSesion); + private readonly seleccion = new Subject(); + private readonly actual = signal({ tipo: 'cerrado' }); + readonly estado = this.actual.asReadonly(); + readonly registrosTemporales = computed(() => { + const estado = this.actual(); + return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo); + }); + + constructor() { + this.seleccion.pipe( + switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe( + map(detalle => { + if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) { + throw new Error('Detalle incompatible con la selección'); + } + return detalle + ? { tipo: 'disponible', resumen, detalle } as const + : { tipo: 'no-disponible', resumen } as const; + }), + catchError(() => of({ tipo: 'error', resumen } as const)), + ) : of({ tipo: 'cerrado' } as const)), + takeUntilDestroyed(inject(DestroyRef)), + ).subscribe(estado => this.actual.set(estado)); + } + + abrir(paciente: SeguimientoPaciente, corte: string) { + const resumen: PacienteResumen = { + id_seudonimo: paciente.id_seudonimo, + grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad, + estatus: paciente.estatus.etiqueta, + corte, + origen: 'seguimiento-demostracion', + citologia: paciente.ultima_citologia ? { + fecha: paciente.ultima_citologia.fecha, + resultado: paciente.ultima_citologia.bethesda, + calidad: paciente.ultima_citologia.calidad, + } : null, + vph: paciente.ultimo_vph ? { + fecha: paciente.ultimo_vph.fecha, + resultado: paciente.ultimo_vph.resultado, + genotipo16y18: paciente.ultimo_vph.genotipo_16_18, + } : null, + diasTomaDiagnostico: paciente.dias_toma_diagnostico, + prioridad: paciente.prioridad?.etiqueta ?? null, + }; + this.actual.set({ tipo: 'cargando', resumen }); + this.seleccion.next(resumen); + } + + cerrar() { this.seleccion.next(null); } + + agregarRegistro(alta: AltaRegistroTemporal) { + const estado = this.actual(); + if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false; + return this.sesion.agregar(alta.id_seudonimo, alta.registro); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts new file mode 100644 index 0000000..e3d2a75 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts @@ -0,0 +1,53 @@ +import { AfterViewInit, Component, DestroyRef, ElementRef, inject, Input, OnDestroy, ViewChild, output } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatIconModule } from '@angular/material/icon'; +import { PacienteDetalleEstado } from './paciente-detalle.models'; +import { PacienteRegistroDialog } from './paciente-registro-dialog'; +import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; +import { etiquetaRegistro, etiquetaResultado } from './paciente-registros-sesion'; +import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; + +@Component({ + selector: 'app-paciente-detalle', + imports: [MatButtonModule, MatCardModule, MatDialogModule, MatIconModule, PacienteRiesgoTabla], + templateUrl: './paciente-detalle.html', + styleUrl: './paciente-detalle.scss', +}) +export class PacienteDetalleComponent implements AfterViewInit, OnDestroy { + @Input({ required: true }) estado: PacienteDetalleEstado = { tipo: 'cerrado' }; + @Input() categorias: Record = {}; + @Input() registrosTemporales: readonly RegistroTemporal[] = []; + readonly volver = output(); + readonly registroAgregado = output(); + readonly etiquetaRegistro = etiquetaRegistro; + readonly etiquetaResultado = etiquetaResultado; + private readonly dialog = inject(MatDialog); + private readonly destroy = inject(DestroyRef); + private dialogoActivo?: MatDialogRef; + @ViewChild('titulo') private titulo?: ElementRef; + ngAfterViewInit() { this.titulo?.nativeElement.focus(); } + ngOnDestroy() { this.dialogoActivo?.close(); } + + temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); } + + abrirRegistro(tipo: TipoRegistroTemporal) { + if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return; + const id_seudonimo = this.estado.resumen.id_seudonimo; + const ref = this.dialog.open(PacienteRegistroDialog, { + data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh', + autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false, + }); + this.dialogoActivo = ref; + ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => { + this.dialogoActivo = undefined; + if (registro) this.registroAgregado.emit({ id_seudonimo, registro }); + }); + } + etiquetaCitologia(resultado: string | null, calidad: string | null) { + if (resultado !== null) return this.categorias[resultado]?.etiqueta ?? resultado; + return calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte'; + } +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html new file mode 100644 index 0000000..f4f82cc --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html @@ -0,0 +1,36 @@ +

    {{ titulo }}

    +
    + +

    Paciente {{ data.id_seudonimo }}

    +
    + + {{ etiquetaTipo }} + + @for (opcion of tipos; track opcion.valor) { + {{ opcion.etiqueta }} + } + + @if (form.controls.seleccion.hasError('required')) { Selecciona una opción. } + @else { Selecciona una opción válida. } + + @if (data.tipo === 'resultado') { + + Resultado + + @for (opcion of resultados; track opcion.valor) { + {{ opcion.etiqueta }} + } + + Selecciona primero el tipo de estudio. + @if (form.controls.resultado.hasError('required')) { Selecciona un resultado para este estudio. } + @else { El resultado no corresponde al estudio seleccionado. } + + } + +
    +
    + + + + +
    diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.scss b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.scss new file mode 100644 index 0000000..40f0694 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.scss @@ -0,0 +1,5 @@ +:host { display: block; color: var(--issste-text); } +.fields { display: grid; gap: 1.25rem; margin-block: 1.5rem .75rem; } +mat-form-field { width: 100%; min-width: 0; } +button { min-height: 44px; } +mat-dialog-actions { gap: .5rem; flex-wrap: wrap; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts new file mode 100644 index 0000000..0e5f813 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts @@ -0,0 +1,67 @@ +import { Component, DestroyRef, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; +import { FechaCompuesta } from './fecha-compuesta'; +import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO, esOpcion, opciones } from './paciente-registro.catalogos'; +import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; +import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation'; + +export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; } + +const opcionValida = (catalogo: Readonly>): ValidatorFn => + control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true }; +const fechaValida: ValidatorFn = control => !control.value || esFechaReal(control.value) ? null : { fecha: true }; + +@Component({ + selector: 'app-paciente-registro-dialog', + imports: [ReactiveFormsModule, MatDialogModule, MatButtonModule, MatFormFieldModule, MatSelectModule, FechaCompuesta], + templateUrl: './paciente-registro-dialog.html', + styleUrl: './paciente-registro-dialog.scss', +}) +export class PacienteRegistroDialog { + readonly data = inject(MAT_DIALOG_DATA); + private readonly dialogRef = inject>(MatDialogRef); + readonly titulo = this.data.tipo === 'condicion' ? 'Agregar condición' + : this.data.tipo === 'procedimiento' ? 'Agregar procedimiento' : 'Agregar resultado'; + readonly etiquetaTipo = this.data.tipo === 'condicion' ? 'Tipo de condición' + : this.data.tipo === 'procedimiento' ? 'Tipo de procedimiento' : 'Tipo de estudio'; + readonly etiquetaFecha = this.data.tipo === 'condicion' ? 'Fecha de inicio' + : this.data.tipo === 'procedimiento' ? 'Fecha del procedimiento' : 'Fecha del estudio'; + private readonly catalogo = this.data.tipo === 'condicion' ? CONDICIONES_DEMO + : this.data.tipo === 'procedimiento' ? PROCEDIMIENTOS_DEMO : ESTUDIOS_DEMO; + readonly tipos = opciones(this.catalogo); + resultados: ReturnType = []; + readonly form = new FormGroup({ + seleccion: new FormControl('', { nonNullable: true, validators: [Validators.required, opcionValida(this.catalogo)] }), + fecha: new FormControl('', { nonNullable: true, validators: [Validators.required, fechaValida] }), + resultado: new FormControl({ value: '', disabled: true }, { nonNullable: true }), + }); + private enviado = false; + + constructor() { + if (this.data.tipo === 'resultado') { + this.form.controls.seleccion.valueChanges.pipe(takeUntilDestroyed(inject(DestroyRef))).subscribe(estudio => { + const catalogo = esOpcion(ESTUDIOS_DEMO, estudio) ? RESULTADOS_DEMO[estudio] : null; + this.resultados = catalogo ? opciones(catalogo) : []; + const resultado = this.form.controls.resultado; + resultado.reset(''); + resultado.setValidators([Validators.required, opcionValida(catalogo ?? {})]); + if (catalogo) resultado.enable(); else resultado.disable(); + }); + } + } + + agregar() { + this.form.markAllAsTouched(); + if (this.enviado || this.form.invalid) return; + const { seleccion, fecha, resultado } = this.form.getRawValue(); + const registro = crearRegistroTemporal(this.data.tipo, seleccion, fecha, resultado); + if (!registro) return; + this.enviado = true; + this.dialogRef.close(registro); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts new file mode 100644 index 0000000..94fa339 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -0,0 +1,289 @@ +import { EnvironmentInjector, createEnvironmentInjector } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; +import { MatSelectHarness } from '@angular/material/select/testing'; +import { MatInputHarness } from '@angular/material/input/testing'; +import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing'; +import { MatDialog } from '@angular/material/dialog'; +import { firstValueFrom } from 'rxjs'; +import fixtureData from '../fixtures/cacu_seguimiento.json'; +import { seguimientoResponse } from '../cacu-seguimiento.service'; +import { IndicadoresTracking } from '../indicadores-tracking'; +import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; +import { PacienteDetalleState } from './paciente-detalle.state'; +import { PacienteRegistroDialog } from './paciente-registro-dialog'; +import { PacienteRegistrosSesion } from './paciente-registros-sesion'; +import { TipoRegistroTemporal } from './paciente-registro.models'; + +const pacientes = seguimientoResponse(fixtureData).items; +const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [ + { tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' }, + { tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' }, + { tipo: 'resultado', texto: 'Agregar resultado', opcion: 'VPH', resultado: 'VPH no detectado' }, +]; + +describe('Altas de demostración desde la ficha de Seguimiento', () => { + let fixture: ReturnType>; + let root: HTMLElement; + let http: HttpTestingController; + let dialog: MatDialog; + + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + dialog = TestBed.inject(MatDialog); + montarTracking(); + }); + + function montarTracking() { + fixture = TestBed.createComponent(IndicadoresTracking); + root = fixture.nativeElement; + fixture.componentRef.setInput('dominio', 'cacu'); + fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + http.expectOne(r => r.url === '/cacu/seguimiento' && r.method === 'GET').flush(fixtureData); + http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/metadatos' && r.method === 'GET').flush({}); + fixture.detectChanges(); + } + + afterEach(() => { + dialog.closeAll(); + fixture.destroy(); + http.verify(); + }); + + function abrir(index = 0) { + root.querySelectorAll('tbody button')[index].click(); + fixture.detectChanges(); + } + function volver() { + root.querySelector('app-paciente-detalle > button')!.click(); + fixture.detectChanges(); + } + function boton(texto: string) { + return Array.from(root.querySelectorAll('app-paciente-detalle button')).find(b => b.textContent?.trim() === texto)!; + } + async function abrirDialogo(texto: string) { + const origen = boton(texto); + origen.focus(); origen.click(); + expect(dialog.openDialogs).toHaveLength(1); + const ref = dialog.openDialogs[0]; + const abierto = firstValueFrom(ref.afterOpened()); + fixture.detectChanges(); + await abierto; + await fixture.whenStable(); + fixture.detectChanges(); + expect(document.querySelector('[role="dialog"]')).not.toBeNull(); + expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-labelledby')).toBeTruthy(); + expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-describedby')).toBeNull(); + expect(document.querySelector('[role="dialog"]')?.contains(document.activeElement)).toBe(true); + return { ref, origen }; + } + async function confirmar() { + const ref = dialog.openDialogs[0]; + const cerrado = firstValueFrom(ref.afterClosed()); + document.querySelector('app-paciente-registro-dialog [type="submit"]')!.click(); + await cerrado; + fixture.detectChanges(); await fixture.whenStable(); + } + + async function capturarFecha(dia: string, mes: string, anio: string) { + const loader = TestbedHarnessEnvironment.documentRootLoader(fixture); + for (const [parte, valor] of [['dia', dia], ['mes', mes], ['anio', anio]]) { + const input = await loader.getHarness(MatInputHarness.with({ selector: `[data-fecha="${parte}"]` })); + await input.setValue(valor); + } + } + + for (const accion of acciones) { + it(`abre, valida y confirma «${accion.texto}» sin HTTP y restaura el foco`, async () => { + const inicial = JSON.stringify(PACIENTES_DETALLE_SINTETICOS); + const resumen = JSON.stringify(fixture.componentInstance.data); + abrir(); + const { origen } = await abrirDialogo(accion.texto); + const loader = TestbedHarnessEnvironment.documentRootLoader(fixture); + const tipo = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="seleccion"]' })); + await tipo.clickOptions({ text: accion.opcion }); + if (accion.resultado) { + const resultado = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="resultado"]' })); + await resultado.clickOptions({ text: accion.resultado }); + } + await capturarFecha('26', 'Octubre', '2026'); + expect(document.querySelector('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(false); + await confirmar(); + const registro = root.querySelector(`[data-registro-temporal="${accion.tipo}"]`)!; + expect(registro.textContent).toContain(accion.opcion); + expect(registro.textContent).toContain('2026-10-26'); + expect(root.querySelectorAll(`[data-registro-temporal="${accion.tipo}"]`)).toHaveLength(1); + if (accion.tipo !== 'resultado') { + expect(registro.closest('.history-card table')).not.toBeNull(); + let encabezado = registro.previousElementSibling; + while (encabezado && !encabezado.classList.contains('section-row')) encabezado = encabezado.previousElementSibling; + expect(encabezado?.textContent?.trim()).toBe(accion.tipo === 'condicion' ? 'Condiciones' : 'Procedimientos'); + } else { + expect(registro.closest('.tests-card')).not.toBeNull(); + } + expect(root.textContent).toContain('Cambios sin guardar'); + expect(document.activeElement).toBe(origen); + expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial); + expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen); + const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0]; + expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo); + expect(almacenado.origen).toBe('sesion-demostracion'); + expect(almacenado.fecha).toBe('2026-10-26'); + http.expectNone(() => true); + }); + + it(`cancela «${accion.texto}» sin guardar el borrador`, async () => { + abrir(); + const { ref, origen } = await abrirDialogo(accion.texto); + (ref.componentInstance as PacienteRegistroDialog).form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia'); + await capturarFecha('26', 'Octubre', '2026'); + const cerrado = firstValueFrom(ref.afterClosed()); + document.querySelector('app-paciente-registro-dialog button[type="button"]')!.click(); + expect(await cerrado).toBeUndefined(); + fixture.detectChanges(); await fixture.whenStable(); + expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]); + expect(root.querySelector('[data-registro-temporal]')).toBeNull(); + expect(document.activeElement).toBe(origen); + await abrirDialogo(accion.texto); + expect((dialog.openDialogs[0].componentInstance as PacienteRegistroDialog).form.controls.seleccion.value).toBe(''); + expect(Array.from(document.querySelectorAll('app-fecha-compuesta input')).every(input => input.value === '')).toBe(true); + http.expectNone(() => true); + }); + + it(`bloquea fechas incompletas e imposibles en «${accion.texto}» y admite corregirlas`, async () => { + abrir(); + const { ref } = await abrirDialogo(accion.texto); + const component = ref.componentInstance as PacienteRegistroDialog; + component.form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia'); + if (accion.tipo === 'resultado') component.form.controls.resultado.setValue('negativo'); + for (const partes of [['29', 'Febrero', ''], ['31', 'Abril', '2024'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2025']]) { + await capturarFecha(partes[0], partes[1], partes[2]); + expect(component.form.controls.fecha.value).toBe(''); + expect(document.querySelector('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(true); + component.agregar(); + expect(dialog.openDialogs).toHaveLength(1); + expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]); + } + await capturarFecha('29', '2', '2024'); + expect(component.form.controls.fecha.value).toBe('2024-02-29'); + await confirmar(); + expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()[0].fecha).toBe('2024-02-29'); + http.expectNone(() => true); + }); + + it(`Escape cierra las sugerencias de «${accion.texto}» antes de permitir cancelar el diálogo`, async () => { + abrir(); + const { ref, origen } = await abrirDialogo(accion.texto); + const mes = await TestbedHarnessEnvironment.documentRootLoader(fixture).getHarness( + MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' })); + await mes.enterText('ma'); + expect(await mes.isOpen()).toBe(true); + const input = document.querySelector('[data-fecha="mes"]')!; + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true })); + fixture.detectChanges(); await fixture.whenStable(); + expect(await mes.isOpen()).toBe(false); + expect(dialog.openDialogs).toHaveLength(1); + expect(document.activeElement).toBe(input); + expect(input.value).toBe('ma'); + const cerrado = firstValueFrom(ref.afterClosed()); + // Con las sugerencias cerradas, Escape conserva la cancelación habitual del modal. + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true })); + expect(await cerrado).toBeUndefined(); + fixture.detectChanges(); await fixture.whenStable(); + expect(document.activeElement).toBe(origen); + expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]); + http.expectNone(() => true); + }); + } + + it('permite Escape y cierra el diálogo si se abandona la ficha sin confirmar', async () => { + abrir(); + const { ref } = await abrirDialogo('Agregar condición'); + const cerrado = firstValueFrom(ref.afterClosed()); + document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true })); + expect(await cerrado).toBeUndefined(); + fixture.detectChanges(); + const otro = await abrirDialogo('Agregar resultado'); + const destruido = firstValueFrom(otro.ref.afterClosed()); + volver(); + expect(await destruido).toBeUndefined(); + expect(TestBed.inject(PacienteRegistrosSesion).paraPaciente(pacientes[0].id_seudonimo)).toEqual([]); + expect(root.querySelector('app-paciente-detalle')).toBeNull(); + http.expectNone(() => true); + }); + + it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => { + abrir(2); + const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent; + expect(root.querySelectorAll('app-paciente-riesgo-tabla thead th')).toHaveLength(6); + expect(root.textContent).toContain('Información no disponible'); + for (const tipo of acciones) { + const { ref } = await abrirDialogo(tipo.texto); + const form = (ref.componentInstance as PacienteRegistroDialog).form; + form.patchValue({ seleccion: tipo.tipo === 'condicion' ? 'lesion_cervical' : tipo.tipo === 'procedimiento' ? 'escision_cervical' : 'histologia', fecha: '2026-10-26' }); + if (tipo.tipo === 'resultado') form.controls.resultado.setValue('nic1'); + fixture.detectChanges(); + await confirmar(); + } + expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3); + expect(root.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa); + expect(root.textContent).toContain('Recomendaciones no disponibles'); + volver(); abrir(0); + expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0); + volver(); abrir(2); + expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3); + volver(); + fixture.destroy(); // La navegación puede desmontar Seguimiento; la aplicación sigue viva. + montarTracking(); abrir(2); + expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3); + http.expectNone(() => true); + }); + + it('no sustituye la última citología o VPH ni modifica el resumen, prioridades o datos recibidos', async () => { + const inicial = structuredClone(fixture.componentInstance.data); + abrir(); + const resumen = structuredClone(fixture.componentInstance.pacienteDetalle.estado()); + const { ref } = await abrirDialogo('Agregar resultado'); + const form = (ref.componentInstance as PacienteRegistroDialog).form; + form.patchValue({ seleccion: 'vph', fecha: '2026-10-26' }); + form.controls.resultado.setValue('positivo_16_18'); + fixture.detectChanges(); await confirmar(); + expect(fixture.componentInstance.pacienteDetalle.estado()).toEqual(resumen); + expect(fixture.componentInstance.data).toEqual(inicial); + expect(root.textContent).toContain('Último resultado de VPH'); + expect(root.textContent).toContain('NEGATIVO'); + expect(root.textContent).toContain('VPH 16/18 detectado'); + expect(root.textContent).toContain('Valores ilustrativos · Sin evaluación clínica'); + http.expectNone(() => true); + }); +}); + +describe('Vida de la selección y de la memoria de sesión', () => { + it('sobrevive a nuevas instancias de selección y rechaza altas de una ficha anterior', () => { + const parent = TestBed.inject(EnvironmentInjector); + const crear = () => createEnvironmentInjector([PacienteDetalleState], parent); + const primero = crear(); + const segundo = crear(); + try { + const a = primero.get(PacienteDetalleState); + const b = segundo.get(PacienteDetalleState); + a.abrir(pacientes[0], fixtureData.corte); + expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true); + a.cerrar(); + expect(a.registrosTemporales()).toEqual([]); + primero.destroy(); + b.abrir(pacientes[0], fixtureData.corte); + expect(b.registrosTemporales()).toHaveLength(1); + b.abrir(pacientes[1], fixtureData.corte); + expect(b.registrosTemporales()).toEqual([]); + expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false); + } finally { + if (!primero.destroyed) primero.destroy(); + segundo.destroy(); + } + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.catalogos.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.catalogos.ts new file mode 100644 index 0000000..48f1329 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.catalogos.ts @@ -0,0 +1,53 @@ +/** Opciones exclusivamente sintéticas de demostración; no son una clasificación clínica validada. */ +export const CONDICIONES_DEMO = { + embarazo: 'Embarazo', + lesion_cervical: 'Lesión cervical', + antecedente_cacu: 'Antecedente de cáncer cervicouterino', + inmunosupresion: 'Inmunosupresión', +} as const; + +export const PROCEDIMIENTOS_DEMO = { + colposcopia: 'Colposcopia', + escision_cervical: 'Escisión cervical', + ablacion_cervical: 'Ablación cervical', + histerectomia: 'Histerectomía', +} as const; + +export const ESTUDIOS_DEMO = { + vph: 'VPH', + citologia: 'Citología cervical', + histologia: 'Histología cervical', +} as const; + +export const RESULTADOS_DEMO = { + vph: { + negativo: 'VPH no detectado', + positivo_16_18: 'VPH 16/18 detectado', + positivo_otro: 'Otro VPH de alto riesgo detectado', + }, + citologia: { + negativa: 'Negativa para lesión intraepitelial', + asc_us: 'ASC-US', + lsil: 'Lesión intraepitelial de bajo grado (LSIL)', + hsil: 'Lesión intraepitelial de alto grado (HSIL)', + insatisfactoria: 'Muestra insatisfactoria', + }, + histologia: { + sin_lesion: 'Sin lesión en la muestra', + nic1: 'NIC 1', + nic2: 'NIC 2', + nic3: 'NIC 3', + }, +} as const; + +export type TipoCondicionDemo = keyof typeof CONDICIONES_DEMO; +export type TipoProcedimientoDemo = keyof typeof PROCEDIMIENTOS_DEMO; +export type TipoEstudioDemo = keyof typeof ESTUDIOS_DEMO; + +export function esOpcion(catalogo: T, valor: unknown): valor is Extract { + return typeof valor === 'string' && Object.hasOwn(catalogo, valor); +} + +export function opciones(catalogo: Readonly>) { + return Object.entries(catalogo).map(([valor, etiqueta]) => ({ valor, etiqueta })); +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts new file mode 100644 index 0000000..0f72c23 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts @@ -0,0 +1,24 @@ +import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos'; + +type ResultadoDemo = { + [E in TipoEstudioDemo]: { estudio: E; resultado: keyof typeof RESULTADOS_DEMO[E] } +}[TipoEstudioDemo]; + +export type NuevoRegistroTemporal = + | { tipo: 'condicion'; condicion: TipoCondicionDemo; fecha: string } + | { tipo: 'procedimiento'; procedimiento: TipoProcedimientoDemo; fecha: string } + | ({ tipo: 'resultado'; fecha: string } & ResultadoDemo); + +export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo']; + +/** Independiente del resumen recibido y del historial inicial del proveedor. */ +export type RegistroTemporal = Readonly; + +export interface AltaRegistroTemporal { + id_seudonimo: string; + registro: NuevoRegistroTemporal; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts new file mode 100644 index 0000000..8fb331b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts @@ -0,0 +1,176 @@ +import { TestBed } from '@angular/core/testing'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { ESTUDIOS_DEMO, RESULTADOS_DEMO } from './paciente-registro.catalogos'; +import { PacienteRegistroDialog } from './paciente-registro-dialog'; +import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; +import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation'; +import { PacienteRegistrosSesion } from './paciente-registros-sesion'; + +describe('Fecha de calendario de registros temporales', () => { + it('acepta días reales, incluyendo años bisiestos y límites de año', () => { + for (const fecha of ['2024-02-29', '2000-02-29', '2026-04-30', '0001-01-01', '9999-12-31']) { + expect(esFechaReal(fecha), fecha).toBe(true); + } + }); + + it('rechaza fechas imposibles, normalizaciones y cadenas arbitrarias', () => { + for (const fecha of ['', 'ayer', '2026-02-29', '1900-02-29', '2026-04-31', '2026-00-01', '2026-13-01', + '2026-01-00', '0000-01-01', '2026-1-1', '26/10/2026', ' 2026-10-26', '2026-10-26T00:00:00Z', null, new Date()]) { + expect(esFechaReal(fecha), String(fecha)).toBe(false); + } + }); +}); + +const casos: { tipo: TipoRegistroTemporal; seleccion: string; registro: NuevoRegistroTemporal }[] = [ + { tipo: 'condicion', seleccion: 'embarazo', registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } }, + { tipo: 'procedimiento', seleccion: 'colposcopia', registro: { tipo: 'procedimiento', procedimiento: 'colposcopia', fecha: '2026-10-26' } }, + { tipo: 'resultado', seleccion: 'vph', registro: { tipo: 'resultado', estudio: 'vph', resultado: 'negativo', fecha: '2026-10-26' } }, +]; + +describe.each(casos)('Formulario de $tipo', caso => { + let fixture: ReturnType>; + let component: PacienteRegistroDialog; + let cerrar: ReturnType; + + beforeEach(() => { + cerrar = vi.fn(); + TestBed.configureTestingModule({ providers: [ + { provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } }, + { provide: MatDialogRef, useValue: { close: cerrar } }, + ] }); + fixture = TestBed.createComponent(PacienteRegistroDialog); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('muestra destino, campos obligatorios y confirmación deshabilitada sin texto técnico', () => { + const root: HTMLElement = fixture.nativeElement; + expect(root.textContent).not.toMatch(/demostración|sintético|persistencia|solo existe en esta sesión/i); + expect(root.textContent).toContain('Paciente 001'); + expect(root.querySelector('[type="submit"]')!.disabled).toBe(true); + component.agregar(); + fixture.detectChanges(); + expect(root.textContent).toContain('Selecciona una opción'); + expect(root.textContent).toContain('Ingresa una fecha válida'); + expect(cerrar).not.toHaveBeenCalled(); + }); + + it('rechaza opciones ajenas al catálogo y fechas inválidas antes de cerrar', () => { + component.form.patchValue({ seleccion: 'toString', fecha: '2026-02-30' }); + component.agregar(); + fixture.detectChanges(); + expect(component.form.invalid).toBe(true); + expect(fixture.nativeElement.textContent).toContain('Ingresa una fecha real'); + expect(cerrar).not.toHaveBeenCalled(); + }); + + it('confirma exactamente una vez con un registro válido y tipado', () => { + component.form.patchValue({ seleccion: caso.seleccion, fecha: caso.registro.fecha }); + if (caso.registro.tipo === 'resultado') component.form.controls.resultado.setValue(caso.registro.resultado); + fixture.detectChanges(); + expect(component.form.valid).toBe(true); + expect(fixture.nativeElement.querySelector('[type="submit"]').disabled).toBe(false); + fixture.nativeElement.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); + component.agregar(); + expect(cerrar).toHaveBeenCalledExactlyOnceWith(caso.registro); + }); +}); + +describe('Resultados dependientes del estudio', () => { + let component: PacienteRegistroDialog; + let cerrar: ReturnType; + beforeEach(() => { + cerrar = vi.fn(); + TestBed.configureTestingModule({ providers: [ + { provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } }, + { provide: MatDialogRef, useValue: { close: cerrar } }, + ] }); + const fixture = TestBed.createComponent(PacienteRegistroDialog); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('limpia el resultado al cambiar de estudio y exige elegir uno compatible', () => { + expect(component.form.controls.resultado.disabled).toBe(true); + component.form.patchValue({ seleccion: 'vph', fecha: '2026-10-26' }); + component.form.controls.resultado.setValue('positivo_16_18'); + expect(component.form.valid).toBe(true); + component.form.controls.seleccion.setValue('citologia'); + expect(component.form.controls.resultado.value).toBe(''); + expect(component.form.invalid).toBe(true); + expect(component.resultados.map(r => r.valor)).not.toContain('positivo_16_18'); + component.form.controls.resultado.setValue('positivo_16_18'); + component.agregar(); + expect(cerrar).not.toHaveBeenCalled(); + component.form.controls.resultado.setValue('asc_us'); + expect(component.form.valid).toBe(true); + component.form.controls.seleccion.setValue(''); + expect(component.form.controls.resultado.value).toBe(''); + expect(component.form.controls.resultado.disabled).toBe(true); + expect(component.resultados).toEqual([]); + expect(component.form.invalid).toBe(true); + }); + + it('admite cada pareja de los tres catálogos y rechaza combinaciones cruzadas', () => { + for (const estudio of Object.keys(ESTUDIOS_DEMO) as (keyof typeof ESTUDIOS_DEMO)[]) { + component.form.patchValue({ seleccion: estudio, fecha: '2026-10-26' }); + expect(component.resultados.map(r => r.valor)).toEqual(Object.keys(RESULTADOS_DEMO[estudio])); + for (const resultado of Object.keys(RESULTADOS_DEMO[estudio])) { + component.form.controls.resultado.setValue(resultado); + expect(component.form.valid).toBe(true); + expect(crearRegistroTemporal('resultado', estudio, '2026-10-26', resultado)).toEqual({ tipo: 'resultado', estudio, fecha: '2026-10-26', resultado }); + } + } + expect(crearRegistroTemporal('resultado', 'histologia', '2026-10-26', 'positivo_16_18')).toBeNull(); + expect(crearRegistroTemporal('resultado', 'vph', '2026-10-26', 'nic3')).toBeNull(); + expect(crearRegistroTemporal('resultado', 'toString', '2026-10-26', 'toString')).toBeNull(); + }); +}); + +describe('Memoria de registros temporales', () => { + it('asocia las tres altas al seudónimo exacto sin convertir ni mezclar identidades', () => { + const sesion = TestBed.inject(PacienteRegistrosSesion); + for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true); + expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']); + expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true); + for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]); + sesion.agregar('toString', casos[0].registro); + expect(sesion.paraPaciente('toString')).toHaveLength(1); + expect(sesion.paraPaciente('001')).toHaveLength(3); + }); + + it('conserva instantáneas inmutables y no retiene el objeto de entrada', () => { + const sesion = TestBed.inject(PacienteRegistrosSesion); + const nuevo = { ...casos[0].registro }; + const vacio = sesion.paraPaciente('A'); + sesion.agregar('A', nuevo); + const primera = sesion.paraPaciente('A'); + nuevo.fecha = '2000-01-01'; + sesion.agregar('A', casos[1].registro); + expect(vacio).toEqual([]); + expect(primera).toHaveLength(1); + expect(primera[0].fecha).toBe('2026-10-26'); + expect(Object.isFrozen(primera)).toBe(true); + expect(Object.isFrozen(primera[0])).toBe(true); + expect(new Set(sesion.paraPaciente('A').map(r => r.id)).size).toBe(2); + }); + + it('defiende la escritura en memoria de fechas y combinaciones inválidas', () => { + const sesion = TestBed.inject(PacienteRegistrosSesion); + expect(sesion.agregar('A', { ...casos[0].registro, fecha: 'ayer' })).toBe(false); + expect(sesion.agregar('', casos[0].registro)).toBe(false); + expect(sesion.agregar('A', { tipo: 'resultado', estudio: 'vph', resultado: 'nic3', fecha: '2026-10-26' } as unknown as NuevoRegistroTemporal)).toBe(false); + expect(sesion.paraPaciente('A')).toEqual([]); + }); + + it('una nueva instancia de aplicación empieza vacía, sin leer ni escribir almacenamiento web', () => { + const storage = [vi.spyOn(Storage.prototype, 'setItem'), vi.spyOn(Storage.prototype, 'getItem')]; + const anterior = TestBed.inject(PacienteRegistrosSesion); + anterior.agregar('001', casos[0].registro); + TestBed.resetTestingModule(); + const nueva = TestBed.inject(PacienteRegistrosSesion); + expect(nueva).not.toBe(anterior); + expect(nueva.paraPaciente('001')).toEqual([]); + for (const spy of storage) { expect(spy).not.toHaveBeenCalled(); spy.mockRestore(); } + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.validation.ts new file mode 100644 index 0000000..7b17ab0 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.validation.ts @@ -0,0 +1,34 @@ +import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO, esOpcion } from './paciente-registro.catalogos'; +import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; + +/** Fecha de calendario ISO estricta, sin normalización permisiva de Date.parse ni huso horario. */ +export function esFechaReal(valor: unknown): valor is string { + if (typeof valor !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(valor)) return false; + const [anio, mes, dia] = valor.split('-').map(Number); + if (anio < 1 || mes < 1 || mes > 12 || dia < 1) return false; + const bisiesto = anio % 4 === 0 && (anio % 100 !== 0 || anio % 400 === 0); + const dias = [31, bisiesto ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + return dia <= dias[mes - 1]; +} + +/** La misma frontera de validación se usa al enviar el formulario y al escribir en memoria. */ +export function crearRegistroTemporal( + tipo: TipoRegistroTemporal, + seleccion: string, + fecha: string, + resultado = '', +): NuevoRegistroTemporal | null { + if (!esFechaReal(fecha)) return null; + switch (tipo) { + case 'condicion': + return esOpcion(CONDICIONES_DEMO, seleccion) ? { tipo, condicion: seleccion, fecha } : null; + case 'procedimiento': + return esOpcion(PROCEDIMIENTOS_DEMO, seleccion) ? { tipo, procedimiento: seleccion, fecha } : null; + case 'resultado': + if (!esOpcion(ESTUDIOS_DEMO, seleccion) || !esOpcion(RESULTADOS_DEMO[seleccion], resultado)) return null; + // La pertenencia al catálogo del estudio se comprobó arriba; conserva esa pareja en el modelo. + return { tipo, estudio: seleccion, resultado, fecha } as NuevoRegistroTemporal; + default: + return null; + } +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts b/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts new file mode 100644 index 0000000..8198377 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts @@ -0,0 +1,45 @@ +import { Injectable, signal } from '@angular/core'; +import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO } from './paciente-registro.catalogos'; +import { NuevoRegistroTemporal, RegistroTemporal } from './paciente-registro.models'; +import { crearRegistroTemporal } from './paciente-registro.validation'; + +const SIN_REGISTROS: readonly RegistroTemporal[] = Object.freeze([]); + +/** Una instancia por aplicación Angular. Se pierde en una recarga completa, sin almacenamiento externo. */ +@Injectable({ providedIn: 'root' }) +export class PacienteRegistrosSesion { + private readonly registros = signal>(new Map()); + private siguienteId = 0; + + paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] { + return this.registros().get(idSeudonimo) ?? SIN_REGISTROS; + } + + agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean { + if (!idSeudonimo || !nuevo) return false; + const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion + : nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio; + const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : ''); + if (!validado) return false; + const registro: RegistroTemporal = Object.freeze({ + ...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion', + }); + this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([ + ...(actual.get(idSeudonimo) ?? []), registro, + ]))); + return true; + } +} + +export function etiquetaRegistro(registro: RegistroTemporal): string { + switch (registro.tipo) { + case 'condicion': return CONDICIONES_DEMO[registro.condicion]; + case 'procedimiento': return PROCEDIMIENTOS_DEMO[registro.procedimiento]; + case 'resultado': return ESTUDIOS_DEMO[registro.estudio]; + } +} + +export function etiquetaResultado(registro: RegistroTemporal): string { + return registro.tipo === 'resultado' + ? (RESULTADOS_DEMO[registro.estudio] as Readonly>)[registro.resultado] : ''; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html new file mode 100644 index 0000000..49cfa6b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -0,0 +1,37 @@ +

    Estimaciones de riesgo

    +

    Valores ilustrativos · Sin evaluación clínica

    +@let lectura = estado(); +@switch (lectura.tipo) { + @case ('cargando') {

    Cargando estimaciones de riesgo…

    } + @case ('vacio') {

    Sin estimaciones de riesgo disponibles.

    } + @case ('no-disponible') {

    Estimaciones de riesgo no disponibles.

    } + @case ('error') {

    No se pudieron cargar las estimaciones de riesgo.

    } + @case ('disponible') { +
    + + + + + + + + + + + + @for (fila of lectura.datos.filas; track fila.id) { + + + + + + + + + } + +
    Ejemplos ilustrativos de estimaciones de riesgo
    Antecedentes precolposcopiaAntecedentes poscolposcopiaResultado VPH actualCitología actualRiesgo inmediato CIN3+ (%)Riesgo CIN3+ a 5 años (%)
    {{ fila.antecedentesPrecolposcopia }}{{ fila.antecedentesPoscolposcopia }}{{ fila.resultadoVphActual }}{{ fila.citologiaActual }}{{ fila.riesgoInmediatoPorcentaje === null ? 'No disponible' : (fila.riesgoInmediatoPorcentaje | number:'1.1-2') + ' %' }}{{ fila.riesgoCin3A5AnosPorcentaje === null ? 'No disponible' : (fila.riesgoCin3A5AnosPorcentaje | number:'1.1-2') + ' %' }}
    +
    + } +} +

    Recomendaciones no disponibles.

    diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss new file mode 100644 index 0000000..b5b49a3 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -0,0 +1,15 @@ +:host { display: block; min-width: 0; max-width: 100%; } +h4 { margin-block: 0 .5rem; font-size: 1.05rem; } +.illustrative-label, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; } +.risk-scroll { width: 100%; min-width: 0; max-width: 100%; max-height: 28rem; overflow: auto; + border: 1px solid var(--issste-border); border-radius: .5rem; box-sizing: border-box; } +.risk-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } +table { width: 100%; min-width: 58rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; } +caption { text-align: start; padding: .75rem; color: var(--issste-text-secondary); } +th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: break-word; } +th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; } +th:nth-child(-n+2) { min-width: 10rem; } +th:nth-child(n+3) { min-width: 7rem; } +td { background: var(--issste-surface); } +tbody tr:last-child td { border-bottom: 0; } +.percentage { font-variant-numeric: tabular-nums; white-space: nowrap; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts new file mode 100644 index 0000000..065729e --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -0,0 +1,14 @@ +import { Component, inject } from '@angular/core'; +import { DecimalPipe } from '@angular/common'; +import { PacienteRiesgoState } from './paciente-riesgo.state'; + +@Component({ + selector: 'app-paciente-riesgo-tabla', + imports: [DecimalPipe], + providers: [PacienteRiesgoState], + templateUrl: './paciente-riesgo-tabla.html', + styleUrl: './paciente-riesgo-tabla.scss', +}) +export class PacienteRiesgoTabla { + readonly estado = inject(PacienteRiesgoState).estado; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts new file mode 100644 index 0000000..ef5e3bc --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts @@ -0,0 +1,16 @@ +import { EstimacionesRiesgo } from './paciente-riesgo.models'; + +/** Invented values for layout only. Not copied from CCSM, validated or patient-derived. */ +export const ESTIMACIONES_RIESGO_ILUSTRATIVAS: EstimacionesRiesgo = { + origen: 'ilustrativo', + filas: [ + { id: 'ejemplo-1', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa', + resultadoVphActual: 'Positivo', citologiaActual: 'ASC-US / LSIL', riesgoInmediatoPorcentaje: 2.4, riesgoCin3A5AnosPorcentaje: 6.8 }, + { id: 'ejemplo-2', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa', + resultadoVphActual: 'Positivo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.8, riesgoCin3A5AnosPorcentaje: 3.2 }, + { id: 'ejemplo-3', antecedentesPrecolposcopia: 'Sin información de ejemplo', antecedentesPoscolposcopia: 'Sin información de ejemplo', + resultadoVphActual: 'Negativo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.2, riesgoCin3A5AnosPorcentaje: 0.9 }, + { id: 'ejemplo-4', antecedentesPrecolposcopia: 'Alto grado', antecedentesPoscolposcopia: 'Control de ejemplo', + resultadoVphActual: 'Positivo', citologiaActual: 'Alto grado', riesgoInmediatoPorcentaje: 7.6, riesgoCin3A5AnosPorcentaje: 12.4 }, + ], +}; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts new file mode 100644 index 0000000..84c738b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -0,0 +1,23 @@ +import { Observable } from 'rxjs'; + +/** Presentation model, not a WebApi contract or a clinical decision rule. */ +export interface EstimacionRiesgo { + id: string; + antecedentesPrecolposcopia: string; + antecedentesPoscolposcopia: string; + resultadoVphActual: string; + citologiaActual: string; + riesgoInmediatoPorcentaje: number | null; + riesgoCin3A5AnosPorcentaje: number | null; +} +export interface EstimacionesRiesgo { + origen: 'ilustrativo'; + filas: readonly EstimacionRiesgo[]; +} +/** No patient input: these examples must never be matched to a selected patient. */ +export interface PacienteRiesgoProvider { + obtener(): Observable; +} +export type PacienteRiesgoEstado = + | { tipo: 'cargando' | 'vacio' | 'no-disponible' | 'error' } + | { tipo: 'disponible'; datos: EstimacionesRiesgo }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts new file mode 100644 index 0000000..16b95b8 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -0,0 +1,14 @@ +import { Injectable, InjectionToken, inject } from '@angular/core'; +import { defer, of } from 'rxjs'; +import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures'; +import { PacienteRiesgoProvider } from './paciente-riesgo.models'; + +@Injectable({ providedIn: 'root' }) +export class PacienteRiesgoIlustrativoProvider implements PacienteRiesgoProvider { + obtener() { return defer(() => of(structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS))); } +} + +// Future adapters can replace this token; no HTTP route or patient matching is assumed. +export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { + providedIn: 'root', factory: () => inject(PacienteRiesgoIlustrativoProvider), +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts new file mode 100644 index 0000000..affe99c --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -0,0 +1,95 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { of, Subject, throwError } from 'rxjs'; +import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures'; +import { EstimacionesRiesgo, PacienteRiesgoProvider } from './paciente-riesgo.models'; +import { PACIENTE_RIESGO_PROVIDER, PacienteRiesgoIlustrativoProvider } from './paciente-riesgo.provider'; +import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; + +describe('P0-C.2: proveedor ilustrativo independiente', () => { + it('lee sin HttpClient ni paciente y devuelve copias independientes del fixture', () => { + const provider = TestBed.inject(PacienteRiesgoIlustrativoProvider); + const baseline = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS); + provider.obtener().subscribe(data => { + expect(data).toEqual(baseline); + data.filas[0].riesgoInmediatoPorcentaje = 99; + }); + provider.obtener().subscribe(data => expect(data).toEqual(baseline)); + expect(ESTIMACIONES_RIESGO_ILUSTRATIVAS).toEqual(baseline); + expect(baseline.filas).toHaveLength(4); + }); +}); + +describe('P0-C.2: tabla accesible y estados de lectura', () => { + function setup(provider?: PacienteRiesgoProvider) { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), + ...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] }); + const fixture = TestBed.createComponent(PacienteRiesgoTabla); + fixture.detectChanges(); + return fixture; + } + afterEach(() => { TestBed.inject(HttpTestingController).verify(); }); + it('renderiza seis encabezados, cuatro filas sin selección y porcentajes solo ilustrativos', () => { + const f = setup(), root: HTMLElement = f.nativeElement; + expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).toEqual([ + 'Antecedentes precolposcopia', 'Antecedentes poscolposcopia', 'Resultado VPH actual', 'Citología actual', + 'Riesgo inmediato CIN3+ (%)', 'Riesgo CIN3+ a 5 años (%)', + ]); + expect([...root.querySelectorAll('th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); + expect(root.querySelectorAll('tbody tr')).toHaveLength(4); + expect(root.querySelectorAll('tbody td')).toHaveLength(24); + expect(root.querySelector('caption')!.textContent).toContain('ilustrativos'); + expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-ilustrativo'); + expect(root.querySelector('#riesgo-ilustrativo')!.textContent).toBe('Valores ilustrativos · Sin evaluación clínica'); + expect(root.querySelectorAll('[aria-selected], button, a, input')).toHaveLength(0); + expect([...root.querySelectorAll('.percentage')].every(td => td.textContent!.trim().endsWith('%'))).toBe(true); + expect(root.textContent).toContain('Recomendaciones no disponibles'); + TestBed.inject(HttpTestingController).expectNone(() => true); + }); + it('contiene el desplazamiento y conserva anchos mínimos y encabezados, con foco de teclado', () => { + const f = setup(), root: HTMLElement = f.nativeElement; + const scroll = root.querySelector('.risk-scroll')!; + expect(scroll.tabIndex).toBe(0); expect(scroll.getAttribute('role')).toBe('region'); + expect(scroll.getAttribute('aria-label')).toContain('tabla desplazable'); + // jsdom verifies the responsive CSS contract; viewport geometry still needs Chrome review. + expect(getComputedStyle(scroll).overflow).toBe('auto'); + expect(getComputedStyle(scroll).maxWidth).toBe('100%'); + expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('58rem'); + expect(getComputedStyle(root.querySelector('th')!).position).toBe('sticky'); + }); + it('sustituye el fixture por inyección sin calcular porcentajes ni convertir null en cero', () => { + const data = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS); + data.filas = [{ ...data.filas[0], riesgoInmediatoPorcentaje: 0, riesgoCin3A5AnosPorcentaje: null }]; + const obtener = vi.fn(() => of(data)), f = setup({ obtener }); + expect(obtener).toHaveBeenCalledExactlyOnceWith(); + const cells = [...f.nativeElement.querySelectorAll('.percentage')] as HTMLElement[]; + expect(cells.map(c => c.textContent)).toEqual(['0.0 %', 'No disponible']); + TestBed.inject(HttpTestingController).expectNone(() => true); + }); + it.each([ + { data: { origen: 'ilustrativo', filas: [] } as EstimacionesRiesgo, text: 'Sin estimaciones de riesgo disponibles.' }, + { data: null, text: 'Estimaciones de riesgo no disponibles.' }, + ])('representa ausencia explícita: $text', ({ data, text }) => { + const f = setup({ obtener: () => of(data) }); + expect(f.nativeElement.textContent).toContain(text); + expect(f.nativeElement.querySelector('table')).toBeNull(); + expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); + }); + it('distingue carga y error sin filtrar mensajes internos, y cancela al desmontarse', () => { + const source = new Subject(); + const f = setup({ obtener: () => source }); + expect(f.nativeElement.textContent).toContain('Cargando estimaciones de riesgo'); + source.error(new Error('private')); f.detectChanges(); + expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudieron cargar'); + expect(f.nativeElement.textContent).not.toContain('private'); + expect(f.nativeElement.querySelector('table')).toBeNull(); + f.destroy(); expect(source.observed).toBe(false); + }); + it('un error inmediato del adaptador también mantiene las recomendaciones ausentes', () => { + const f = setup({ obtener: () => throwError(() => new Error('private')) }); + expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); + expect(f.nativeElement.textContent).not.toContain('private'); + TestBed.inject(HttpTestingController).expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts new file mode 100644 index 0000000..23efcd8 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -0,0 +1,14 @@ +import { inject, Injectable } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { catchError, map, of } from 'rxjs'; +import { PacienteRiesgoEstado } from './paciente-riesgo.models'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; + +@Injectable() +export class PacienteRiesgoState { + readonly estado = toSignal(inject(PACIENTE_RIESGO_PROVIDER).obtener().pipe( + map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } + : datos.filas.length ? { tipo: 'disponible', datos } : { tipo: 'vacio' }), + catchError(() => of({ tipo: 'error' })), + ), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado }); +} diff --git a/src/styles.scss b/src/styles.scss index 7afccdf..c8d099b 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -72,6 +72,22 @@ body { font-family: var(--issste-font-body); } +.dashboard .catalog-grid > app-indicador-catalog-card { scroll-margin-top: var(--issste-header-clearance, 6rem); } +.dashboard .graphic-navigation-trigger { + position: fixed; + z-index: 90; + inset-inline-start: max(.5rem, env(safe-area-inset-left)); + top: 50%; + transform: translateY(-50%); + width: 48px; + height: 48px; + color: var(--issste-text); + background: var(--issste-accent); + box-shadow: 0 2px 8px rgb(0 0 0 / 18%); +} +.dashboard .graphic-navigation-trigger:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 3px; } +.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing) { pointer-events: none; } + h1, h2, h3, h4, h5, h6 { font-family: var(--issste-font-heading); font-weight: 700; From 94c63c460cad28d2700b637229d278e4084088ed Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 28 Oct 2026 09:45:00 -0600 Subject: [PATCH 50/51] feat(eu7): incorporar transiciones animadas en dona y barras --- .../indicadores/indicador-eu7-escenario.html | 4 +- .../indicador-eu7-escenario.spec.ts | 6 +- .../indicadores-eu7-escenario.spec.ts | 29 ++- .../indicadores/indicadores-eu7-escenario.ts | 21 +- src/app/shared/plotly/plotly-chart.spec.ts | 21 ++ src/app/shared/plotly/plotly-chart.ts | 8 +- .../shared/plotly/plotly-controller.spec.ts | 209 +++++++++++++++++- src/app/shared/plotly/plotly-controller.ts | 113 +++++++++- 8 files changed, 389 insertions(+), 22 deletions(-) diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html index d084249..26db2f9 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.html +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -48,14 +48,14 @@

    Distribución de resultados, {{ m.periodo }}

    @if (m.total !== null && m.total > 0 && donutFigure) { - + } @else {

    {{ 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.' }}

    }

    {{ sinDatoNote }}

    {{ selectionLabel }} por escenario clínico, {{ m.periodo }}

    Porcentaje del total válido de cada escenario; excluye «Sin dato».

    @if (m.escenarios.length && barsFigure) { - + }
    diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts index 0120d8f..a0e8c86 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', template: '' }) class ChartStub { - figure = input(); label = input(); showNotes = input(); + figure = input(); label = input(); showNotes = input(); animated = input(); plotClick = output(); } 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); }); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts index fd35bd1..4ed77e2 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -42,8 +42,11 @@ describe('EU7 modelo de presentación del entregable', () => { expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1))) .toEqual(['5.0', '24.3', '21.7', '7.8']); const category = barras(m, { categoria: 'LIEAG' }, 'claro'); - expect(category.data).toHaveLength(1); - expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); + // Same traces in every selection (animation identity); unselected ones are zero-width. + expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid'])); + const lieag = category.data.find(t => t['uid'] === 'LIEAG')!; + expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!)); + expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true); expect((category.layout['annotations'] as { text: string }[]).map(a => a.text)) .toEqual(m.escenarios.map(s => `${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} % (${s.celdas['LIEAG'].n}/${s.den})`)); expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]); @@ -74,7 +77,10 @@ describe('EU7 modelo de presentación del entregable', () => { else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 }); else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 }); const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro'); - expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]); + expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]); + expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true); + expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t => + t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true); expect(JSON.stringify(f)).not.toContain('123456'); expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull(); }); @@ -95,6 +101,7 @@ describe('EU7 modelo de presentación del entregable', () => { (data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0); const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]); expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true); + expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true); expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })])); }); it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => { @@ -102,4 +109,20 @@ describe('EU7 modelo de presentación del entregable', () => { const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]); expect(m.celdas['NORMAL'].n).toBeNull(); }); + it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => { + const original = structuredClone(data), m = model(), snapshot = structuredClone(m); + const ids = m.categorias.map(c => c.id); + for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) { + const f = barras(m, selection, 'claro'); + expect(f.data.map(t => t['uid'])).toEqual(ids); + expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length); + f.data.forEach((t, i) => { + if (t['hoverinfo'] === 'skip') { + expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => '')); + } else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i]))); + }); + dona(m, selection, 'claro'); + } + expect(m).toEqual(snapshot); expect(data).toEqual(original); + }); }); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index 4324199..aca81aa 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -217,13 +217,20 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id); const y = m.escenarios.map(s => escapar(s.etiqueta)); const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0)); - return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => { - const x = m.escenarios.map(s => porcentaje(s, c.id)); - return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x, - marker: { color: c.color, line: { color: p.background, width: 1 } }, - text: x.map(v => v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', - customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]), - hovertemplate: `%{y}
    ${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` }; + // Every category keeps its trace (same uid and count) so a selection animates; + // an unselected category is a zero-width bar without text or hover, never data. + return { data: m.categorias.map(c => { + const visible = visibles.includes(c.id); + const x = m.escenarios.map(s => { + const value = porcentaje(s, c.id); + return value === null ? null : visible ? value : 0; + }); + return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x, + marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } }, + text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', + customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [], + ...(visible ? { hovertemplate: `%{y}
    ${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` } + : { hoverinfo: 'skip' }) }; }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false, diff --git a/src/app/shared/plotly/plotly-chart.spec.ts b/src/app/shared/plotly/plotly-chart.spec.ts index 75b325d..52dfadd 100644 --- a/src/app/shared/plotly/plotly-chart.spec.ts +++ b/src/app/shared/plotly/plotly-chart.spec.ts @@ -26,6 +26,27 @@ describe('PlotlyChart lifecycle', () => { fixture.destroy(); expect(disconnect).toHaveBeenCalled(); expect(mocks.purge).toHaveBeenCalled(); vi.unstubAllGlobals(); }); + it.each([[false, true], [true, false]])('animated respeta prefers-reduced-motion=%s (transición: %s) y es opcional', async (reduce, transition) => { + vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: reduce })); + const settle = async () => { await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); }; + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('animated', true); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} }); + fixture.detectChanges(); await settle(); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} }); + fixture.detectChanges(); await settle(); + expect(mocks.react).toHaveBeenCalledTimes(2); + expect(mocks.react.mock.calls[1][2]['transition'] !== undefined).toBe(transition); + fixture.destroy(); vi.unstubAllGlobals(); + }); + it('sin animated las actualizaciones no llevan transición', async () => { + const fixture = TestBed.createComponent(PlotlyChart); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [1] }], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); + fixture.componentRef.setInput('figure', { data: [{ type: 'bar', x: [2] }], layout: {} }); + fixture.detectChanges(); await fixture.whenStable(); for (let i = 0; i < 40; i++) await Promise.resolve(); + expect(mocks.react.mock.calls[1][2]['transition']).toBeUndefined(); fixture.destroy(); + }); it('muestra error asíncrono y se recupera con reintento', async () => { mocks.react.mockRejectedValueOnce(new Error('render failed')); const fixture = TestBed.createComponent(PlotlyChart); diff --git a/src/app/shared/plotly/plotly-chart.ts b/src/app/shared/plotly/plotly-chart.ts index 22925d3..2212a1b 100644 --- a/src/app/shared/plotly/plotly-chart.ts +++ b/src/app/shared/plotly/plotly-chart.ts @@ -5,6 +5,10 @@ import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; import { PlotlyController } from './plotly-controller'; import { PLOTLY_LOADER } from './plotly-runtime'; +function prefersReducedMotion(): boolean { + return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; +} + @Component({ selector: 'app-plotly-chart', imports: [MatButtonModule, MatProgressBarModule], @@ -27,6 +31,8 @@ import { PLOTLY_LOADER } from './plotly-runtime'; export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { @Input() showNotes = true; @Input() label = 'Figura estadística'; + // Opt-in: updates of the same visible figure move smoothly instead of redrawing. + @Input() animated = false; @Input({ required: true }) figure!: PlotlyFigure; @ViewChild('host', { static: true }) host!: ElementRef; readonly renderError = output(); @@ -57,7 +63,7 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy { this.controller = new PlotlyController(this.host.nativeElement, this.loadPlotly, state => { this.status.set(state); if (state === 'error') this.renderError.emit(); - }, event => this.plotClick.emit(event)); + }, event => this.plotClick.emit(event), { animate: () => this.animated && !prefersReducedMotion() }); if (typeof ResizeObserver !== 'undefined') { this.observer = new ResizeObserver(this.windowResize); this.observer.observe(this.host.nativeElement); diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts index da71695..0fb746c 100644 --- a/src/app/shared/plotly/plotly-controller.spec.ts +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -1,6 +1,6 @@ import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures'; import { vi } from 'vitest'; -import { PlotlyController } from './plotly-controller'; +import { cubicInOut, pieFrame, piesInterpolable, PlotlyController, TRANSITION_MS } from './plotly-controller'; import { PlotlyRuntime } from './plotly-runtime'; import { PlotlyFigure } from '../../features/indicadores/indicadores.models'; function deferred() { @@ -151,6 +151,33 @@ describe('PlotlyController con Plotly instalado', () => { runtime = (module.default ?? module) as typeof runtime; } finally { canvas.mockRestore(); } }); + it('Plotly real acepta las transiciones de barras y los fotogramas de pies y termina en la figura destino', async () => { + const host = document.createElement('div'); + document.body.append(host); + let clock = 0, controller: PlotlyController | undefined; + const ready = () => new Promise((resolve, reject) => { pending = { resolve, reject }; }); + let pending!: { resolve: () => void; reject: (e: Error) => void }; + try { + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') pending?.resolve(); + if (state === 'error') pending?.reject(new Error('Plotly transition failed')); + }, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) }); + const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, orientation: 'h', x: [v], y: ['A'] })), layout: { barmode: 'stack' } }); + let done = ready(); controller.setFigure(bars([40, 60])); await done; + done = ready(); controller.setFigure(bars([0, 60])); await done; + expect((host as unknown as { data: { x: number[] }[] }).data.map(t => t.x)).toEqual([[0], [60]]); + controller.destroy(); controller = undefined; + const pies = (values: number[]): PlotlyFigure => ({ data: [{ type: 'pie', name: 'grupos', values, marker: { colors: ['rgba(1,2,3,1)', 'rgba(4,5,6,1)'] } }], layout: {} }); + controller = new PlotlyController(host, () => Promise.resolve(runtime), state => { + if (state === 'ready') pending?.resolve(); + if (state === 'error') pending?.reject(new Error('Plotly pie frames failed')); + }, undefined, { animate: () => true, nextFrame: () => Promise.resolve(clock += 150) }); + done = ready(); controller.setFigure(pies([10, 0])); await done; + done = ready(); controller.setFigure(pies([3, 7])); await done; + expect((host as unknown as { data: { values: number[] }[] }).data[0].values).toEqual([3, 7]); + expect(host.style.visibility).toBe('visible'); + } finally { controller?.destroy(); host.remove(); } + }); it('usa propiedades admitidas por el esquema de Plotly 4.1.2', () => { expect(runtime.version).toBe('4.1.2'); const config = runtime.PlotSchema.get().config; @@ -212,3 +239,183 @@ describe('PlotlyController con Plotly instalado', () => { }); }); + +describe('PlotlyController transiciones opcionales', () => { + const pie = (values: number[], alpha = 1): PlotlyFigure => ({ data: [ + { type: 'pie', name: 'centro', values: [1], text: ['Total'] }, + { type: 'pie', name: 'grupos', values, text: values.map(String), marker: { colors: values.map(() => `rgba(10,20,30,${alpha})`) } }, + ], layout: { height: 440 } }); + const bars = (x: number[]): PlotlyFigure => ({ data: x.map((v, i) => ({ type: 'bar', uid: 'c' + i, x: [v], y: ['A'] })), layout: {} }); + let host: HTMLElement, plotly: PlotlyRuntime, clock: number, animate: boolean; + let state: ReturnType void>>; + const nextFrame = () => Promise.resolve(clock += 100); + beforeEach(() => { + host = document.createElement('div'); clock = 0; animate = true; + plotly = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) }, + addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined) }; + state = vi.fn(); + }); + const controller = () => new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, { animate: () => animate, nextFrame }); + async function settleLong() { for (let i = 0; i < 80; i++) await Promise.resolve(); } + + it('easing cubic-in-out y fotogramas intermedios de pies: valores y alfa se mueven, textos esperan', () => { + expect([0, .5, 1].map(cubicInOut)).toEqual([0, .5, 1]); + expect(cubicInOut(.25)).toBeLessThan(.25); expect(cubicInOut(.75)).toBeGreaterThan(.75); + const from = pie([10, 0], .3), to = pie([4, 6], 1); + expect(piesInterpolable(from, to)).toBe(true); + expect(piesInterpolable(from, bars([1]))).toBe(false); + expect(piesInterpolable(from, { ...to, data: [to.data[0]] })).toBe(false); + const half = pieFrame(from, to, .5); + expect(half.data[0]['values']).toEqual([1]); + expect(half.data[0]['text']).toEqual(['']); + expect(half.data[1]['values']).toEqual([7, 3]); expect(half.data[1]['text']).toEqual(['', '']); + expect((half.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']); + expect(to.data[1]['values']).toEqual([4, 6]); + for (const trace of half.data) { + expect(trace['textinfo']).toBe('none'); expect(trace['hoverinfo']).toBe('skip'); + expect(trace['hovertemplate']).toBeNull(); expect(trace['customdata']).toEqual([]); + } + // Same values, only dimming (a selection that keeps the totals): colors move, texts stay. + const dimmed = pieFrame(pie([4, 6], .3), pie([4, 6], 1), .5); + expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']); + expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']); + expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]); + }); + it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => { + const c = controller(); + c.setFigure(pie([10, 0])); await settleLong(); + expect(host.style.visibility).toBe('visible'); state.mockClear(); vi.mocked(plotly.react).mockClear(); + const target = pie([4, 6]); + c.setFigure(target); + expect(host.style.visibility).toBe('visible'); expect(state).not.toHaveBeenCalledWith('loading'); + await settleLong(); + const calls = vi.mocked(plotly.react).mock.calls; + // 100 ms per frame over TRANSITION_MS, plus the exact final figure. + expect(calls.length).toBe(Math.ceil(TRANSITION_MS / 100)); + const values = calls.map(call => call[1][1]['values'] as number[]); + expect(values[0][0]).toBeLessThan(10); expect(values[0][0]).toBeGreaterThan(4); + for (let i = 1; i < values.length - 1; i++) expect(values[i][0]).toBeLessThan(values[i - 1][0]); + expect(calls.at(-1)![1]).toEqual(target.data); expect(calls.at(-1)![2]).toEqual(target.layout); + expect(state).toHaveBeenLastCalledWith('ready'); expect(host.style.visibility).toBe('visible'); + }); + it('las barras usan layout.transition de 450 ms cubic-in-out en un solo react', async () => { + const c = controller(); + c.setFigure(bars([1, 2])); await settleLong(); + expect(vi.mocked(plotly.react).mock.calls[0][2]['transition']).toBeUndefined(); + c.setFigure(bars([3, 0])); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(2); + expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toEqual({ duration: TRANSITION_MS, easing: 'cubic-in-out' }); + }); + it('sin animación (opción desactivada o movimiento reducido) conserva el renderizado oculto original', async () => { + animate = false; + const c = controller(); + c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); + c.setFigure(pie([4, 6])); + expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading'); + await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(2); + expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined(); + }); + it('una selección nueva interrumpe la animación y parte del último fotograma dibujado', async () => { + const c = controller(); + c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear(); + c.setFigure(pie([0, 10])); + for (let i = 0; i < 6; i++) await Promise.resolve(); + c.setFigure(pie([10, 0])); + await settleLong(); + const last = vi.mocked(plotly.react).mock.calls.at(-1)!; + expect(last[1][1]['values']).toEqual([10, 0]); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + + it('no interpola pies con nulos, otra identidad u orden de categorías', () => { + const source = pie([10, 0]); + const changed = pie([5, 5]); changed.data[1]['values'] = [null, 5]; + expect(piesInterpolable(source, changed)).toBe(false); + changed.data[1]['values'] = [5, 5]; changed.data[1]['name'] = 'otro'; + expect(piesInterpolable(source, changed)).toBe(false); + source.data[1]['labels'] = ['A', 'B']; + const reordered = pie([5, 5]); reordered.data[1]['labels'] = ['B', 'A']; + expect(piesInterpolable(source, reordered)).toBe(false); + }); + it('ningún cuadro geométrico expone conteos, plantillas, tooltips ni el total destino adelantado', async () => { + const source = pie([10, 0]), target = pie([4, 6]); + target.data.forEach(trace => Object.assign(trace, { customdata: [[4, 40], [6, 60]], + hovertemplate: '%{value} / %{customdata[0]}', hovertext: ['4', '6'], texttemplate: '%{value}' })); + const original = structuredClone(target), c = controller(); + c.setFigure(source); await settleLong(); vi.mocked(plotly.react).mockClear(); + c.setFigure(target); await settleLong(); + const calls = vi.mocked(plotly.react).mock.calls; + for (const call of calls.slice(0, -1)) for (const trace of call[1]) { + expect(trace['hoverinfo']).toBe('skip'); expect(trace['hovertemplate']).toBeNull(); + expect(trace['customdata']).toEqual([]); expect(trace['hovertext']).toEqual([]); + expect(trace['texttemplate']).toBe(''); expect(trace['textinfo']).toBe('none'); + expect((trace['text'] as string[]).every(text => text === '')).toBe(true); + } + expect(calls.at(-1)![1]).toEqual(target.data); expect(target).toEqual(original); c.destroy(); + }); + it('interrumpe tras un react pendiente y usa el último cuadro completado sin renders concurrentes', async () => { + const frames: ((time: number) => void)[] = []; + const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, + { animate: () => true, nextFrame: () => new Promise(resolve => frames.push(resolve)) }); + const step = async (time: number) => { expect(frames.length).toBeGreaterThan(0); frames.shift()!(time); await settleLong(); }; + c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear(); + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + c.setFigure(pie([0, 10])); await settleLong(); await step(0); await step(150); + const drawn = vi.mocked(plotly.react).mock.calls[0][1][1]['values'] as number[]; + c.setFigure(pie([8, 2])); c.resize(); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(1); expect(plotly.Plots.resize).not.toHaveBeenCalled(); + pending.resolve(); await settleLong(); + await step(200); // Discard stale frame; start the latest transition. + await step(250); await step(400); + const resumed = vi.mocked(plotly.react).mock.calls[1][1][1]['values'] as number[]; + expect(resumed[0]).toBeCloseTo(drawn[0] + (8 - drawn[0]) * cubicInOut(150 / TRANSITION_MS)); + await step(700); + expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(pie([8, 2]).data); + expect(state.mock.calls).toEqual([['ready']]); expect(plotly.Plots.resize).toHaveBeenCalledTimes(1); c.destroy(); + }); + it('movimiento reducido durante la dona termina inmediatamente con datos exactos', async () => { + const frames: ((time: number) => void)[] = []; + const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, + { animate: () => animate, nextFrame: () => new Promise(resolve => frames.push(resolve)) }); + c.setFigure(pie([10, 0])); await settleLong(); vi.mocked(plotly.react).mockClear(); + const target = pie([4, 6]); c.setFigure(target); await settleLong(); + frames.shift()!(0); await settleLong(); animate = false; + frames.shift()!(150); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(1); expect(vi.mocked(plotly.react).mock.calls[0][1]).toEqual(target.data); + expect(state).toHaveBeenLastCalledWith('ready'); c.destroy(); + }); + it('destruir mientras espera un fotograma no vuelve a dibujar ni a emitir ready', async () => { + let frame!: (time: number) => void; + const c = new PlotlyController(host, () => Promise.resolve(plotly), state, undefined, + { animate: () => true, nextFrame: () => new Promise(resolve => frame = resolve) }); + c.setFigure(pie([10, 0])); await settleLong(); state.mockClear(); vi.mocked(plotly.react).mockClear(); + c.setFigure(pie([0, 10])); await settleLong(); c.destroy(); frame(0); await settleLong(); frame(100); await settleLong(); + expect(plotly.react).not.toHaveBeenCalled(); expect(state).not.toHaveBeenCalled(); + expect(host.style.visibility).toBe('hidden'); + }); + it.each(['uid', 'escenario', 'nulo', 'trazas'])('barras con cambio de %s se redibujan exactamente sin interpolación', async kind => { + const c = controller(), target = bars([3, 4]); + c.setFigure(bars([1, 2])); await settleLong(); + if (kind === 'uid') target.data[0]['uid'] = 'otro'; + if (kind === 'escenario') target.data[0]['y'] = ['Otro']; + if (kind === 'nulo') target.data[0]['x'] = [null]; + if (kind === 'trazas') target.data.pop(); + state.mockClear(); c.setFigure(target); + expect(host.style.visibility).toBe('hidden'); expect(state).toHaveBeenCalledWith('loading'); + await settleLong(); + expect(vi.mocked(plotly.react).mock.calls[1][2]['transition']).toBeUndefined(); + expect(vi.mocked(plotly.react).mock.calls[1][1]).toEqual(target.data); c.destroy(); + }); + it('barras rápidas se serializan, descartan destinos intermedios y nunca anuncian ready obsoleto', async () => { + const c = controller(); c.setFigure(bars([1, 2])); await settleLong(); state.mockClear(); + const pending = deferred(); vi.mocked(plotly.react).mockReturnValueOnce(pending.promise); + c.setFigure(bars([0, 2])); await settleLong(); + c.setFigure(bars([3, 0])); c.setFigure(bars([4, 5])); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(2); expect(state).not.toHaveBeenCalled(); + pending.resolve(); await settleLong(); + expect(plotly.react).toHaveBeenCalledTimes(3); + expect(vi.mocked(plotly.react).mock.calls.at(-1)![1]).toEqual(bars([4, 5]).data); + expect(state.mock.calls).toEqual([['ready']]); expect(host.style.visibility).toBe('visible'); c.destroy(); + }); +}); diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts index 2a98f3f..9286055 100644 --- a/src/app/shared/plotly/plotly-controller.ts +++ b/src/app/shared/plotly/plotly-controller.ts @@ -6,6 +6,75 @@ interface EventHost extends HTMLElement { removeListener?: (name: string, listener: (event: unknown) => void) => void; } +export const TRANSITION_MS = 450; +export interface PlotlyControllerOptions { + // Evaluated per update: animate only an update of an already visible figure. + animate?: () => boolean; + // Resolves on the next animation frame with its timestamp (injectable for tests). + nextFrame?: () => Promise; +} +const nextAnimationFrame = () => new Promise(resolve => requestAnimationFrame(resolve)); +// Plotly's 'cubic-in-out', reproduced for the interpolated pie frames. +export function cubicInOut(t: number): number { + return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; +} +const RGBA = /^rgba\((\d+),(\d+),(\d+),([\d.]+)\)$/; +function mixColor(from: unknown, to: unknown, t: number): unknown { + const a = typeof from === 'string' ? RGBA.exec(from.replace(/\s/g, '')) : null; + const b = typeof to === 'string' ? RGBA.exec(to.replace(/\s/g, '')) : null; + if (!a || !b) return to; + const v = [1, 2, 3, 4].map(i => Number(a[i]) + (Number(b[i]) - Number(a[i])) * t); + return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`; +} +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n)); +/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */ +export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean { + return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => { + const old = from.data[i]; + return trace['type'] === 'pie' && old['type'] === 'pie' && trace['name'] === old['name'] + && JSON.stringify(trace['labels']) === JSON.stringify(old['labels']) + && numbers(trace['values']) && numbers(old['values']) && trace['values'].length === old['values'].length; + }); +} +/** One intermediate pie frame: values and rgba colors move, texts wait for the final frame. */ +export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): PlotlyFigure { + const moving = to.data.some((trace, i) => (trace['values'] as number[]) + .some((v, j) => v !== (from.data[i]['values'] as number[])[j])); + return { ...to, data: to.data.map((trace, i) => { + const a = from.data[i]['values'] as number[], b = trace['values'] as number[]; + const oldMarker = from.data[i]['marker'] as Record | undefined; + const marker = trace['marker'] as Record | undefined; + const oldColors = oldMarker?.['colors'], colors = marker?.['colors']; + const sameValues = a.every((v, j) => v === b[j]); + const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length + && colors.some((c, j) => c !== oldColors[j]); + if (sameValues && !mixColors && !moving) return trace; + // Geometry is illustrative until the exact target render. Hide all clinical + // readouts (including the centre) and never attach counts to moving slices. + return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }), + ...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '', + hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}), + ...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) }; + }) }; +} +const transitionable = (figure: PlotlyFigure) => figure.data.length > 0 + && figure.data.every(trace => ['bar', 'scatter'].includes(String(trace['type'] ?? 'scatter'))); +// A changed catalogue, scenario axis or availability mask is an exact redraw. +// In particular, never tween a published value into an unavailable/suppressed one. +function cartesianInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean { + return transitionable(from) && transitionable(to) && from.data.length === to.data.length + && to.data.every((trace, i) => { + const old = from.data[i]; + if (trace['type'] !== old['type'] || trace['uid'] !== old['uid']) return false; + return ['x', 'y'].every(axis => { + const a = old[axis], b = trace[axis]; + if (!Array.isArray(a) || !Array.isArray(b)) return a === b; + return a.length === b.length && b.every((v, j) => + typeof v === 'number' && typeof a[j] === 'number' ? true : v === a[j]); + }); + }); +} + // One serialized queue owns the host. A completed stale operation cannot expose // its graph or overwrite a newer react operation. Resize uses the same queue. export class PlotlyController { @@ -18,17 +87,28 @@ export class PlotlyController { private plotly?: PlotlyRuntime; private frameCount = 0; private listenerAttached = false; + // Last figure drawn on the host (target or intermediate frame); origin of the next transition. + private shown?: PlotlyFigure; + private animating = false; private readonly handleClick = (event: unknown) => { if (!this.destroyed && !this.busy && this.rendered === this.version) this.click?.(event); }; constructor(private host: HTMLElement, private load: () => Promise, private state: (state: 'loading' | 'ready' | 'error') => void, - private click?: (event: unknown) => void) {} + private click?: (event: unknown) => void, + private options: PlotlyControllerOptions = {}) {} + private get config() { return { responsive: false, displaylogo: false, showSendToCloud: false, modeBarButtonsToRemove: ['sendChartToCloud'] }; } setFigure(figure: PlotlyFigure) { if (this.destroyed) return; this.desired = figure; this.version++; + // A visible figure that will animate stays on screen; hiding it is the flash + // between selections. Every other update keeps the original hidden render. + this.animating = this.rendered >= 0 && this.host.style.visibility === 'visible' && !!this.shown && !!this.options.animate?.() + && !this.shown.frames?.length && !figure.frames?.length + && (piesInterpolable(this.shown, figure) || cartesianInterpolable(this.shown, figure)); + if (this.animating) return void this.drain(); this.host.style.visibility = 'hidden'; this.state('loading'); void this.drain(); @@ -55,15 +135,33 @@ export class PlotlyController { try { if (this.rendered !== version && this.desired) { // Plotly may mutate inputs; clone the complete JSON without changing values. - const figure = structuredClone(this.desired); + const target = structuredClone(this.desired); + const figure = structuredClone(target); if (this.frameCount) await this.plotly.deleteFrames(this.host, Array.from({ length: this.frameCount }, (_, i) => i)); this.frameCount = 0; if (this.destroyed) break; - await this.plotly.react(this.host, figure.data, figure.layout, { - ...figure.config, responsive: false, displaylogo: false, - showSendToCloud: false, - modeBarButtonsToRemove: ['sendChartToCloud'], - }); + const animate = this.animating && !!this.options.animate?.() && !!this.shown + && !this.shown.frames?.length && !figure.frames?.length; + const config = { ...figure.config, ...this.config }; + if (animate && piesInterpolable(this.shown!, figure)) { + const from = this.shown!, nextFrame = this.options.nextFrame ?? nextAnimationFrame; + const start = await nextFrame(); + for (;;) { + const t = Math.min(1, ((await nextFrame()) - start) / TRANSITION_MS); + if (this.destroyed || version !== this.version || !this.options.animate?.() || t >= 1) break; + const frame = pieFrame(from, figure, cubicInOut(t)); + const copy = structuredClone(frame); + await this.plotly.react(this.host, copy.data, copy.layout, config); + this.shown = frame; + } + if (this.destroyed) break; + if (version !== this.version) continue; + } + const layout = animate && this.shown && cartesianInterpolable(this.shown, figure) + && figure.layout['transition'] === undefined + ? { ...figure.layout, transition: { duration: TRANSITION_MS, easing: 'cubic-in-out' } } : figure.layout; + await this.plotly.react(this.host, figure.data, layout, config); + this.shown = target; if (!this.destroyed && !this.listenerAttached && this.click && (this.host as EventHost).on) { (this.host as EventHost).on!('plotly_click', this.handleClick); this.listenerAttached = true; @@ -88,6 +186,7 @@ export class PlotlyController { if (version !== this.version) continue; this.rendered = version; this.resizePending = false; + this.shown = undefined; this.host.style.visibility = 'hidden'; this.state('error'); } From 26fe1ccbb3959f4eb81226b7b946ba98794d41dc Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 28 Oct 2026 10:36:58 -0600 Subject: [PATCH 51/51] feat(cacu): preparar interfaz de riesgo individual de paciente --- .../paciente-detalle/paciente-detalle.spec.ts | 30 ++- .../paciente-registro-integracion.spec.ts | 10 +- .../paciente-riesgo-tabla.html | 93 ++++++--- .../paciente-riesgo-tabla.scss | 25 ++- .../paciente-detalle/paciente-riesgo-tabla.ts | 2 + .../paciente-riesgo.fixtures.ts | 16 -- .../paciente-riesgo.models.ts | 59 ++++-- .../paciente-riesgo.provider.ts | 14 +- .../paciente-detalle/paciente-riesgo.spec.ts | 186 ++++++++++++------ .../paciente-detalle/paciente-riesgo.state.ts | 8 +- .../paciente-riesgo.testing.ts | 21 ++ .../paciente-riesgo.validation.spec.ts | 123 ++++++++++++ .../paciente-riesgo.validation.ts | 58 ++++++ 13 files changed, 486 insertions(+), 159 deletions(-) delete mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts index b783757..ecd3f67 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts @@ -9,6 +9,8 @@ import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.models'; import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider'; import { PacienteDetalleState } from './paciente-detalle.state'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; const pacientes = seguimientoResponse(fixtureData).items; @@ -145,8 +147,9 @@ describe('Ficha individual desde Seguimiento CaCu', () => { expect(Array.from(detail.querySelectorAll('.history-card button'), button => button.textContent?.trim())).toEqual(['Agregar condición', 'Agregar procedimiento']); expect(detail.querySelector('.history-card')!.compareDocumentPosition(detail.querySelector('.tests-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); expect(detail.querySelector('.tests-card')!.compareDocumentPosition(detail.querySelector('.risks-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(detail.textContent).toContain('Valores ilustrativos · Sin evaluación clínica'); - expect(detail.querySelectorAll('app-paciente-riesgo-tabla tbody tr')).toHaveLength(4); + expect(detail.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(detail.querySelectorAll('app-paciente-riesgo-tabla table')).toHaveLength(0); + expect(detail.textContent).not.toContain('Valores ilustrativos'); volver(); expect(root.querySelector('app-paciente-detalle')).toBeNull(); expect(root.querySelector('form')!.closest('[hidden]')).toBeNull(); @@ -201,7 +204,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => { it('muestra ausencia de ficha sin asignar a otro paciente los antecedentes anteriores', () => { expect(abrir().textContent).toContain('Antecedente de tamizaje cervical'); - const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent; + const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent; volver(); const detail = abrir(2); expect(detail.textContent).toContain(pacientes[2].id_seudonimo); @@ -211,7 +214,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => { expect(detail.textContent).not.toContain('Colposcopia (demostración)'); expect(detail.textContent).toContain('Normal'); // Received study is still available. expect(detail.textContent).not.toContain('ficha sintética'); - expect(detail.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa); + expect(detail.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible); + expect(detail.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); expect(detail.querySelectorAll('app-paciente-riesgo-tabla [aria-selected]')).toHaveLength(0); http.expectNone(() => true); }); @@ -234,6 +238,24 @@ describe('Ficha individual desde Seguimiento CaCu', () => { http.expectNone(() => true); }); + it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => { + const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER); + const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo())); + try { + const detail = abrir(); + const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!; + expect(tarjeta.textContent).toContain('Información simulada'); + expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3); + expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo); + expect(obtener).toHaveBeenCalledExactlyOnceWith(); + volver(); + const otra = abrir(1); + expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); + http.expectNone(() => true); + } finally { obtener.mockRestore(); } + }); + it('distingue fuentes, nulos, falsos, ceros y listas sin registros sin inferir condiciones', () => { let detail = abrir(); expect(detail.textContent).toContain('Últimos resultados'); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts index 94fa339..dfdb390 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -218,8 +218,9 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => { abrir(2); - const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent; - expect(root.querySelectorAll('app-paciente-riesgo-tabla thead th')).toHaveLength(6); + const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent; + expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); + expect(riesgoNoDisponible).toContain('Riesgo individual no disponible para esta paciente.'); expect(root.textContent).toContain('Información no disponible'); for (const tipo of acciones) { const { ref } = await abrirDialogo(tipo.texto); @@ -230,7 +231,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { await confirmar(); } expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3); - expect(root.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa); + expect(root.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible); expect(root.textContent).toContain('Recomendaciones no disponibles'); volver(); abrir(0); expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0); @@ -257,7 +258,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { expect(root.textContent).toContain('Último resultado de VPH'); expect(root.textContent).toContain('NEGATIVO'); expect(root.textContent).toContain('VPH 16/18 detectado'); - expect(root.textContent).toContain('Valores ilustrativos · Sin evaluación clínica'); + expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); http.expectNone(() => true); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 49cfa6b..a5e3c7e 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -1,37 +1,68 @@ -

    Estimaciones de riesgo

    -

    Valores ilustrativos · Sin evaluación clínica

    +

    Riesgo individual CaCu

    @let lectura = estado(); @switch (lectura.tipo) { - @case ('cargando') {

    Cargando estimaciones de riesgo…

    } - @case ('vacio') {

    Sin estimaciones de riesgo disponibles.

    } - @case ('no-disponible') {

    Estimaciones de riesgo no disponibles.

    } - @case ('error') {

    No se pudieron cargar las estimaciones de riesgo.

    } + @case ('cargando') {

    Cargando riesgo individual…

    } + @case ('no-disponible') { +

    Riesgo individual no disponible para esta paciente.

    +

    La consulta de riesgo individual aún no está habilitada.

    + } + @case ('error') {

    No se pudo validar o cargar el riesgo individual.

    } @case ('disponible') { -
    - - - - - - - - - - - - @for (fila of lectura.datos.filas; track fila.id) { - - - - - - - - - } - -
    Ejemplos ilustrativos de estimaciones de riesgo
    Antecedentes precolposcopiaAntecedentes poscolposcopiaResultado VPH actualCitología actualRiesgo inmediato CIN3+ (%)Riesgo CIN3+ a 5 años (%)
    {{ fila.antecedentesPrecolposcopia }}{{ fila.antecedentesPoscolposcopia }}{{ fila.resultadoVphActual }}{{ fila.citologiaActual }}{{ fila.riesgoInmediatoPorcentaje === null ? 'No disponible' : (fila.riesgoInmediatoPorcentaje | number:'1.1-2') + ' %' }}{{ fila.riesgoCin3A5AnosPorcentaje === null ? 'No disponible' : (fila.riesgoCin3A5AnosPorcentaje | number:'1.1-2') + ' %' }}
    -
    +

    Información simulada · Entorno DEV · Sin evaluación clínica

    + @if (lectura.datos.cohorte; as cohorte) { +
    Cohorte
    + +
    + Variables del modelo PIMM +

    Códigos técnicos del modelo; no constituyen un diagnóstico.

    + +
    + } @else { +

    Sin membresía en la cohorte vigente.

    + } + @if (lectura.datos.riesgo; as riesgo) { +
    Modelo y evaluación
    + + @if (riesgo.horizontes.length) { +
    + + + + + + + + + + @for (h of riesgo.horizontes; track h.horizonte_anios) { + + + + + + + } + +
    Probabilidades simuladas por horizonte desde la fecha índice
    Horizonte (años)Probabilidad (%)Intervalo de confianza (%)Estado de evaluación
    {{ h.horizonte_anios }}{{ h.probabilidad * 100 | number:'1.0-4' }} %@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}
    +
    + } @else {

    Sin horizontes evaluados en el lote vigente.

    } + } @else {

    Sin riesgo disponible: no hay lote vigente.

    } } }

    Recomendaciones no disponibles.

    diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss index b5b49a3..90a76f3 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -1,15 +1,20 @@ :host { display: block; min-width: 0; max-width: 100%; } h4 { margin-block: 0 .5rem; font-size: 1.05rem; } -.illustrative-label, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; } +h5 { margin-block: 1rem .5rem; font-size: 1rem; } +.simulated-label { border-inline-start: 3px solid var(--issste-accent); padding: .75rem; font-weight: 600; } +.availability, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; } +.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr)); gap: 1rem; } +.metadata div { min-width: 0; } +dt { color: var(--issste-text-secondary); font-size: .9rem; } +dd { margin: .3rem 0 0; overflow-wrap: anywhere; } +summary { cursor: pointer; padding-block: .75rem; } .risk-scroll { width: 100%; min-width: 0; max-width: 100%; max-height: 28rem; overflow: auto; border: 1px solid var(--issste-border); border-radius: .5rem; box-sizing: border-box; } -.risk-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } -table { width: 100%; min-width: 58rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; } +.risk-scroll:focus-visible, summary:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } +table { width: 100%; min-width: 36rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; } caption { text-align: start; padding: .75rem; color: var(--issste-text-secondary); } -th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: break-word; } -th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; } -th:nth-child(-n+2) { min-width: 10rem; } -th:nth-child(n+3) { min-width: 7rem; } -td { background: var(--issste-surface); } -tbody tr:last-child td { border-bottom: 0; } -.percentage { font-variant-numeric: tabular-nums; white-space: nowrap; } +th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: anywhere; } +thead th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; } +tbody th, td { background: var(--issste-surface); } +tbody tr:last-child > * { border-bottom: 0; } +.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 065729e..ed650ff 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,6 +1,7 @@ import { Component, inject } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { PacienteRiesgoState } from './paciente-riesgo.state'; +import { tieneIntervalo } from './paciente-riesgo.validation'; @Component({ selector: 'app-paciente-riesgo-tabla', @@ -11,4 +12,5 @@ import { PacienteRiesgoState } from './paciente-riesgo.state'; }) export class PacienteRiesgoTabla { readonly estado = inject(PacienteRiesgoState).estado; + readonly tieneIntervalo = tieneIntervalo; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts deleted file mode 100644 index ef5e3bc..0000000 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { EstimacionesRiesgo } from './paciente-riesgo.models'; - -/** Invented values for layout only. Not copied from CCSM, validated or patient-derived. */ -export const ESTIMACIONES_RIESGO_ILUSTRATIVAS: EstimacionesRiesgo = { - origen: 'ilustrativo', - filas: [ - { id: 'ejemplo-1', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa', - resultadoVphActual: 'Positivo', citologiaActual: 'ASC-US / LSIL', riesgoInmediatoPorcentaje: 2.4, riesgoCin3A5AnosPorcentaje: 6.8 }, - { id: 'ejemplo-2', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa', - resultadoVphActual: 'Positivo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.8, riesgoCin3A5AnosPorcentaje: 3.2 }, - { id: 'ejemplo-3', antecedentesPrecolposcopia: 'Sin información de ejemplo', antecedentesPoscolposcopia: 'Sin información de ejemplo', - resultadoVphActual: 'Negativo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.2, riesgoCin3A5AnosPorcentaje: 0.9 }, - { id: 'ejemplo-4', antecedentesPrecolposcopia: 'Alto grado', antecedentesPoscolposcopia: 'Control de ejemplo', - resultadoVphActual: 'Positivo', citologiaActual: 'Alto grado', riesgoInmediatoPorcentaje: 7.6, riesgoCin3A5AnosPorcentaje: 12.4 }, - ], -}; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 84c738b..832a217 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -1,23 +1,50 @@ import { Observable } from 'rxjs'; -/** Presentation model, not a WebApi contract or a clinical decision rule. */ -export interface EstimacionRiesgo { - id: string; - antecedentesPrecolposcopia: string; - antecedentesPoscolposcopia: string; - resultadoVphActual: string; - citologiaActual: string; - riesgoInmediatoPorcentaje: number | null; - riesgoCin3A5AnosPorcentaje: number | null; +export type EstadoEvaluacionCacu = 'preliminary' | 'final'; +export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo'; + +export interface CohorteRiesgoCacu { + url: string; + version: string; + fecha_indice: string; + tipo_censura: TipoCensuraCacu | null; + c: number | null; + l: number | null; + r: number | null; + pap_0: string | null; + hpv_0: string | null; } -export interface EstimacionesRiesgo { - origen: 'ilustrativo'; - filas: readonly EstimacionRiesgo[]; + +export interface HorizonteRiesgoCacu { + horizonte_anios: number; + /** Transport values remain probabilities in [0, 1], never percentages. */ + probabilidad: number; + ic_bajo?: number | null; + ic_alto?: number | null; + estado: EstadoEvaluacionCacu; } -/** No patient input: these examples must never be matched to a selected patient. */ + +export interface LoteRiesgoCacu { + lote_id: number; + modelo_nombre: string; + modelo_version: string; + evaluado_en: string; + estado_lote: EstadoEvaluacionCacu; + horizontes: HorizonteRiesgoCacu[]; +} + +/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */ +export interface RiesgoPacienteCacu { + simulado: true; + cohorte: CohorteRiesgoCacu | null; + riesgo: LoteRiesgoCacu | null; +} + +/** Deliberately no patient argument until secure identity resolution is authorized. */ export interface PacienteRiesgoProvider { - obtener(): Observable; + obtener(): Observable; } + export type PacienteRiesgoEstado = - | { tipo: 'cargando' | 'vacio' | 'no-disponible' | 'error' } - | { tipo: 'disponible'; datos: EstimacionesRiesgo }; + | { tipo: 'cargando' | 'no-disponible' | 'error' } + | { tipo: 'disponible'; datos: RiesgoPacienteCacu }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 16b95b8..c04a30a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -1,14 +1,8 @@ -import { Injectable, InjectionToken, inject } from '@angular/core'; -import { defer, of } from 'rxjs'; -import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures'; +import { InjectionToken } from '@angular/core'; +import { of } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; -@Injectable({ providedIn: 'root' }) -export class PacienteRiesgoIlustrativoProvider implements PacienteRiesgoProvider { - obtener() { return defer(() => of(structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS))); } -} - -// Future adapters can replace this token; no HTTP route or patient matching is assumed. +// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization. export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { - providedIn: 'root', factory: () => inject(PacienteRiesgoIlustrativoProvider), + providedIn: 'root', factory: () => ({ obtener: () => of(null) }), }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index affe99c..1cee25a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -2,26 +2,12 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { of, Subject, throwError } from 'rxjs'; -import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures'; -import { EstimacionesRiesgo, PacienteRiesgoProvider } from './paciente-riesgo.models'; -import { PACIENTE_RIESGO_PROVIDER, PacienteRiesgoIlustrativoProvider } from './paciente-riesgo.provider'; +import { PacienteRiesgoProvider } from './paciente-riesgo.models'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; -describe('P0-C.2: proveedor ilustrativo independiente', () => { - it('lee sin HttpClient ni paciente y devuelve copias independientes del fixture', () => { - const provider = TestBed.inject(PacienteRiesgoIlustrativoProvider); - const baseline = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS); - provider.obtener().subscribe(data => { - expect(data).toEqual(baseline); - data.filas[0].riesgoInmediatoPorcentaje = 99; - }); - provider.obtener().subscribe(data => expect(data).toEqual(baseline)); - expect(ESTIMACIONES_RIESGO_ILUSTRATIVAS).toEqual(baseline); - expect(baseline.filas).toHaveLength(4); - }); -}); - -describe('P0-C.2: tabla accesible y estados de lectura', () => { +describe('RIESGO-CACU-02: presentación y aislamiento', () => { function setup(provider?: PacienteRiesgoProvider) { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), ...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] }); @@ -29,67 +15,137 @@ describe('P0-C.2: tabla accesible y estados de lectura', () => { fixture.detectChanges(); return fixture; } - afterEach(() => { TestBed.inject(HttpTestingController).verify(); }); - it('renderiza seis encabezados, cuatro filas sin selección y porcentajes solo ilustrativos', () => { - const f = setup(), root: HTMLElement = f.nativeElement; - expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).toEqual([ - 'Antecedentes precolposcopia', 'Antecedentes poscolposcopia', 'Resultado VPH actual', 'Citología actual', - 'Riesgo inmediato CIN3+ (%)', 'Riesgo CIN3+ a 5 años (%)', - ]); - expect([...root.querySelectorAll('th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); - expect(root.querySelectorAll('tbody tr')).toHaveLength(4); - expect(root.querySelectorAll('tbody td')).toHaveLength(24); - expect(root.querySelector('caption')!.textContent).toContain('ilustrativos'); - expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-ilustrativo'); - expect(root.querySelector('#riesgo-ilustrativo')!.textContent).toBe('Valores ilustrativos · Sin evaluación clínica'); - expect(root.querySelectorAll('[aria-selected], button, a, input')).toHaveLength(0); - expect([...root.querySelectorAll('.percentage')].every(td => td.textContent!.trim().endsWith('%'))).toBe(true); - expect(root.textContent).toContain('Recomendaciones no disponibles'); + afterEach(() => { TestBed.inject(HttpTestingController).expectNone(() => true); + TestBed.inject(HttpTestingController).verify(); }); - it('contiene el desplazamiento y conserva anchos mínimos y encabezados, con foco de teclado', () => { + + it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => { const f = setup(), root: HTMLElement = f.nativeElement; + expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(root.textContent).toContain('aún no está habilitada'); + expect(root.textContent).toContain('Recomendaciones no disponibles'); + expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/); + expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0); + TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull()); + }); + + it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => { + const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data)); + data.riesgo!.horizontes[1].estado = 'preliminary'; + const baseline = structuredClone(data); + const f = setup({ obtener }), root: HTMLElement = f.nativeElement; + expect(obtener).toHaveBeenCalledExactlyOnceWith(); + expect(root.querySelectorAll('thead th')).toHaveLength(4); + expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); + expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); + expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); + expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); + expect(root.textContent).toContain('Final (final)'); + expect(root.textContent).toContain('Preliminar (preliminary)'); + for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) { + expect(root.textContent).toContain(value); + } + expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado'); + expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV'); + expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); + // Internal batch key stays in the contract, never in a UI label. + expect(root.textContent).not.toContain('lote_id'); + expect(data).toEqual(baseline); + }); + + it('mantiene tabla desplazable, foco de teclado y detalles técnicos accesibles', () => { + const f = setup({ obtener: () => of(riesgoCacuEjemplo()) }), root: HTMLElement = f.nativeElement; const scroll = root.querySelector('.risk-scroll')!; - expect(scroll.tabIndex).toBe(0); expect(scroll.getAttribute('role')).toBe('region'); + expect(scroll.tabIndex).toBe(0); + expect(scroll.getAttribute('role')).toBe('region'); expect(scroll.getAttribute('aria-label')).toContain('tabla desplazable'); - // jsdom verifies the responsive CSS contract; viewport geometry still needs Chrome review. expect(getComputedStyle(scroll).overflow).toBe('auto'); expect(getComputedStyle(scroll).maxWidth).toBe('100%'); - expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('58rem'); - expect(getComputedStyle(root.querySelector('th')!).position).toBe('sticky'); + expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); + expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky'); + expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM'); + expect(root.textContent).toContain('no constituyen un diagnóstico'); }); - it('sustituye el fixture por inyección sin calcular porcentajes ni convertir null en cero', () => { - const data = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS); - data.filas = [{ ...data.filas[0], riesgoInmediatoPorcentaje: 0, riesgoCin3A5AnosPorcentaje: null }]; - const obtener = vi.fn(() => of(data)), f = setup({ obtener }); - expect(obtener).toHaveBeenCalledExactlyOnceWith(); - const cells = [...f.nativeElement.querySelectorAll('.percentage')] as HTMLElement[]; - expect(cells.map(c => c.textContent)).toEqual(['0.0 %', 'No disponible']); - TestBed.inject(HttpTestingController).expectNone(() => true); + + it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { + const data = riesgoCacuEjemplo(); + data.riesgo!.estado_lote = 'preliminary'; + data.riesgo!.horizontes = [ + { horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' }, + { horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' }, + { horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' }, + ]; + const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; + expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); + expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); + expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']); + expect(root.textContent).toContain('Preliminar (preliminary)'); }); - it.each([ - { data: { origen: 'ilustrativo', filas: [] } as EstimacionesRiesgo, text: 'Sin estimaciones de riesgo disponibles.' }, - { data: null, text: 'Estimaciones de riesgo no disponibles.' }, - ])('representa ausencia explícita: $text', ({ data, text }) => { + + it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => { + const data = riesgoCacuEjemplo(); + data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null }; const f = setup({ obtener: () => of(data) }); - expect(f.nativeElement.textContent).toContain(text); - expect(f.nativeElement.querySelector('table')).toBeNull(); - expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); + const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent); + expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']); + expect(f.nativeElement.textContent).not.toMatch(/undefined|null/); }); - it('distingue carga y error sin filtrar mensajes internos, y cancela al desmontarse', () => { - const source = new Subject(); - const f = setup({ obtener: () => source }); - expect(f.nativeElement.textContent).toContain('Cargando estimaciones de riesgo'); - source.error(new Error('private')); f.detectChanges(); - expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudieron cargar'); - expect(f.nativeElement.textContent).not.toContain('private'); + + it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => { + const data = riesgoCacuEjemplo(); + if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null; + if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null; + if (caso === 'horizontes') data.riesgo!.horizontes = []; + const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; + if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente'); + if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente'); + if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados'); + if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull(); + expect(root.textContent).toContain('Información simulada'); + expect(root.textContent).toContain('Recomendaciones no disponibles'); + }); + + it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => { + const data = { ...riesgoCacuEjemplo(), simulado }; + const f = setup({ obtener: () => of(data) }); + expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); + expect(f.nativeElement.textContent).not.toContain('modelo-cacu'); expect(f.nativeElement.querySelector('table')).toBeNull(); + }); + + it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => { + const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12; + const f = setup({ obtener: () => of(data) }); + expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); + expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0); + }); + + it('representa carga y cancela la suscripción al desmontarse', () => { + const source = new Subject(), f = setup({ obtener: () => source }); + expect(f.nativeElement.textContent).toContain('Cargando riesgo individual'); + expect(source.observed).toBe(true); f.destroy(); expect(source.observed).toBe(false); }); - it('un error inmediato del adaptador también mantiene las recomendaciones ausentes', () => { - const f = setup({ obtener: () => throwError(() => new Error('private')) }); + + it('aísla estado y fixture entre instancias sin reutilizar información', () => { + const source = new Subject(), f = setup({ obtener: () => source }); + const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges(); + data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges(); + expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); + f.destroy(); + const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges(); + expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); + expect(otra.nativeElement.querySelector('table')).toBeNull(); + expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08); + otra.destroy(); expect(source.observed).toBe(false); + }); + + it.each(['observable', 'sincrono'])('oculta detalles internos del error %s', tipo => { + const error = new Error('private pac_id=4821'); + const f = setup({ obtener: () => { if (tipo === 'sincrono') throw error; return throwError(() => error); } }); + expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudo validar o cargar'); + expect(f.nativeElement.textContent).not.toMatch(/private|4821|pac_id/); expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); - expect(f.nativeElement.textContent).not.toContain('private'); - TestBed.inject(HttpTestingController).expectNone(() => true); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index 23efcd8..5a109fa 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -1,14 +1,16 @@ import { inject, Injectable } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; -import { catchError, map, of } from 'rxjs'; +import { catchError, defer, map, of } from 'rxjs'; import { PacienteRiesgoEstado } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { riesgoPacienteResponse } from './paciente-riesgo.validation'; @Injectable() export class PacienteRiesgoState { - readonly estado = toSignal(inject(PACIENTE_RIESGO_PROVIDER).obtener().pipe( + private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); + readonly estado = toSignal(defer(() => this.provider.obtener()).pipe( map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } - : datos.filas.length ? { tipo: 'disponible', datos } : { tipo: 'vacio' }), + : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), catchError(() => of({ tipo: 'error' })), ), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado }); } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts new file mode 100644 index 0000000..511c042 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -0,0 +1,21 @@ +import { RiesgoPacienteCacu } from './paciente-riesgo.models'; + +/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */ +export function riesgoCacuEjemplo(): RiesgoPacienteCacu { + return { + simulado: true, + cohorte: { + url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15', + tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO', + }, + riesgo: { + lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', + evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', + horizontes: [ + { horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' }, + { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' }, + { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' }, + ], + }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts new file mode 100644 index 0000000..7716d4a --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts @@ -0,0 +1,123 @@ +import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; +import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation'; +import { TipoCensuraCacu } from './paciente-riesgo.models'; + +describe('RIESGO-CACU-02: frontera del contrato DEV', () => { + it('conserva todos los campos del ejemplo externo y copia los objetos', () => { + const entrada = riesgoCacuEjemplo(); + const salida = riesgoPacienteResponse(entrada); + expect(salida).toEqual(entrada); + salida.riesgo!.horizontes[0].probabilidad = 0; + salida.cohorte!.c = -999; + expect(entrada).toEqual(riesgoCacuEjemplo()); + }); + + it('admite campos aditivos sin eliminarlos ni renombrarlos', () => { + const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } }; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + }); + + it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])( + 'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => { + const entrada = riesgoCacuEjemplo(); + entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null; + expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo); + }, + ); + + it('preserva los nulos independientes y el sentinel basal del contrato', () => { + const entrada = riesgoCacuEjemplo(); + entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null }; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + entrada.riesgo = null; + entrada.cohorte.c = null; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + entrada.cohorte = null; + expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null }); + }); + + it('no impone dependencia entre cohorte nullable y riesgo nullable', () => { + const entrada = riesgoCacuEjemplo(); + entrada.cohorte = null; + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + }); + + it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => { + const entrada = riesgoCacuEjemplo(); + entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({ + horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final', + })); + expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + }); + + it.each([ + {}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null }, + { ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 }, + ])('conserva IC incompletos sin generar límites: %j', limites => { + const entrada = riesgoCacuEjemplo(); + entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }]; + const salida = riesgoPacienteResponse(entrada); + expect(salida).toEqual(entrada); + expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false); + }); + + it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => { + const entrada = riesgoCacuEjemplo(); + entrada.riesgo!.estado_lote = 'preliminary'; + entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }]; + const salida = riesgoPacienteResponse(entrada); + expect(salida).toEqual(entrada); + expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true); + }); + + const invalidos: [string, (v: any) => void][] = [ + ['no simulado', v => v.simulado = false], + ['simulado string', v => v.simulado = 'true'], + ['sin simulado', v => delete v.simulado], + ['sin cohorte', v => delete v.cohorte], + ['sin riesgo', v => delete v.riesgo], + ['cohorte lista', v => v.cohorte = []], + ['URL ajena', v => v.cohorte.url = 'otra'], + ['versión ausente', v => delete v.cohorte.version], + ['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'], + ['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'], + ['basal string', v => v.cohorte.c = '0'], + ['variable no finita', v => v.cohorte.l = Infinity], + ['variable omitida', v => delete v.cohorte.r], + ['pap no textual', v => v.cohorte.pap_0 = 5], + ['hpv no textual', v => v.cohorte.hpv_0 = false], + ['lote fraccionario', v => v.riesgo.lote_id = 1.5], + ['lote string', v => v.riesgo.lote_id = '12'], + ['modelo omitido', v => delete v.riesgo.modelo_nombre], + ['versión no textual', v => v.riesgo.modelo_version = 2], + ['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'], + ['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'], + ['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'], + ['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'], + ['sin horizontes', v => delete v.riesgo.horizontes], + ['horizontes nulos', v => v.riesgo.horizontes = null], + ['horizonte nulo', v => v.riesgo.horizontes[0] = null], + ['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'], + ['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN], + ['horizontes desordenados', v => v.riesgo.horizontes.reverse()], + ['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1], + ['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01], + ['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01], + ['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'], + ['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null], + ['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN], + ['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'], + ['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01], + ['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01], + ['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'], + ['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })], + ['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07], + ]; + it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => { + const entrada = riesgoCacuEjemplo(); mutar(entrada); + expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida'); + }); + it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => { + expect(() => riesgoPacienteResponse(entrada)).toThrow(); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts new file mode 100644 index 0000000..e26ba5a --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -0,0 +1,58 @@ +import { isoDate } from '../cacu-seguimiento.models'; +import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const nullableNumber = (v: unknown) => v === null || finite(v); +const nullableText = (v: unknown) => v === null || typeof v === 'string'; +const text = (v: unknown) => typeof v === 'string'; +const estado = (v: unknown) => v === 'preliminary' || v === 'final'; +const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1; +const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo']; + +function utcTimestamp(v: unknown) { + return typeof v === 'string' + && /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v) + && isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v)); +} + +function cohorteValida(v: unknown) { + return v === null || record(v) + && v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice']) + && (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string)) + && nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r']) + && nullableText(v['pap_0']) && nullableText(v['hpv_0']); +} + +function horizonteValido(v: unknown) { + if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false; + for (const key of ['ic_bajo', 'ic_alto']) { + if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false; + } + // Missing/null endpoints are preserved. A complete interval must contain the probability. + return !(probability(v['ic_bajo']) && probability(v['ic_alto'])) + || v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto']; +} + +function riesgoValido(v: unknown) { + if (v === null) return true; + if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version']) + || !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false; + const horizontes = v['horizontes']; + return horizontes.every(horizonteValido) + && horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']); +} + +/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */ +export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu { + if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) { + throw new Error('Respuesta de riesgo individual DEV inválida'); + } + return structuredClone(v) as unknown as RiesgoPacienteCacu; +} + +/** Presentation helper: an incomplete interval must never become a fabricated range. */ +export function tieneIntervalo(h: HorizonteRiesgoCacu): boolean { + return probability(h.ic_bajo) && probability(h.ic_alto) + && h.ic_bajo <= h.probabilidad && h.probabilidad <= h.ic_alto; +}