Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9639423a32 | |||
| 1fe88dfb45 | |||
| 9cc67c0ef2 | |||
| 1eda9eea29 | |||
| 2cf3a5a40d | |||
| 30946823c4 | |||
| d946228319 | |||
| 8cb3c97b80 | |||
| 1fc23bd0bd | |||
| 11337679dc | |||
| 4685a91a7c | |||
| 69afcc7fdb | |||
| 9fcc65d84f | |||
| c4faa7d9f6 | |||
| 98d0614d80 | |||
| 35e1bc33d3 | |||
| f96fe97ed6 | |||
| fe9442237b | |||
| 61cdf5b72e | |||
| 37c4eacf84 | |||
| 41be0c343f | |||
| ecf2778f1a | |||
| 9c012e9bb4 | |||
| 91832cc6ff | |||
| ea91b31b17 | |||
| ae5e4c5db5 | |||
| b1c4b78f32 | |||
| a66205b725 |
@@ -42,3 +42,9 @@ __screenshots__/
|
||||
# System files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Temporary UX reports and one-off static checks
|
||||
/UX-*-informe.md
|
||||
/scripts/ux06b-resources.test.mjs
|
||||
/scripts/ux06c-presentation.test.mjs
|
||||
/scripts/ux06d-presentation.test.mjs
|
||||
|
||||
+3
-1
@@ -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"
|
||||
|
||||
Generated
+7
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -0,0 +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 }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -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()
|
||||
]
|
||||
};
|
||||
|
||||
+17
-4
@@ -1,7 +1,20 @@
|
||||
<mat-toolbar color="primary">
|
||||
<span>{{ title }}</span>
|
||||
</mat-toolbar>
|
||||
<a class="skip-link" href="#contenido-principal">Saltar al contenido principal</a>
|
||||
<header class="institutional-header">
|
||||
<div class="header-content">
|
||||
<img class="institutional-logo" src="images/LogoISSSTELEON.png" alt="ISSSTELEON"
|
||||
width="1125" height="358" />
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<main #mainContent id="contenido-principal" tabindex="-1">
|
||||
<router-outlet />
|
||||
</main>
|
||||
|
||||
@if (showBackToTop()) {
|
||||
<button class="back-to-top" type="button" aria-label="Volver al inicio" (click)="backToTop()">
|
||||
<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M12 19V5m-7 7 7-7 7 7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { routes } from './app.routes';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Router, provideRouter } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresPage } from './features/indicadores/indicadores-page';
|
||||
it('permite acceso directo a /indicadores sin guard ni autenticación', async () => {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
|
||||
const harness = await RouterTestingHarness.create();
|
||||
await harness.navigateByUrl('/indicadores', IndicadoresPage);
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
||||
expect(harness.routeNativeElement?.textContent).toContain('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();
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||
|
||||
export const routes: Routes = [];
|
||||
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
||||
export const routes: Routes = [
|
||||
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
|
||||
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, data: { dominio }, loadComponent: loadIndicadores })),
|
||||
];
|
||||
|
||||
+108
-2
@@ -1,3 +1,109 @@
|
||||
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) 5.5rem;
|
||||
scroll-margin-top: var(--issste-header-clearance);
|
||||
}
|
||||
|
||||
.skip-link {
|
||||
position: fixed;
|
||||
top: var(--issste-space-2);
|
||||
left: var(--issste-page-gutter);
|
||||
z-index: 101;
|
||||
transform: translateY(-200%);
|
||||
padding: var(--issste-space-2) var(--issste-space-3);
|
||||
color: var(--issste-surface);
|
||||
background: var(--issste-text);
|
||||
border-radius: var(--issste-radius);
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
@media (max-width: 550px) {
|
||||
.header-content {
|
||||
gap: var(--issste-space-2);
|
||||
min-height: 64px;
|
||||
}
|
||||
|
||||
.institutional-logo {
|
||||
width: 145px;
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
|
||||
.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; }
|
||||
|
||||
+107
-11
@@ -1,25 +1,121 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
describe('App — UX-06D volver al inicio', () => {
|
||||
let scrollY: number;
|
||||
beforeEach(() => {
|
||||
scrollY = 0;
|
||||
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => scrollY);
|
||||
TestBed.configureTestingModule({ imports: [App], providers: [provideRouter([])] });
|
||||
});
|
||||
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function render() {
|
||||
const fixture = TestBed.createComponent(App);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
function scroll(fixture: ReturnType<typeof render>, position: number) {
|
||||
scrollY = position;
|
||||
window.dispatchEvent(new Event('scroll'));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
it('oculta al inicio y en el umbral, muestra después y vuelve a ocultar al subir', () => {
|
||||
const fixture = render();
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
|
||||
scroll(fixture, 400);
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
|
||||
scroll(fixture, 401);
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).not.toBeNull();
|
||||
scroll(fixture, 0);
|
||||
expect(fixture.nativeElement.querySelector('.back-to-top')).toBeNull();
|
||||
});
|
||||
it('reconoce una posición restaurada al montar el shell', () => {
|
||||
scrollY = 900;
|
||||
expect(render().nativeElement.querySelector('.back-to-top')).not.toBeNull();
|
||||
});
|
||||
it.each([false, true])('activa un botón nativo y respeta movimiento reducido=%s', reduced => {
|
||||
const matchMedia = vi.fn().mockReturnValue({ matches: reduced } as MediaQueryList);
|
||||
vi.stubGlobal('matchMedia', matchMedia);
|
||||
const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
|
||||
const fixture = render();
|
||||
scroll(fixture, 900);
|
||||
const button = fixture.nativeElement.querySelector('.back-to-top') as HTMLButtonElement;
|
||||
const main = fixture.nativeElement.querySelector('main') as HTMLElement;
|
||||
const focus = vi.spyOn(main, 'focus');
|
||||
expect(button.type).toBe('button');
|
||||
expect(button.tabIndex).toBe(0);
|
||||
expect(button.getAttribute('aria-label')).toBe('Volver al inicio');
|
||||
expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
|
||||
button.click();
|
||||
expect(matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)');
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: reduced ? 'instant' : 'smooth' });
|
||||
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
|
||||
// Native Enter/Space activation is checked in Chrome, not emulated by jsdom.
|
||||
});
|
||||
it('registra un listener pasivo y elimina exactamente el mismo al destruir', () => {
|
||||
const add = vi.spyOn(window, 'addEventListener');
|
||||
const remove = vi.spyOn(window, 'removeEventListener');
|
||||
const fixture = render();
|
||||
const registration = add.mock.calls.find(call => call[0] === 'scroll')!;
|
||||
expect(registration[2]).toEqual({ passive: true });
|
||||
fixture.destroy();
|
||||
expect(remove).toHaveBeenCalledWith('scroll', registration[1]);
|
||||
scrollY = 900;
|
||||
window.dispatchEvent(new Event('scroll'));
|
||||
expect(fixture.componentInstance.showBackToTop()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
+25
-5
@@ -1,13 +1,33 @@
|
||||
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';
|
||||
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';
|
||||
export class App implements OnInit, OnDestroy {
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
readonly showBackToTop = signal(false);
|
||||
@ViewChild('mainContent') private mainContent?: ElementRef<HTMLElement>;
|
||||
private readonly browserWindow = inject(DOCUMENT).defaultView;
|
||||
private readonly updateScroll = () => this.showBackToTop.set((this.browserWindow?.scrollY ?? 0) > 400);
|
||||
|
||||
ngOnInit() {
|
||||
this.updateScroll();
|
||||
this.browserWindow?.addEventListener('scroll', this.updateScroll, { passive: true });
|
||||
}
|
||||
|
||||
backToTop() {
|
||||
const reducedMotion = this.browserWindow?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
// Keep keyboard focus near the destination when the floating button disappears.
|
||||
this.mainContent?.nativeElement.focus({ preventScroll: true });
|
||||
this.browserWindow?.scrollTo({ top: 0, behavior: reducedMotion ? 'instant' : 'smooth' });
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.browserWindow?.removeEventListener('scroll', this.updateScroll);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
export interface SeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
grupo_edad: string;
|
||||
estatus: SeguimientoStatus;
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
}
|
||||
export interface SeguimientoResponse {
|
||||
simulado: boolean;
|
||||
corte: string;
|
||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
filtros: { estatus: string | null };
|
||||
estatus_disponibles: SeguimientoStatus[];
|
||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||
items: SeguimientoPaciente[];
|
||||
}
|
||||
export function isoDate(value: unknown): value is string {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return false;
|
||||
const date = new Date(value + 'T00:00:00Z');
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= 200;
|
||||
}
|
||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
// The current authorization covers demonstration records only. Validate this
|
||||
// before passing any item to the component; real-patient activation is separate.
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
})) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CacuSeguimientoService {
|
||||
private readonly http = inject(HttpClient);
|
||||
consultar(query: SeguimientoQuery) {
|
||||
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||
if (query.corte) params = params.set('corte', query.corte);
|
||||
if (query.estatus) params = params.set('estatus', query.estatus);
|
||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import fixtureData from './fixtures/cacu_seguimiento.json';
|
||||
import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service';
|
||||
import { latestStudy } from './cacu-seguimiento.models';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
|
||||
describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers:[provideHttpClient(),provideHttpClientTesting()] });
|
||||
fixture=TestBed.createComponent(IndicadoresTracking); http=TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio','cacu'); fixture.componentRef.setInput('domainLabel','CaCu');
|
||||
});
|
||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||
it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => {
|
||||
fixture.detectChanges(); http.expectNone(()=>true); respond();
|
||||
const root:HTMLElement=fixture.nativeElement;
|
||||
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||
expect(root.textContent).toContain('Ventana consultada:');
|
||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||
expect(root.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');
|
||||
req.flush({...fixtureData,ventana:{...fixtureData.ventana,meses:6},filtros:{estatus:'VIGILANCIA'}}); fixture.detectChanges();
|
||||
fixture.componentInstance.draft.meses=12; // Draft edits must not affect server pagination.
|
||||
fixture.componentInstance.navigate(2); req=http.expectOne(r=>r.url==='/cacu/seguimiento');
|
||||
expect(req.request.params.get('page')).toBe('2'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('corte')).toBe('2026-09-30');
|
||||
req.flush({...fixtureData,ventana:{...fixtureData.ventana,meses:6},filtros:{estatus:'VIGILANCIA'},paginacion:{...fixtureData.paginacion,page:2}});
|
||||
fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.componentInstance.data?.paginacion.page).toBe(2);
|
||||
});
|
||||
it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => {
|
||||
const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'});
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.componentInstance.status).toBe(code===404?'pending':'error'); fixture.componentInstance.retry();
|
||||
http.expectOne(r=>r.url==='/cacu/seguimiento').flush({...fixtureData,items:[],paginacion:{page:1,page_size:50,total_items:0,total_pages:0}});
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({}, {status:404,statusText:'Absent'}); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay registros');
|
||||
});
|
||||
it('no activa registros reales ni acepta respuestas malformadas', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow();
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow();
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
|
||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
||||
});
|
||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||
const service=TestBed.inject(CacuSeguimientoService);
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
});
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
{
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.2.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "estatus_seguimiento",
|
||||
"valores_estrato": [
|
||||
"VIGILANCIA",
|
||||
"POST_COLPOSCOPIA",
|
||||
"POST_TRATAMIENTO",
|
||||
"INFO_INSUFICIENTE"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"VIGILANCIA": "Vigilancia",
|
||||
"POST_COLPOSCOPIA": "Post colposcopia",
|
||||
"POST_TRATAMIENTO": "Post tratamiento",
|
||||
"INFO_INSUFICIENTE": "Información insuficiente"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 44,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"generado_en": "2026-10-22T20:26:40.633043+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "94749f578a4d901edf038bca0427e9975bac72de1a1fdea382f4de1d5eb7402b",
|
||||
"parametros_sha": "091ab456d7f51e865bf31e1fd4201d22a3acf9877f057d0473b4765c20095092",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"NORMAL",
|
||||
"ASC-US",
|
||||
"LIEBG",
|
||||
"ASC-H",
|
||||
"LIEAG",
|
||||
"CIS"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"calidad_insatisfactoria": "INSATISFACTORIO",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"periodo_inicio": "2025-07-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 1027,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 145,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 65,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 22,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 36,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "CIS",
|
||||
"n": 9,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 46,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 117,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 39,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 30,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 5,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 11,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 6,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "NORMAL",
|
||||
"n": 26,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-US",
|
||||
"n": 7,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEBG",
|
||||
"n": 7,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "NORMAL",
|
||||
"n": 192,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-US",
|
||||
"n": 20,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEBG",
|
||||
"n": 16,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEAG",
|
||||
"n": 9,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 12,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
{
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.2.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "grupo_edad",
|
||||
"valores_estrato": [
|
||||
"<25",
|
||||
"25-34",
|
||||
"35-44",
|
||||
"45-54",
|
||||
"55-64",
|
||||
"65+",
|
||||
"sin_dato"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"<25": "<25",
|
||||
"25-34": "25-34",
|
||||
"35-44": "35-44",
|
||||
"45-54": "45-54",
|
||||
"55-64": "55-64",
|
||||
"65+": "65+",
|
||||
"sin_dato": "Sin dato"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 44,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"generado_en": "2026-10-22T20:26:40.633043+00:00",
|
||||
"kit_version": "0.8.0",
|
||||
"toml_sha": "94749f578a4d901edf038bca0427e9975bac72de1a1fdea382f4de1d5eb7402b",
|
||||
"parametros_sha": "091ab456d7f51e865bf31e1fd4201d22a3acf9877f057d0473b4765c20095092",
|
||||
"parametros": {
|
||||
"sql": {
|
||||
"_catalogo": [
|
||||
"NORMAL",
|
||||
"ASC-US",
|
||||
"LIEBG",
|
||||
"ASC-H",
|
||||
"LIEAG",
|
||||
"CIS"
|
||||
],
|
||||
"_grupos": [
|
||||
"TOTAL"
|
||||
],
|
||||
"calidad_insatisfactoria": "INSATISFACTORIO",
|
||||
"fecha_corte": "2026-10-22",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"periodo_inicio": "2025-07-01"
|
||||
},
|
||||
"umbral_supresion": 5
|
||||
}
|
||||
}
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "NORMAL",
|
||||
"n": 50,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-US",
|
||||
"n": null,
|
||||
"orden": 1,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEBG",
|
||||
"n": null,
|
||||
"orden": 2,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "NORMAL",
|
||||
"n": 320,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-US",
|
||||
"n": 32,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEBG",
|
||||
"n": 21,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEAG",
|
||||
"n": 13,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 15,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "NORMAL",
|
||||
"n": 441,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-US",
|
||||
"n": 25,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEBG",
|
||||
"n": 21,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEAG",
|
||||
"n": 9,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 16,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "NORMAL",
|
||||
"n": 365,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-US",
|
||||
"n": 36,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEBG",
|
||||
"n": 21,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEAG",
|
||||
"n": 16,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 23,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "NORMAL",
|
||||
"n": 245,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-US",
|
||||
"n": 23,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEBG",
|
||||
"n": 10,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-H",
|
||||
"n": 5,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEAG",
|
||||
"n": 5,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 11,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "NORMAL",
|
||||
"n": 74,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "ASC-US",
|
||||
"n": 6,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "LIEBG",
|
||||
"n": null,
|
||||
"orden": 2,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "65+",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "NORMAL",
|
||||
"n": 10,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "ASC-US",
|
||||
"n": null,
|
||||
"orden": 1,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "LIEBG",
|
||||
"n": null,
|
||||
"orden": 2,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "ASC-H",
|
||||
"n": null,
|
||||
"orden": 3,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "LIEAG",
|
||||
"n": null,
|
||||
"orden": 4,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "CIS",
|
||||
"n": null,
|
||||
"orden": 5,
|
||||
"suprimido": 1
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "sin_dato",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": null,
|
||||
"orden": 6,
|
||||
"suprimido": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
{
|
||||
"simulado": true,
|
||||
"corte": "2026-09-30",
|
||||
"ventana": {
|
||||
"meses": 3,
|
||||
"desde": "2026-07-01",
|
||||
"hasta": "2026-09-30"
|
||||
},
|
||||
"filtros": {
|
||||
"estatus": null
|
||||
},
|
||||
"estatus_disponibles": [
|
||||
{
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
{
|
||||
"codigo": "POST_COLPOSCOPIA",
|
||||
"etiqueta": "Post colposcopia"
|
||||
},
|
||||
{
|
||||
"codigo": "POST_TRATAMIENTO",
|
||||
"etiqueta": "Post tratamiento"
|
||||
},
|
||||
{
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
}
|
||||
],
|
||||
"reglas": [
|
||||
{
|
||||
"clave": "cacu.seguimiento.marco",
|
||||
"valor": [
|
||||
"estatus"
|
||||
],
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.precedencia",
|
||||
"valor": [
|
||||
"POST_TRATAMIENTO",
|
||||
"POST_COLPOSCOPIA",
|
||||
"INFO_INSUFICIENTE",
|
||||
"VIGILANCIA"
|
||||
],
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.ventana_meses",
|
||||
"valor": 3,
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.fecha_estudio",
|
||||
"valor": "toma",
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.estudios",
|
||||
"valor": [
|
||||
"citologia",
|
||||
"vph"
|
||||
],
|
||||
"estado": "provisional"
|
||||
},
|
||||
{
|
||||
"clave": "cacu.seguimiento.resultado_mostrado",
|
||||
"valor": "ultimo",
|
||||
"estado": "provisional"
|
||||
}
|
||||
],
|
||||
"paginacion": {
|
||||
"page": 1,
|
||||
"page_size": 10,
|
||||
"total_items": 1284,
|
||||
"total_pages": 129
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id_seudonimo": "P-4BC9B9E8F4",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": null,
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-09-28",
|
||||
"resultado": "NEGATIVO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-2C9E494F5D",
|
||||
"grupo_edad": "65+",
|
||||
"estatus": {
|
||||
"codigo": "POST_COLPOSCOPIA",
|
||||
"etiqueta": "Post colposcopia"
|
||||
},
|
||||
"ultima_citologia": null,
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-09-23",
|
||||
"resultado": "POSITIVO",
|
||||
"genotipo_16_18": true
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-E470F3442F",
|
||||
"grupo_edad": "35-44",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-09-18",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-09-08",
|
||||
"resultado": "NEGATIVO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-24A2B1D6B5",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-09-13",
|
||||
"bethesda": "LIEAG",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": 23,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-9E0E15AB5C",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "POST_COLPOSCOPIA",
|
||||
"etiqueta": "Post colposcopia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-08-22",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-07-14",
|
||||
"resultado": "NEGATIVO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-45A44DFE6F",
|
||||
"grupo_edad": "<25",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-08-04",
|
||||
"bethesda": null,
|
||||
"calidad": "INSATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-08-15",
|
||||
"resultado": "POSITIVO",
|
||||
"genotipo_16_18": false
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-367397F2CE",
|
||||
"grupo_edad": "65+",
|
||||
"estatus": {
|
||||
"codigo": "POST_TRATAMIENTO",
|
||||
"etiqueta": "Post tratamiento"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-08-05",
|
||||
"bethesda": "ASC-H",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": 41,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-2FB7CB6653",
|
||||
"grupo_edad": "45-54",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-07-24",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-517CD5E39B",
|
||||
"grupo_edad": "55-64",
|
||||
"estatus": {
|
||||
"codigo": "INFO_INSUFICIENTE",
|
||||
"etiqueta": "Información insuficiente"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-07-17",
|
||||
"bethesda": "ASC-US",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": null,
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
},
|
||||
{
|
||||
"id_seudonimo": "P-E1157546FD",
|
||||
"grupo_edad": "25-34",
|
||||
"estatus": {
|
||||
"codigo": "VIGILANCIA",
|
||||
"etiqueta": "Vigilancia"
|
||||
},
|
||||
"ultima_citologia": {
|
||||
"fecha": "2026-07-01",
|
||||
"bethesda": "NORMAL",
|
||||
"calidad": "SATISFACTORIO"
|
||||
},
|
||||
"ultimo_vph": {
|
||||
"fecha": "2026-07-01",
|
||||
"resultado": "INDETERMINADO",
|
||||
"genotipo_16_18": null
|
||||
},
|
||||
"dias_toma_diagnostico": null,
|
||||
"prioridad": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresMemory, GlobalApplied } from './indicadores-memory';
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorCatalogCard>>;
|
||||
let http: HttpTestingController;
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); create(['f', 'g']);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function create(figuras: string[], domain = 'cacu') {
|
||||
fixture = TestBed.createComponent(IndicadorCatalogCard);
|
||||
fixture.componentRef.setInput('dominio', domain);
|
||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
}
|
||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||
it.each(['C1', 'C2', 'C3r'])('UX-07A omite IDs y contrato %s y conserva título y contador', contrato => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'K05_eeg_20_minutos', titulo: 'EEG con ≥ 20 min de registro', contrato,
|
||||
figuras: ['fig_c1_grupos', 'fig_c1_puntos'], tipos_periodo: ['semestre'] });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
||||
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
||||
// The internal panel heading is deliberately visually hidden and retains identity.
|
||||
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
||||
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
||||
expect(copy.textContent).not.toMatch(/K05_eeg_20_minutos|Contrato|fig_c1_/);
|
||||
expect(fixture.componentInstance.indicador.id).toBe('K05_eeg_20_minutos');
|
||||
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
|
||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
||||
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
|
||||
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
|
||||
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
|
||||
]);
|
||||
http.expectNone(() => true);
|
||||
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
||||
for (const [id, label] of [
|
||||
['fig_c2_apiladas', 'Barras apiladas'],
|
||||
['fig_c2_barras', 'Barras'],
|
||||
['fig_c2_donas', 'Donas'],
|
||||
['fig_c9_futura', 'Representación 5'],
|
||||
]) {
|
||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
||||
const pending = request(id);
|
||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||
expect(pending.request.params.get('tema')).toBe('claro');
|
||||
expect(pending.request.params.get('periodos')).toBe('2025-S1');
|
||||
pending.flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.selectedFigure).toBe(id);
|
||||
expect(TestBed.inject(IndicadoresMemory).figure('cacu', 'i')).toBe(id);
|
||||
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`);
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_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<HTMLButtonElement>;
|
||||
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);
|
||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||
request('f').flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].componentInstance.result().figure.data[0].y).toEqual([7]); http.expectNone(() => true);
|
||||
});
|
||||
it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva carga diferida', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||
request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g']);
|
||||
expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.visible).toBe(false); http.expectNone(() => true);
|
||||
fixture.componentInstance.setVisible(true); fixture.detectChanges(); request('g').flush({ data: [], layout: {} });
|
||||
fixture.destroy(); create(['f', 'g'], 'cama'); expect(fixture.componentInstance.selectedFigure).toBe('f');
|
||||
fixture.destroy(); create(['f']); expect(fixture.componentInstance.selectedFigure).toBe('f');
|
||||
});
|
||||
it('cambio de aplicado conserva elección y consulta sólo su representación; fuera de vista cancela revisión obsoleta', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} });
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); fixture.detectChanges();
|
||||
const current = request('g'); expect(current.request.params.get('periodos')).toBe('2025-S2'); http.expectNone(r => r.url.endsWith('/figuras/f'));
|
||||
fixture.componentInstance.setVisible(false); fixture.detectChanges();
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 3 }); fixture.detectChanges(); expect(current.cancelled).toBe(true);
|
||||
expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
it('opciones ajenas al catálogo y selección repetida no consultan', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('bad'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.selectedFigure).toBe('f'); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
it('C2 sin magnitudes elimina la copia HTML de la nota y no cambia trazas Plotly', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigureCard] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
const fixture = TestBed.createComponent(IndicadorFigureCard);
|
||||
const figure = { data: [{ type: 'pie', values: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } };
|
||||
fixture.componentRef.setInput('state', { status: 'ready', figure, presentationFigure: structuredClone(figure) });
|
||||
fixture.componentRef.setInput('selected', { id: 'i', titulo: 'I', contrato: 'C2', figuras: ['fig_c2_donas'], tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(fixture.nativeElement.textContent).toContain('Los sectores');
|
||||
expect(figure.data[0].values).toEqual([null, null]); fixture.destroy();
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChanges, OnDestroy, output, untracked, ViewChild } from '@angular/core';
|
||||
import { catchError, of, Subscription } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
|
||||
import { dualFigures } from './indicadores-dual-figures';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ' · ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
<div [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
<p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p>
|
||||
@if (selectedFigure) {
|
||||
@if (!pair.length || otherFigures.length) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
||||
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
|
||||
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||
<div class="representation-panel">
|
||||
@if (isDual) { <h3>{{ figureDisplayName(figure, indicador.figuras) }}</h3> }
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else { <p role="status">El indicador no tiene figuras disponibles.</p> }
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: 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); 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; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
mat-form-field { width: 100%; margin-top: var(--issste-space-4); }
|
||||
.catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4);
|
||||
border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } }
|
||||
`,
|
||||
})
|
||||
export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
localSelection: DonutSelection = {};
|
||||
private selectionContext = '';
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private numericSubscription?: Subscription;
|
||||
private numericKey = '';
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private metadataSubscription?: Subscription;
|
||||
private metadataKey = '';
|
||||
metadata?: IndicadorMetadatos;
|
||||
private activatedKey = '';
|
||||
constructor() {
|
||||
effect(() => {
|
||||
this.snapshots.expanded(); this.snapshots.retries();
|
||||
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
|
||||
});
|
||||
}
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
private updateNumeric() {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied);
|
||||
if (key !== this.activatedKey) {
|
||||
this.numericSubscription?.unsubscribe(); this.numericKey = '';
|
||||
if (this.visible) this.activatedKey = key;
|
||||
}
|
||||
if (this.activatedKey !== key || !this.snapshots.expanded()
|
||||
|| !filterCompatibility(this.applied, this.indicador.tipos_periodo).compatible) return;
|
||||
const attempt = JSON.stringify([key, this.snapshots.retries()]);
|
||||
if (this.numericKey === attempt) return;
|
||||
this.numericKey = attempt;
|
||||
this.numericSubscription?.unsubscribe();
|
||||
this.numericSubscription = this.snapshots.read(this.dominio, this.indicador, this.applied).subscribe();
|
||||
}
|
||||
ngOnDestroy() { this.numericSubscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() pinned = false;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
readonly pinChanged = output<void>();
|
||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||
readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private identity = '';
|
||||
visible = false;
|
||||
titleId = '';
|
||||
contentId = '';
|
||||
panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); }
|
||||
selectedFigure?: string;
|
||||
selectFigure(figure: string) {
|
||||
if (!this.indicador.figuras.includes(figure) || figure === this.selectedFigure) return;
|
||||
this.selectedFigure = this.pair.includes(figure) ? this.pair[0] : figure;
|
||||
this.memory.rememberFigure(this.dominio, this.indicador.id, figure);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnChanges() {
|
||||
const context = JSON.stringify([this.dominio, this.indicador.id, this.indicador.version, this.applied, this.tema]);
|
||||
if (context !== this.selectionContext) { this.localSelection = {}; this.selectionContext = context; }
|
||||
const remembered = this.memory.figure(this.dominio, this.indicador.id);
|
||||
const selected = remembered && this.indicador.figuras.includes(remembered) ? remembered : this.pair[0] ?? this.indicador.figuras[0];
|
||||
this.selectedFigure = this.pair.includes(selected) ? this.pair[0] : selected;
|
||||
const identity = indicatorIdentity(this.dominio, this.indicador.id);
|
||||
if (identity === this.identity) { this.updateNumeric(); return; }
|
||||
this.identity = identity;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadata = undefined;
|
||||
this.metadataKey = '';
|
||||
const id = identityElementId(identity);
|
||||
this.titleId = id + '-title';
|
||||
this.contentId = id + '-content';
|
||||
this.visible = false;
|
||||
this.updateNumeric();
|
||||
}
|
||||
setVisible(visible: boolean) {
|
||||
if (this.visible === visible) return;
|
||||
this.visible = visible;
|
||||
this.updateNumeric();
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
loadMetadata() {
|
||||
const key = JSON.stringify([this.dominio, this.indicador.id]);
|
||||
if (this.metadataKey === key) return;
|
||||
this.metadataKey = key;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.indicators.metadatos(this.dominio, this.indicador.id)
|
||||
.pipe(catchError(() => of(undefined))).subscribe(value => {
|
||||
if (this.metadataKey !== key) return;
|
||||
if (!value) this.metadataKey = '';
|
||||
this.metadata = value;
|
||||
this.changeDetector.markForCheck();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
@if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ' · ' + dominio + ' · ' + figuraId"
|
||||
[attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
|
||||
(click)="toggleMethodology()">
|
||||
<mat-icon aria-hidden="true">help_outline</mat-icon>
|
||||
Cómo leer
|
||||
</button>
|
||||
<div class="methodology-detail" [id]="methodologyId" [hidden]="!methodologyExpanded()">
|
||||
<ul>
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">{{ periodInterpretation }}</p>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (state.status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<div class="figure-skeleton"><p class="state" role="status">Cargando figura…</p><div class="skeleton" aria-hidden="true"></div></div>
|
||||
} @else if (state.status === 'deferred') {
|
||||
<div class="figure-skeleton"><p class="state" role="status">{{ state.message }}</p><div class="skeleton" aria-hidden="true"></div></div>
|
||||
} @else if (state.status === 'incompatible') {
|
||||
<div class="state incompatible" role="status"><p>Filtro general incompatible con esta figura.</p><p>{{ state.message }}</p></div>
|
||||
} @else if (state.status === 'error') {
|
||||
<div class="state" role="alert"><p>{{ state.message }}</p>
|
||||
<button mat-stroked-button (click)="retry.emit()">Reintentar solicitud</button></div>
|
||||
} @else if (state.figure; as figure) {
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
@if (chartFigure) {
|
||||
<div [hidden]="state.status !== 'ready'">
|
||||
@if (state.status === 'ready' && state.hierarchy; as hierarchy) {
|
||||
<div #donutNavigation class="donut-navigation" tabindex="-1" aria-label="Explorar grupos de la dona">
|
||||
<p class="donut-status" role="status">{{ activeParent ? 'Categorías de ' + activeParent + '. Anillo exterior: porcentajes dentro de este grupo. Anillo interior: todos los grupos.' : 'Selecciona un segmento para ver sus categorías. También puedes explorar los grupos con Tab y Enter o Espacio.' }}</p>
|
||||
<div class="donut-toolbar">
|
||||
<span class="donut-context">{{ activeParent ? 'Categorías' : 'Grupos' }}</span>
|
||||
@if (activeParent) {
|
||||
<button mat-icon-button type="button" class="donut-restore" matTooltip="Restaurar vista"
|
||||
aria-label="Restaurar vista de la gráfica" (click)="returnToParents($event)">
|
||||
<svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" width="24" height="24">
|
||||
<path d="M3 10a9 9 0 1 1 2.6 8.4M3 4v6h6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="donut-legend" aria-label="Leyenda de la dona">
|
||||
<div #donutKeyboard class="donut-keyboard" role="group" aria-label="Explorar grupos con teclado">
|
||||
@for (parent of hierarchy.parents; track parent) {
|
||||
<button type="button" [attr.aria-pressed]="activeParent === parent" (click)="expandParent(parent)">
|
||||
<span class="legend-swatch" [style.background]="legendColor(parent, true)" aria-hidden="true"></span>{{ parent }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
<div class="donut-children-region" [class.expanded]="!!activeParent"
|
||||
[attr.aria-hidden]="activeParent ? null : 'true'" [attr.inert]="activeParent ? null : ''">
|
||||
<div class="donut-children-content">
|
||||
<h3 class="donut-children-title">Categorías</h3>
|
||||
<div class="donut-children" role="group" [attr.aria-label]="'Categorías de ' + activeParent">
|
||||
@for (child of visibleChildren; track child.label) {
|
||||
<button type="button" [attr.aria-pressed]="activeCategory === child.label" (click)="selectCategory(child.label)">
|
||||
<span class="legend-swatch" [style.background]="legendColor(child.label, false)" aria-hidden="true"></span>{{ child.label }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
<span class="legend-swatch" [style.background]="entry.color ?? 'currentColor'" aria-hidden="true"></span>{{ entry.label }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
@if (state.footnotes?.length) {
|
||||
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
@if (state.categoryLabels?.length) {
|
||||
<details class="category-labels">
|
||||
<summary>Nombres completos de las categorías</summary>
|
||||
<ul>
|
||||
@for (label of state.categoryLabels; track $index) {
|
||||
<li><span>{{ label.abbreviated }}</span>: {{ label.original }}</li>
|
||||
}
|
||||
</ul>
|
||||
</details>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</mat-card>
|
||||
@@ -0,0 +1,97 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.interpretation {
|
||||
margin-bottom: var(--issste-space-4);
|
||||
color: var(--issste-text);
|
||||
font-family: var(--issste-font-body);
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.methodology-detail {
|
||||
margin-top: var(--issste-space-3);
|
||||
padding: var(--issste-space-4);
|
||||
border-left: 3px solid var(--issste-accent);
|
||||
}
|
||||
.interpretation ul { margin: 0; padding-left: 1.25rem; }
|
||||
.interpretation li + li { margin-top: .25rem; }
|
||||
.period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); }
|
||||
.methodology-toggle { margin-top: 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; }
|
||||
.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) { .methodology-detail { padding: var(--issste-space-3); } }
|
||||
|
||||
.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; }
|
||||
.donut-navigation {
|
||||
position: relative;
|
||||
color: var(--issste-text);
|
||||
}
|
||||
.dark .donut-navigation { color: #eef1f7; }
|
||||
.donut-status {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
}
|
||||
.donut-legend { padding: 0 .75rem; box-sizing: border-box; }
|
||||
.donut-keyboard, .donut-children { display: flex; flex-wrap: wrap; align-content: start; gap: .25rem .75rem; }
|
||||
.donut-children-region {
|
||||
display: grid; grid-template-rows: 0fr; opacity: 0; transform: translateY(-.25rem);
|
||||
transition: grid-template-rows 225ms ease, opacity 180ms ease, transform 225ms ease;
|
||||
}
|
||||
.donut-children-region.expanded { grid-template-rows: 1fr; opacity: 1; transform: translateY(0); }
|
||||
.donut-children-content { min-height: 0; overflow: hidden; }
|
||||
.donut-children-title { margin: .5rem 0 0; padding-top: .5rem; border-top: 1px solid var(--issste-border);
|
||||
font: var(--mat-sys-body-small); font-weight: 600; }
|
||||
.donut-children { padding-top: .25rem; }
|
||||
.donut-legend button { display: flex; align-items: center; gap: .5rem; max-width: 100%; min-height: 44px;
|
||||
padding: .25rem .5rem; border: 1px solid transparent; border-radius: 4px; background: transparent; color: inherit;
|
||||
font: inherit; font-size: .875rem; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.donut-legend button[aria-pressed=true] { border-color: currentColor; font-weight: 600; }
|
||||
.legend-swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; }
|
||||
.donut-toolbar {
|
||||
height: 48px; box-sizing: border-box;
|
||||
display: flex; align-items: center; justify-content: space-between; gap: .5rem; padding: 0 .75rem;
|
||||
}
|
||||
.donut-context { min-width: 0; overflow-wrap: anywhere; font: var(--mat-sys-body-small); }
|
||||
.donut-restore { flex-shrink: 0; color: inherit; }
|
||||
.donut-legend button:focus-visible, .donut-restore:focus-visible {
|
||||
outline: 2px solid currentColor; outline-offset: 3px;
|
||||
}
|
||||
.donut-static-legend {
|
||||
display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: .25rem .9rem;
|
||||
padding: .5rem .75rem .25rem; color: var(--issste-text); box-sizing: border-box;
|
||||
}
|
||||
.dark .donut-static-legend { color: #eef1f7; }
|
||||
.donut-static-legend__item { display: flex; align-items: center; gap: .5rem; min-height: 32px; max-width: 100%;
|
||||
font: var(--mat-sys-body-small); overflow-wrap: anywhere; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { vi } from 'vitest';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { presentationFigure } from './indicadores.presentation';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutHierarchy, donutLegend } from './indicadores-donut-drilldown';
|
||||
|
||||
describe('IndicadorFigureCard', () => {
|
||||
const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] };
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigureCard>>;
|
||||
let react: ReturnType<typeof vi.fn>;
|
||||
let purge: ReturnType<typeof vi.fn>;
|
||||
let disconnect: ReturnType<typeof vi.fn>;
|
||||
let observe: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
react = vi.fn().mockResolvedValue(undefined);
|
||||
purge = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
observe = vi.fn();
|
||||
vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
|
||||
TestBed.configureTestingModule({
|
||||
imports: [IndicadorFigureCard],
|
||||
providers: [{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({
|
||||
react, purge, Plots: { resize: vi.fn().mockResolvedValue(undefined) },
|
||||
addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined),
|
||||
}) }],
|
||||
});
|
||||
fixture = TestBed.createComponent(IndicadorFigureCard);
|
||||
fixture.componentRef.setInput('selected', selected);
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c1_puntos');
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('state', { status: 'idle' });
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); vi.unstubAllGlobals(); });
|
||||
function state(value: FigureState) { fixture.componentRef.setInput('state', value); fixture.detectChanges(); }
|
||||
async function settle() {
|
||||
await fixture.whenStable();
|
||||
for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function ready(original: PlotlyFigure) {
|
||||
const copy = presentationFigure(original, { indicador: selected.id, figura: 'fig_c1_puntos', tema: 'claro' });
|
||||
state({ status: 'ready', figure: original, presentationFigure: copy });
|
||||
return copy;
|
||||
}
|
||||
it('C2 expande por Plotly y teclado, vuelve con foco y conserva host; reinicia al cambiar resultado', async () => {
|
||||
const { figure, data } = donutFixture();
|
||||
const hierarchy = donutHierarchy(figure, data)!;
|
||||
state({ status: 'ready', figure, presentationFigure: figure, hierarchy }); await settle();
|
||||
const host = fixture.nativeElement.querySelector('.plot');
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(chart.figure.data).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Volver a grupos');
|
||||
expect(fixture.nativeElement.querySelectorAll('.donut-navigation > button')).toHaveLength(0);
|
||||
const categories = fixture.nativeElement.querySelector('.donut-children-region') as HTMLElement;
|
||||
expect(categories.classList.contains('expanded')).toBe(false);
|
||||
expect(categories.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(categories.hasAttribute('inert')).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.donut-children-title').textContent).toBe('Categorías');
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G2');
|
||||
expect(categories.classList.contains('expanded')).toBe(true);
|
||||
expect(categories.hasAttribute('inert')).toBe(false);
|
||||
expect(categories.getAttribute('aria-hidden')).toBeNull();
|
||||
expect(chart.figure.data[0]['labels']).toEqual(['B', 'C']);
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G1' }] }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G1');
|
||||
expect(chart.figure.data[0]['labels']).toEqual(['A']);
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G1');
|
||||
chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G2' }] }); await settle();
|
||||
state({ status: 'ready', figure, presentationFigure: structuredClone(figure), hierarchy }); await settle();
|
||||
expect(fixture.componentInstance.activeParent).toBe('G2');
|
||||
const back = fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement;
|
||||
expect(back.getAttribute('aria-label')).toBe('Restaurar vista de la gráfica');
|
||||
expect(back.querySelector('svg')).not.toBeNull();
|
||||
back.focus(); back.click(); await settle();
|
||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.donut-keyboard button'));
|
||||
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull();
|
||||
const group = fixture.nativeElement.querySelectorAll('.donut-keyboard button')[1] as HTMLButtonElement;
|
||||
group.click(); await settle(); expect(group.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(host); expect(purge).not.toHaveBeenCalled();
|
||||
state({ status: 'loading' }); expect(fixture.componentInstance.activeParent).toBeUndefined();
|
||||
expect(fixture.nativeElement.querySelector('.donut-navigation')).toBeNull();
|
||||
state({ status: 'ready', figure: structuredClone(figure), presentationFigure: figure, hierarchy }); await settle();
|
||||
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
|
||||
});
|
||||
it('homologa la dona simple con leyenda HTML superior sin alterar categorías ni valores', async () => {
|
||||
const { figure } = donutFixture();
|
||||
figure.data.pop();
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
|
||||
const copy = presentationFigure(figure, { indicador: selected.id, figura: 'fig_c2_donas', tema: 'claro' });
|
||||
const legend = donutLegend(copy)!;
|
||||
state({ status: 'ready', figure, presentationFigure: copy, donutLegend: legend }); await settle();
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(fixture.nativeElement.querySelectorAll('.donut-static-legend__item')).toHaveLength(3);
|
||||
expect(fixture.nativeElement.querySelector('.donut-static-legend').textContent).toContain('A');
|
||||
expect(chart.figure.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||
expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']);
|
||||
expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']);
|
||||
});
|
||||
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: {} };
|
||||
const notes = ['Fuente: A & B\nSegunda línea', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
|
||||
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
|
||||
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement;
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura');
|
||||
expect([...section.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');
|
||||
expect(fixture.nativeElement.textContent).toContain('Cargando figura');
|
||||
const retry = vi.fn();
|
||||
fixture.componentInstance.retry.subscribe(retry);
|
||||
state({ status: 'error', message: 'La figura o los reportes no están disponibles para esta selección.' });
|
||||
expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('reportes no están disponibles');
|
||||
fixture.nativeElement.querySelector('.state button').click();
|
||||
expect(retry).toHaveBeenCalledTimes(1);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart))).toBeNull();
|
||||
});
|
||||
it('presenta selección incompleta y un indicador sin figuras', () => {
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.nativeElement.textContent).toContain('Completa una selección válida');
|
||||
fixture.componentRef.setInput('selected', { ...selected, figuras: [] });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles');
|
||||
});
|
||||
it('presenta título del JSON, nombre amigable y conserva datos incluso si Plotly los muta', async () => {
|
||||
const original: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }],
|
||||
layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const snapshot = JSON.stringify(original);
|
||||
react.mockImplementation(async (_host, data, layout) => {
|
||||
data[0].y[0] = 0;
|
||||
layout.annotations[0].text = 'Cambio interno de Plotly';
|
||||
});
|
||||
const copy = ready(original);
|
||||
await settle();
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado');
|
||||
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe('Figura: Puntos');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('fig_c1_puntos');
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy);
|
||||
expect(JSON.stringify(original)).toBe(snapshot);
|
||||
expect(copy.data).toEqual(original.data);
|
||||
expect(copy.layout['annotations']).toEqual(original.layout['annotations']);
|
||||
});
|
||||
it('distingue resultado sin puntos del error y mantiene valores binarios indeterminados', async () => {
|
||||
ready({ data: [{ y: [null] }], layout: {} });
|
||||
await settle();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart))).not.toBeNull();
|
||||
ready({ data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' } }], layout: {} });
|
||||
await settle();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles');
|
||||
});
|
||||
it('UX-07B representa pies como texto seguro, sin duplicación ni notas genéricas', async () => {
|
||||
const figure = { data: [{ y: [42] }], layout: {} };
|
||||
const note = 'Primera línea\n<img src=x onerror=alert(1)>\nAviso completo';
|
||||
state({ status: 'ready', figure, presentationFigure: figure, footnotes: [note] }); await settle();
|
||||
const notes = fixture.nativeElement.querySelector('.methodological-footnotes');
|
||||
expect(notes.textContent).toBe(note); expect(notes.querySelector('img')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelectorAll('.methodological-footnotes p')).toHaveLength(1);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.showNotes).toBe(false);
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
state({ status: 'ready', figure, presentationFigure: figure, footnotes: [] }); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
});
|
||||
it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
|
||||
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
});
|
||||
it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => {
|
||||
react.mockRejectedValueOnce(new Error('render'));
|
||||
ready({ data: [{ y: [42] }], layout: {} });
|
||||
await settle();
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo representar la figura');
|
||||
const retry = vi.fn();
|
||||
fixture.componentInstance.retry.subscribe(retry);
|
||||
fixture.nativeElement.querySelector('app-plotly-chart button').click();
|
||||
await settle();
|
||||
expect(react).toHaveBeenCalledTimes(2);
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('D.2 mantiene Plotly oculto entre resultados y purga al destruir la card', async () => {
|
||||
ready({ data: [{ y: [42] }], layout: {} }); await settle();
|
||||
const firstHost = fixture.nativeElement.querySelector('.plot');
|
||||
expect(observe).toHaveBeenCalledWith(firstHost);
|
||||
state({ status: 'loading' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
state({ status: 'incompatible', message: 'Granularidad no publicada' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Granularidad no publicada');
|
||||
ready({ data: [{ y: [50] }], layout: {} }); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
|
||||
expect(firstHost.closest('[hidden]')).toBeNull();
|
||||
fixture.destroy();
|
||||
expect(purge).toHaveBeenCalledWith(firstHost); expect(purge).toHaveBeenCalledTimes(1);
|
||||
expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('UX-06E.P0.2 inicia cerrado y despliega toda la explicación con estado accesible', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'idle' });
|
||||
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
|
||||
expect(section.textContent).toContain('Cómo leer');
|
||||
expect(section.querySelector('h2')).toBeNull();
|
||||
expect(section.classList.contains('expanded')).toBe(false);
|
||||
expect(section.querySelector('.methodology-detail ul')).not.toBeNull();
|
||||
expect(section.querySelector('ul')?.closest('[hidden]')).not.toBeNull();
|
||||
expect(section.querySelectorAll('button')).toHaveLength(1);
|
||||
expect(section.querySelectorAll('[hidden]')).toHaveLength(1);
|
||||
const button = section.querySelector('button')!;
|
||||
const detail = section.querySelector('[id]') as HTMLElement;
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(button.getAttribute('aria-controls')).toBe(detail.id);
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(button.tagName).toBe('BUTTON');
|
||||
expect(button.nextElementSibling?.classList.contains('methodology-detail')).toBe(true);
|
||||
button.focus();
|
||||
expect(document.activeElement).toBe(button);
|
||||
expect(detail.textContent).toContain('SIN_DATO');
|
||||
expect(detail.textContent).toContain('suprimidos no representan porcentajes observados de 0 %');
|
||||
expect(detail.textContent).toContain('no permite determinar la disponibilidad');
|
||||
expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation);
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
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('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'idle' });
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('conteos por categoría');
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas');
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1');
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'))
|
||||
.toBe(fixture.nativeElement.querySelector('.methodology-detail').id);
|
||||
});
|
||||
it('usa instrucciones exactas en orden y conserva caracteres especiales como texto', () => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_donas', descripcion: 'No repetir', como_leer: [
|
||||
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
|
||||
] }] });
|
||||
state({ status: 'idle' });
|
||||
const lines = fixture.nativeElement.querySelectorAll('.methodology-detail li');
|
||||
expect([...lines].map((line: Element) => line.textContent)).toEqual([
|
||||
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
|
||||
]);
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(fixture.componentInstance.interpretation).toEqual([...lines].map((line: Element) => line.textContent));
|
||||
});
|
||||
it.each([
|
||||
['sin coincidencia', [{ figura: 'otra_figura', descripcion: null, como_leer: ['No corresponde.'] }]],
|
||||
['vacías', [{ figura: 'fig_c2_apiladas', descripcion: 'Sin instrucciones específicas.', como_leer: [] }]],
|
||||
['nulas', [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: null }]],
|
||||
])('mantiene fallback local con figuras_detalle %s', (_label, details) => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: details });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.componentInstance.interpretation).toContain('Las categorías corresponden a la distribución de cada grupo y periodo.');
|
||||
expect(fixture.componentInstance.interpretation).toContain('SIN_DATO, cuando aparece, es una categoría legítima de la representación.');
|
||||
});
|
||||
it('preserva íntegramente, sin filtrado semántico, instrucciones sobre supresión y categorías pequeñas', () => {
|
||||
const instructions = ['Se ocultan categorías individuales pequeñas.', 'La supresión se determina por grupo.', 'Conclusión.'];
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: instructions }] });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.componentInstance.interpretation).toEqual(instructions);
|
||||
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((line: Element) => line.textContent)).toEqual(instructions);
|
||||
});
|
||||
it.each([
|
||||
['fig_c2_barras', 'Barras'],
|
||||
['fig_c2_donas', 'Donas'],
|
||||
])('UX-07D.1 identifica %s con el nombre %s en la tarjeta de figura', (id, label) => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', figuras: [id] });
|
||||
fixture.componentRef.setInput('figuraId', id);
|
||||
ready({ data: [], layout: {} });
|
||||
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`);
|
||||
});
|
||||
it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => {
|
||||
fixture.componentRef.setInput('figuraId', figura);
|
||||
if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull();
|
||||
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((li: any) => li.textContent))
|
||||
.toEqual(fixture.componentInstance.interpretation);
|
||||
});
|
||||
it.each(['cacu', 'cama'])('UX-06E.P0.2 conserva advertencias C2 de %s en ayuda cerrada', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'loading' });
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull();
|
||||
const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement;
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(detail.textContent).toContain('Las barras muestran conteos por categoría; los porcentajes publicados pueden aparecer como etiquetas. Consulta la unidad y el denominador de cada representación.');
|
||||
expect(detail.textContent).toContain('SIN_DATO');
|
||||
expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %');
|
||||
});
|
||||
it('UX-06E.P0.2 quita el panel redundante y preserva todas las anotaciones en Plotly', async () => {
|
||||
const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [
|
||||
{ text: 'Denominador pequeño<br>Intervalos no disponibles' },
|
||||
{ text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' },
|
||||
{ text: 'Supresión: consulta las notas completas' },
|
||||
] }, frames: [] };
|
||||
const snapshot = JSON.stringify(figure);
|
||||
ready(figure); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']);
|
||||
expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text));
|
||||
expect(JSON.stringify(figure)).toBe(snapshot);
|
||||
expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0');
|
||||
});
|
||||
it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => {
|
||||
fixture.componentRef.setInput('tema', tema);
|
||||
const annotation = 'Advertencia metodológica única de la figura.';
|
||||
const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } };
|
||||
ready(original); await settle();
|
||||
const card = fixture.nativeElement.querySelector('.figure-card');
|
||||
expect(card.classList.contains('dark')).toBe(tema === 'oscuro');
|
||||
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain(annotation);
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(chart.notes).toEqual([annotation]);
|
||||
expect(JSON.stringify(original)).toContain(annotation);
|
||||
});
|
||||
it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
state({ status: 'idle' });
|
||||
const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' });
|
||||
fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas');
|
||||
fixture.detectChanges();
|
||||
const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
|
||||
expect(first).not.toBe(second);
|
||||
expect(fixture.nativeElement.querySelector('[id]').id).toBe(second);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'])('UX-06E.B1 conserva C1 de %s íntegro con condiciones críticas visibles', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
state({ status: 'idle' });
|
||||
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
|
||||
const button = section.querySelector('button')!;
|
||||
const detail = section.querySelector('[hidden]') as HTMLElement;
|
||||
expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button');
|
||||
// jsdom does not perform native Enter/Space activation; leave both keys
|
||||
// available to the browser and validate activation in Chrome.
|
||||
for (const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
expect(button.textContent).toContain('Cómo leer');
|
||||
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba · ' + dominio + ' · fig_c1_puntos');
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true);
|
||||
const warnings = detail.querySelector('ul')!;
|
||||
expect(warnings.closest('[hidden]')).not.toBeNull();
|
||||
expect(warnings.textContent).toContain('100 % no implica certeza poblacional');
|
||||
expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
if (dominio === 'tea') {
|
||||
expect(warnings.textContent).toContain('Wilson al 95 %');
|
||||
expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan');
|
||||
expect(warnings.textContent).toContain('denominadores pequeños');
|
||||
} else expect(warnings.textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
|
||||
expect([...warnings.querySelectorAll('li')].map(p => p.textContent))
|
||||
.toEqual(fixture.componentInstance.interpretation);
|
||||
button.focus(); button.click(); fixture.detectChanges();
|
||||
expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false);
|
||||
expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true);
|
||||
});
|
||||
it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' });
|
||||
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
|
||||
expect(section.querySelector('[hidden]')).not.toBeNull();
|
||||
expect(section.querySelector('button')).not.toBeNull();
|
||||
expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([
|
||||
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
|
||||
'Los límites de dibujo no representan necesariamente extremos observados.',
|
||||
'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.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => {
|
||||
const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } };
|
||||
const copy = ready(original); await settle();
|
||||
const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy);
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance;
|
||||
const host = fixture.nativeElement.querySelector('.plot');
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle');
|
||||
const calls = react.mock.calls.length, observers = observe.mock.calls.length;
|
||||
for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); }
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart);
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
|
||||
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
|
||||
expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers);
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Component, ElementRef, Input, OnChanges, output, signal, SimpleChanges, viewChild } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { Dominio, hasNoVisibleValues, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { figureTitle } from './indicadores.presentation';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { 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 {
|
||||
status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible';
|
||||
figure?: PlotlyFigure;
|
||||
presentationFigure?: PlotlyFigure;
|
||||
footnotes?: readonly string[];
|
||||
categoryLabels?: readonly CategoryLabel[];
|
||||
minimumPlotWidth?: number;
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
hierarchy?: DonutHierarchy;
|
||||
source?: 'datos' | 'figuras';
|
||||
fallbackReason?: string;
|
||||
emptyMessage?: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
export class IndicadorFigureCard implements OnChanges {
|
||||
private readonly donutNavigation = viewChild<ElementRef<HTMLElement>>('donutNavigation');
|
||||
private readonly donutKeyboard = viewChild<ElementRef<HTMLElement>>('donutKeyboard');
|
||||
private currentState!: FigureState;
|
||||
// Keep the mounted host's last presentation only. The template hides it whenever
|
||||
// it is not the current result; this is neither applied state nor a results cache.
|
||||
chartFigure?: PlotlyFigure;
|
||||
chartMinimumWidth?: number;
|
||||
activeParent?: string;
|
||||
activeCategory?: string;
|
||||
readonly hierarchySelected = output<DonutSelection>();
|
||||
selectCategory(category: string) {
|
||||
if (!this.state.hierarchy?.children.some(c => c.parent === this.activeParent && c.label === category)) return;
|
||||
this.activeCategory = this.activeCategory === category ? undefined : category;
|
||||
this.hierarchySelected.emit({ parent: this.activeParent, category: this.activeCategory });
|
||||
}
|
||||
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
|
||||
legendColor(label: string, parent: boolean): string {
|
||||
const trace = this.chartFigure?.data[parent && this.activeParent ? 1 : 0];
|
||||
const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
|
||||
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined;
|
||||
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
|
||||
}
|
||||
@Input({ required: true }) set state(value: FigureState) {
|
||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') {
|
||||
this.updateDonut();
|
||||
this.chartMinimumWidth = value.minimumPlotWidth;
|
||||
}
|
||||
}
|
||||
get state() { return this.currentState; }
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (changes['dominio'] || changes['figuraId']
|
||||
|| (changes['selected'] && changes['selected'].previousValue?.id !== this.selected?.id)) {
|
||||
this.activeParent = undefined;
|
||||
if (this.state.status === 'ready') this.updateDonut();
|
||||
}
|
||||
}
|
||||
private updateDonut() {
|
||||
const { presentationFigure, hierarchy } = this.state;
|
||||
// Empty pages retain the series' plot height as well. This is a derived
|
||||
// layout copy; the original figure and its annotations remain available.
|
||||
const source = presentationFigure && this.state.plotHeight
|
||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||
this.chartFigure = source && hierarchy
|
||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
|| !this.state.hierarchy.children.some(c => c.parent === parent && c.value > 0)) return;
|
||||
this.activeParent = parent;
|
||||
this.activeCategory = undefined;
|
||||
this.updateDonut();
|
||||
this.hierarchySelected.emit({ parent });
|
||||
}
|
||||
returnToParents(event?: MouseEvent) {
|
||||
if (!this.activeParent) return;
|
||||
this.activeParent = undefined; this.activeCategory = undefined; this.updateDonut();
|
||||
this.hierarchySelected.emit({});
|
||||
// The restore button disappears. Transfer keyboard focus to the first
|
||||
// persistent alternative; pointer users return to the graphic region.
|
||||
if (event) {
|
||||
const target = event.detail === 0 ? this.donutKeyboard()?.nativeElement.querySelector('button')
|
||||
: this.donutNavigation()?.nativeElement;
|
||||
target?.focus();
|
||||
}
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||
const point = event.points[0];
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
readonly retry = output<void>();
|
||||
readonly plotWidthChanged = output<number>();
|
||||
reportPlotWidth(width: unknown) {
|
||||
if (typeof width === 'number') this.plotWidthChanged.emit(width);
|
||||
}
|
||||
readonly methodologyExpanded = signal(false);
|
||||
readonly metadataRequested = output<void>();
|
||||
toggleMethodology() {
|
||||
const open = !this.methodologyExpanded();
|
||||
this.methodologyExpanded.set(open);
|
||||
if (open && !this.metadata) this.metadataRequested.emit();
|
||||
}
|
||||
get methodologyId(): string {
|
||||
return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology';
|
||||
}
|
||||
|
||||
// Editorial classification of complete local sentences by known family.
|
||||
// Keep mixed C3r/Wilson sentences and all backend content visible.
|
||||
private get contract(): string | undefined {
|
||||
return this.figuraId.startsWith('fig_c1') ? 'C1'
|
||||
: this.figuraId.startsWith('fig_c2') ? 'C2'
|
||||
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
|
||||
}
|
||||
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'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { applyGlobal, GlobalFilterState, IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const catalog = [
|
||||
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] },
|
||||
];
|
||||
describe('IndicadorFigurePanel', () => {
|
||||
let page: IndicadorFigurePanel;
|
||||
let state: GlobalFilterState;
|
||||
let editor: IndicadorPeriodFilters;
|
||||
let http: HttpTestingController;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel, IndicadorPeriodFilters], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
editor = new IndicadorPeriodFilters(); editor.state = state; editor.types = ['semestre'];
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function filters() {
|
||||
fixture.detectChanges();
|
||||
return editor;
|
||||
}
|
||||
function apply() { if (applyGlobal(state, ['semestre'])) { fixture.componentRef.setInput('applied', state.applied); fixture.detectChanges(); } }
|
||||
function load() { fixture.detectChanges(); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
function candidate() {
|
||||
// An unknown representation retains the legacy server-first hierarchy path.
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: 'C2', figuras: ['future_donut', 'f2'] });
|
||||
fixture.componentRef.setInput('figuraId', 'future_donut');
|
||||
load();
|
||||
const sample = donutFixture(); figure().flush(sample.figure);
|
||||
return sample;
|
||||
}
|
||||
it('C2 carga metadatos una vez; explorar, volver y adaptar ancho no consulta HTTP', () => {
|
||||
const sample = candidate();
|
||||
const data = http.expectOne(r => r.url === '/tea/indicadores/i1/datos' && r.params.get('periodos') === '2025-S2');
|
||||
data.flush(sample.data); fixture.detectChanges();
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
||||
expect(page.result().hierarchy?.parents).toEqual(['G1', 'G2']);
|
||||
card.expandParent('G2'); expect(card.chartFigure?.data[0]['labels']).toEqual(['B','C']);
|
||||
page.updatePlotWidth(400); fixture.detectChanges(); expect(card.activeParent).toBe('G2');
|
||||
card.returnToParents(); http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('figuraId', 'f2'); fixture.detectChanges();
|
||||
expect(card.activeParent).toBeUndefined(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(page.result().hierarchy).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
it('descubre una representación futura de un anillo sin IDs codificados y restaura desde la UI sin HTTP', () => {
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], id: 'future_item', contrato: 'C2', figuras: ['future_donut'] });
|
||||
fixture.componentRef.setInput('figuraId', 'future_donut'); load();
|
||||
const sample = donutFixture(); sample.figure.data.pop(); sample.data.id = 'future_item';
|
||||
figure().flush(sample.figure); http.expectOne(r => r.url.endsWith('/future_item/datos')).flush(sample.data);
|
||||
fixture.detectChanges();
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
||||
expect(card.state.hierarchy?.parents).toEqual(['G1','G2']);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub));
|
||||
chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 0, label: 'G2' }] }); fixture.detectChanges();
|
||||
expect(card.activeParent).toBe('G2');
|
||||
chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 1, label: 'G1' }] }); fixture.detectChanges();
|
||||
expect(card.activeParent).toBe('G1');
|
||||
(fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(card.activeParent).toBeUndefined(); http.expectNone(() => true);
|
||||
expect(page.result().figure).toEqual(sample.figure);
|
||||
});
|
||||
it.each(['http', 'suppression', 'mismatch'])('C2 conserva la figura publicada cuando %s impide la jerarquía', reason => {
|
||||
const sample = candidate(), request = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
if (reason === 'http') request.flush({}, { status: 503, statusText: 'Unavailable' });
|
||||
else { if (reason === 'suppression') sample.data.filas[0]['suprimido'] = 1;
|
||||
else sample.data.filas[0]['n'] = 999; request.flush(sample.data); }
|
||||
fixture.detectChanges(); expect(page.result().status).toBe('ready');
|
||||
expect(page.result().hierarchy).toBeUndefined(); expect(page.result().figure).toEqual(sample.figure);
|
||||
});
|
||||
it('C2 cancela metadatos pendientes al cambiar tema y no presenta resultados obsoletos', () => {
|
||||
candidate(); const old = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true); expect(page.result().status).toBe('loading');
|
||||
figure().flush({ data: [], layout: {} }); expect(page.result().hierarchy).toBeUndefined();
|
||||
});
|
||||
|
||||
it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => {
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], figuras: ['fig_c2_barras'], contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_barras');
|
||||
const request = () => http.expectOne(req => req.url.includes('/cama/indicadores/') && req.url.includes('/figuras/'));
|
||||
const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }],
|
||||
layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22,
|
||||
xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } });
|
||||
load(); http.expectOne(r => r.url.endsWith('/datos')).flush({ id: 'i1', contrato: 'C2', tipo_periodo: 'semestre', periodos: [], filas: [] });
|
||||
request().flush(response('Nota vigente')); fixture.detectChanges();
|
||||
for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) {
|
||||
fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges();
|
||||
for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width);
|
||||
expect(page.result().footnotes).toEqual(['Nota vigente']); http.expectNone(() => true);
|
||||
}
|
||||
page.requestFigure(); const old = request(); fixture.detectChanges();
|
||||
expect(page.result().footnotes).toBeUndefined();
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true);
|
||||
const current = request(); current.flush(response('Nota del periodo actual')); fixture.detectChanges();
|
||||
expect(page.result().footnotes).toEqual(['Nota del periodo actual']);
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota del periodo actual');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('UX-07C alterna etiquetas desde el original sin HTTP, conserva el host y restaura hover/categorías', () => {
|
||||
const label = 'Fármaco de riesgo para el neurodesarrollo';
|
||||
const received: PlotlyFigure = { data: [{ type: 'bar', x: [label], y: [0], customdata: [null],
|
||||
hovertemplate: '%{x}<br>%{y:.1f}%<extra></extra>' }], layout: { xaxis: { type: 'category' } } };
|
||||
load(); figure().flush(received); fixture.detectChanges();
|
||||
const before = structuredClone(received), host = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
expect(page.result().categoryLabels?.[0].original).toBe(label);
|
||||
expect(fixture.nativeElement.querySelector('.category-labels')).not.toBeNull();
|
||||
page.updatePlotWidth(1400); fixture.detectChanges();
|
||||
expect(page.result().categoryLabels).toEqual([]);
|
||||
const unchanged = page.result();
|
||||
for (const width of [1400.7, 1399, 1350, 0, NaN]) page.updatePlotWidth(width);
|
||||
expect(page.result()).toBe(unchanged);
|
||||
page.updatePlotWidth(320); fixture.detectChanges();
|
||||
expect(page.result().categoryLabels).toHaveLength(1);
|
||||
http.expectNone(() => true);
|
||||
for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) {
|
||||
fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
expect(page.result().figure).toEqual(before);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(host);
|
||||
if (profile === BASE_VISUAL_PROFILE) {
|
||||
expect(page.result().presentationFigure?.data).toEqual(before.data);
|
||||
expect(page.result().categoryLabels).toEqual([]);
|
||||
} else expect(page.result().categoryLabels).toHaveLength(1);
|
||||
}
|
||||
expect(received).toEqual(before);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
|
||||
['C2', ['conteos por categoría', 'distribución de cada grupo y periodo', 'SIN_DATO']],
|
||||
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
|
||||
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
|
||||
['toString', ['No hay una explicación específica']],
|
||||
])('explica el contrato %s y la distinción entre reporte y valores representables', (contract, expected) => {
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: contract, figuras: ['f1'] }); load();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
for (const text of expected) expect(help).toContain(text);
|
||||
if (contract === 'C3r') {
|
||||
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
|
||||
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
|
||||
}
|
||||
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
|
||||
});
|
||||
it('oculta sólo visualmente el encabezado y conserva identidad, lectura y títulos sin HTTP adicional', () => {
|
||||
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
const id = page.titleId;
|
||||
const heading = fixture.nativeElement.querySelector('h3') as HTMLElement;
|
||||
const section = fixture.nativeElement.querySelector('section') as HTMLElement;
|
||||
expect(heading.id).toBe(id); expect(id).not.toBe('');
|
||||
expect(section.getAttribute('aria-labelledby')).toBe(id);
|
||||
expect(section.firstElementChild).toBe(heading);
|
||||
expect(heading.textContent).toBe('tea · i1 · Uno · f1');
|
||||
expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false);
|
||||
const style = getComputedStyle(heading);
|
||||
expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden');
|
||||
expect(style.position).toBe('absolute'); expect(style.width).toBe('1px'); expect(style.height).toBe('1px');
|
||||
expect(style.clipPath).toBe('inset(50%)'); expect(style.overflow).toBe('hidden');
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
expect(fixture.nativeElement.querySelector('app-indicador-period-filters')).toBeNull();
|
||||
const result = page.result(), savedState = state;
|
||||
fixture.detectChanges();
|
||||
expect(page.titleId).toBe(id); expect(state).toBe(savedState); expect(page.result()).toBe(result);
|
||||
expect(fixture.nativeElement.querySelector('h3')).toBe(heading);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => {
|
||||
load();
|
||||
const received: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
|
||||
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const original = JSON.stringify(received);
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
expect(JSON.stringify(received)).toBe(original);
|
||||
expect(page.result().figure).toEqual(received);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
expect(chart.figure).toBe(page.result().presentationFigure);
|
||||
expect(chart.figure).not.toBe(page.result().figure);
|
||||
expect(chart.figure?.data).toEqual(received.data);
|
||||
expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } });
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
const base = structuredClone(page.result().presentationFigure);
|
||||
const original = page.result().figure;
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const applied = page.applied;
|
||||
fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc');
|
||||
expect(page.result().figure).toBe(original); expect(page.applied).toBe(applied);
|
||||
expect(page.result().presentationFigure?.data).toEqual(received.data);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(page.result().presentationFigure).toEqual(base);
|
||||
expect(page.result().figure).toEqual(received); http.expectNone(() => true);
|
||||
});
|
||||
it('UX-07B cambiar perfil durante carga no cancela ni inicia solicitudes', () => {
|
||||
load(); const pending = figure();
|
||||
fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(pending.cancelled).toBe(false); http.expectNone(() => true);
|
||||
pending.flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('cancela figuras al cambiar tema rápidamente', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const dark = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(dark.request.params.get('tema')).toBe('oscuro');
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges();
|
||||
expect(dark.cancelled).toBe(true);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it.each([
|
||||
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
|
||||
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
|
||||
load();
|
||||
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().message).toContain(message);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('error privado');
|
||||
fixture.nativeElement.querySelector('app-indicador-figure-card .state button').click();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
expect(page.result().status).toBe('ready');
|
||||
});
|
||||
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
|
||||
load(); figure().error(new ProgressEvent('error'));
|
||||
expect(page.result().message).toContain('conectar');
|
||||
page.requestFigure();
|
||||
const pending = figure();
|
||||
fixture.destroy();
|
||||
expect(pending.cancelled).toBe(true);
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
expect(editor.hasPending).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
req.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
const retry = figure();
|
||||
expect(retry.request.params.get('periodos')).toBe(periodos.join(','));
|
||||
retry.flush({ data: [{ y: [null] }], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const themed = figure();
|
||||
expect(themed.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themed.request.params.get('tema')).toBe('oscuro');
|
||||
themed.flush('error', { status: 500, statusText: 'Server Error' });
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
apply(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
});
|
||||
|
||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle');
|
||||
for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); }
|
||||
http.expectNone(() => true);
|
||||
expect(page.result()).toBe(result); expect(state).toBe(filterState);
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
expect(filters()).toBe(control);
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance).toBe(card);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
fixture.destroy();
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal, output } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorFigureCard],
|
||||
template: `
|
||||
<section [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||
(click)="changeDimension('')">Distribución general</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension !== ''" [class.active]="dimension !== ''"
|
||||
[disabled]="!singlePeriod" (click)="chooseStratified()">Distribución estratificada</button>
|
||||
</div>
|
||||
@if (dimension && capabilities.length > 1) {
|
||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@if (result().status === 'ready' && donutPages.length > 1) {
|
||||
<nav class="donut-periods" aria-label="Periodos de la dona">
|
||||
<button type="button" aria-label="Periodo anterior de la dona" [disabled]="donutPeriodIndex <= 0" (click)="changeDonutPeriod(-1)">‹</button>
|
||||
<span role="status" aria-live="polite">{{ activeDonutPeriod }} · {{ donutPeriodIndex + 1 }} / {{ donutPages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
<details><summary>Valores publicados y celdas suprimidas</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
}
|
||||
</section>
|
||||
`,
|
||||
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; }
|
||||
.distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; }
|
||||
.distribution-control legend { padding: 0; font-weight: 600; }
|
||||
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
||||
.distribution-dimensions { margin-top: .75rem; }
|
||||
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
|
||||
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
|
||||
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.distribution-toggle button:focus-visible, .distribution-dimensions button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.distribution-note { margin: .5rem 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.cells { overflow: auto; max-height: 24rem; } th, td { text-align: start; padding: .5rem; }
|
||||
.donut-periods { display: flex; align-items: center; justify-content: center; gap: .75rem; min-height: 48px; }
|
||||
.donut-periods span { text-align: center; overflow-wrap: anywhere; }
|
||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||
.donut-periods button:disabled { opacity: .45; }
|
||||
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
@Input() localSelection: DonutSelection = {};
|
||||
readonly hierarchySelected = output<DonutSelection>();
|
||||
readonly metadataRequested = output<void>();
|
||||
donutPages: { period: string; state: FigureState }[] = [];
|
||||
activeDonutPeriod?: string;
|
||||
private donutIdentity = '';
|
||||
get donutPeriodIndex() { return this.donutPages.findIndex(p => p.period === this.activeDonutPeriod); }
|
||||
changeDonutPeriod(step: number) {
|
||||
if (this.result().status !== 'ready' || ![-1, 1].includes(step)) return;
|
||||
const page = this.donutPages[this.donutPeriodIndex + step];
|
||||
if (!page) return;
|
||||
this.activeDonutPeriod = page.period;
|
||||
// Selection belongs to one page. Reset dependent category/stratum state
|
||||
// even when the same labels exist in the following period.
|
||||
this.hierarchySelected.emit({});
|
||||
this.result.set(this.refreshDonutPage(page.state));
|
||||
}
|
||||
selectHierarchy(selection: DonutSelection) {
|
||||
this.hierarchySelected.emit(selection.parent || selection.category
|
||||
? { ...selection, period: this.activeDonutPeriod ?? this.readySelection?.periodos?.[0] } : {});
|
||||
}
|
||||
private refreshDonutPage(state: FigureState): FigureState {
|
||||
const presentation = this.present(state.figure!, this.readySelection!, state.hierarchy);
|
||||
return { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
}
|
||||
private activateDonutPages(pages: { period: string; state: FigureState }[]): FigureState {
|
||||
const plotHeight = pages.some(p => p.state.hierarchy) ? 440 : undefined;
|
||||
this.donutPages = pages.map(p => ({ ...p, state: { ...p.state, plotHeight } }));
|
||||
this.activeDonutPeriod = pages.some(p => p.period === this.activeDonutPeriod) ? this.activeDonutPeriod : pages[0]?.period;
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
cells: StratifiedCell[] = [];
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
private stratifiedData?: IndicadorDatos;
|
||||
get capabilities() { return stratifiedCapabilities(this.indicador); }
|
||||
get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; }
|
||||
changeDimension(value: DimensionEstrato | '') {
|
||||
if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return;
|
||||
if (this.dimension === value) return;
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
|
||||
}
|
||||
chooseStratified() {
|
||||
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
||||
}
|
||||
private presentStratified(data: IndicadorDatos): FigureState {
|
||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
source: 'datos', footnotes: data.notas,
|
||||
emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' };
|
||||
}
|
||||
private readySelection?: FigureSelection;
|
||||
private plotWidth?: number;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>();
|
||||
private generation = 0;
|
||||
private currentKey = '';
|
||||
titleId = '';
|
||||
distributionAvailabilityId = '';
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; }
|
||||
constructor() {
|
||||
this.figureRequests.pipe(switchMap(request => request
|
||||
? defer(() => this.loadFigure(request.selection)).pipe(
|
||||
catchError(error => of({
|
||||
status: 'error',
|
||||
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
|
||||
&& (request.selection.periodos?.length ?? 0) > 1
|
||||
? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''),
|
||||
} as FigureState)),
|
||||
startWith({ status: 'loading' } as FigureState),
|
||||
map(state => ({ state, selection: request.selection, revision: request.revision, generation: request.generation })))
|
||||
: of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(({ state, selection, revision, generation }) => {
|
||||
if (generation === this.generation && revision === this.applied?.revision) {
|
||||
if (state.status === 'ready') {
|
||||
this.readySelection = selection;
|
||||
if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1
|
||||
? selection.periodos[0] : state.figure && donutPeriod(state.figure);
|
||||
}
|
||||
this.result.set(state);
|
||||
}
|
||||
});
|
||||
}
|
||||
private loadFigure(selection: FigureSelection) {
|
||||
if (this.dimension && selection.periodos?.length === 1 && this.capabilities.includes(this.dimension)) {
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo!, selection.periodos, this.indicador.version, { estrato: this.dimension }).pipe(map(data => {
|
||||
if (data.periodos.length !== 1 || data.periodos[0] !== selection.periodos![0]) throw new Error('Periodo estratificado inválido');
|
||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||
}));
|
||||
}
|
||||
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||
// Both panels, KPI and numeric table share the exact same transport key.
|
||||
// Do not catch /datos errors here: a backend failure is a real error state.
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(
|
||||
switchMap(data => {
|
||||
if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.');
|
||||
const periods = selection.periodos ?? data.periodos;
|
||||
if (selection.figura === 'fig_c2_donas' && periods.length > 1) {
|
||||
const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) }));
|
||||
if (pages.every(p => p.adapted.status === 'supported')) {
|
||||
return of(this.activateDonutPages(pages.map(({ period, adapted }) => {
|
||||
if (adapted.status !== 'supported') throw new Error('Periodo no soportado');
|
||||
return { period, state: { ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage } };
|
||||
})));
|
||||
}
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
: this.publishedFigure(selection, adapted.reason, data);
|
||||
}));
|
||||
}
|
||||
return this.publishedFigure(selection);
|
||||
}
|
||||
private publishedFigure(selection: FigureSelection, fallbackReason?: string, data?: IndicadorDatos) {
|
||||
return defer(() => this.service.figura(selection)).pipe(
|
||||
switchMap(figure => {
|
||||
const pages = donutPeriodFigures(figure, selection, data?.periodos);
|
||||
if (pages) return of(this.activateDonutPages(pages.map(({ period, figure: page }) => ({ period,
|
||||
state: { ...this.present(page, selection, data && donutHierarchy(page, periodDatos(data, period))),
|
||||
source: 'figuras' as const, fallbackReason,
|
||||
emptyMessage: !page.data.length ? 'No hay valores representables publicados para el periodo ' + period + '. Consulta las notas de la figura.' : undefined } }))));
|
||||
const period = this.indicador.contrato === 'C2'
|
||||
? donutPeriod(figure) : undefined;
|
||||
const present = (hierarchy?: DonutHierarchy) => ({ ...this.present(figure, selection, hierarchy), source: 'figuras' as const, fallbackReason });
|
||||
// A fallback has already read /datos; don't request a different subset.
|
||||
return !fallbackReason && period && selection.tipoPeriodo
|
||||
? this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, [period], this.indicador.version).pipe(
|
||||
map(data => present(donutHierarchy(figure, data))),
|
||||
// The optional hierarchy must never prevent the published figure.
|
||||
catchError(() => of(present())))
|
||||
: of(present());
|
||||
}));
|
||||
}
|
||||
private present(figure: NonNullable<FigureState['figure']>, selection: FigureSelection, hierarchy?: DonutHierarchy): FigureState {
|
||||
const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth);
|
||||
return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes,
|
||||
categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth, hierarchy,
|
||||
donutLegend: selection.figura === 'fig_c2_donas' && !hierarchy ? donutLegend(presentation.figure) : undefined,
|
||||
plotWidth: selection.figura === 'fig_c2_donas' && this.indicador.contrato === 'C2' && this.plotWidth !== undefined
|
||||
? (this.plotWidth < 480 ? 320 : 480) : undefined };
|
||||
}
|
||||
updatePlotWidth(width: number) {
|
||||
if (!Number.isFinite(width) || width <= 0 || Math.floor(width) === this.plotWidth) return;
|
||||
this.plotWidth = Math.floor(width);
|
||||
if (this.dimension) return;
|
||||
const state = this.result();
|
||||
const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas';
|
||||
if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut)
|
||||
&& state.status === 'ready' && state.figure && this.readySelection) {
|
||||
const presentation = this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
// A width change within the same label budget must not hide/repaint an
|
||||
// equivalent graph (for example when only the scrollbar gutter changes).
|
||||
if (JSON.stringify([next.presentationFigure, next.categoryLabels, next.minimumPlotWidth, next.plotWidth])
|
||||
!== JSON.stringify([state.presentationFigure, state.categoryLabels, state.minimumPlotWidth, state.plotWidth])) this.result.set(next);
|
||||
}
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
this.distributionAvailabilityId = this.titleId + '-distribution-availability';
|
||||
const key = this.requestKey();
|
||||
if (key === this.currentKey) {
|
||||
if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||
}
|
||||
const state = this.result();
|
||||
if (changes['visualProfile'] && state.status === 'ready' && 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;
|
||||
}
|
||||
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.indicador.version, this.tema, this.applied?.revision, this.applied && selectionKey(this.applied),
|
||||
this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId), this.dimension]);
|
||||
}
|
||||
requestFigure() {
|
||||
if (!this.visible) return;
|
||||
this.currentKey = this.requestKey();
|
||||
this.stratifiedData = undefined; this.cells = [];
|
||||
this.donutPages = [];
|
||||
const applied = this.applied;
|
||||
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
this.generation++;
|
||||
if (!this.indicador.figuras.includes(this.figuraId) || !compatibility.compatible) {
|
||||
this.figureRequests.next(null);
|
||||
this.result.set({ status: 'incompatible', message: !compatibility.compatible
|
||||
? compatibility.reason : 'Esta figura ya no está publicada en el catálogo.' });
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({ revision: applied.revision, generation: this.generation, selection: {
|
||||
dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId,
|
||||
tipoPeriodo: applied.tipo, tema: this.tema,
|
||||
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
|
||||
} });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
|
||||
describe('UX-06E.D.1 KPI presentacional', () => {
|
||||
it('presenta título y definición pendiente sin valores, unidades, fechas ni controles', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Indicador destacado 1'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('h3').textContent).toBe('Indicador destacado 1');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Pendiente de definición');
|
||||
expect(fixture.nativeElement.querySelector('.value')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('button, input, app-plotly-chart')).toBeNull();
|
||||
fixture.destroy();
|
||||
});
|
||||
it.each([null, undefined])('omite el valor opcional %s sin convertirlo a cero', value => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Presentación'); fixture.componentRef.setInput('value', value);
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.value')).toBeNull(); fixture.destroy();
|
||||
});
|
||||
it('admite contenido opcional suministrado por su consumidor sin servicios ni formatos impuestos', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
for (const [name, value] of Object.entries({ title: 'Título de prueba', value: 'Valor de prueba', unit: 'Unidad de prueba',
|
||||
temporalReference: 'Referencia de prueba', state: 'Estado de prueba', additionalInfo: 'Información de prueba' })) {
|
||||
fixture.componentRef.setInput(name, value);
|
||||
}
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
|
||||
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
fixture.destroy();
|
||||
});
|
||||
it('separa valor y unidad y reúne descripción y notas útiles en una sola línea', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Días de la toma al resultado');
|
||||
fixture.componentRef.setInput('value', 7.5);
|
||||
fixture.componentRef.setInput('unit', 'días (mediana)');
|
||||
fixture.componentRef.setInput('additionalInfo', '98 mastografías; Q1 a Q3: 3 a 11 días.');
|
||||
fixture.componentRef.setInput('notes', ['La referencia de 60 días es provisional.', 'La referencia de 60 días es provisional.']);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.value').firstChild.textContent.trim()).toBe('7.5');
|
||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('días (mediana)');
|
||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.value span')).marginInlineStart).toBe('0.3em');
|
||||
expect(fixture.nativeElement.querySelectorAll('.additional-info')).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('98 mastografías; Q1 a Q3: 3 a 11 días. La referencia de 60 días es provisional.');
|
||||
fixture.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-card',
|
||||
imports: [MatCardModule, MatProgressBarModule],
|
||||
template: `
|
||||
<mat-card [attr.aria-busy]="loading">
|
||||
<h3>{{ title }}</h3>
|
||||
@if (loading) { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + title" /> }
|
||||
@if (value !== null && value !== undefined) {
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||
border-radius: var(--issste-radius); box-shadow: none; }
|
||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@Input({ required: true }) title!: string;
|
||||
@Input() value?: string | number | null;
|
||||
@Input() unit?: string;
|
||||
@Input() temporalReference?: string;
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
@Input() additionalInfo?: string;
|
||||
get informationLine(): string | undefined {
|
||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||
return [...new Set(lines)].join(' ');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
|
||||
describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorKpiPanel>>;
|
||||
let http: HttpTestingController;
|
||||
const definition = KPI_BY_DOMAIN.cacu[0];
|
||||
const periods = ['2025-S2', '2025-S1', '2024-S2'];
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorKpiPanel], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadorKpiPanel);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
const availability = emptyAvailability('ready');
|
||||
availability.byIndicator[definition.id] = [periods[2], '2026-01', periods[0], periods[1]].map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' }));
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('definition', definition);
|
||||
fixture.componentRef.setInput('indicador', { id: definition.id, contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: [], titulo: definition.title });
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
fixture.componentRef.setInput('initialPresentation', true);
|
||||
fixture.componentRef.setInput('availability', availability);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function request(period: string) {
|
||||
return http.expectOne(r => r.url.endsWith('/datos') && r.params.get('periodos') === period);
|
||||
}
|
||||
function data(period: string, kind: 'visible' | 'suppressed' | 'incomplete' | 'null' = 'visible', value = 5) {
|
||||
return { id: definition.id, contrato: 'C2', tipo_periodo: 'semestre', periodos: [period],
|
||||
categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} },
|
||||
filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] };
|
||||
}
|
||||
it('consulta secuencialmente por 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());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
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 { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
describe('KPI integración con autoridad global', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
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(); });
|
||||
function load(domain: Dominio, missing = false, periods = ['2025-S1'], initial = domain === 'tea') {
|
||||
// Ordinary consumer tests begin after initialization; dedicated P0 suites
|
||||
// exercise the real shared search for all three domains.
|
||||
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
|
||||
function requests() { return http.match(r => r.url.endsWith('/datos')); }
|
||||
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 }] };
|
||||
}
|
||||
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
|
||||
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('TEA sin catálogo no muestra destacados ni consulta datos', () => {
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
||||
expect(panels().map(p => p.definition.id)).toEqual([]);
|
||||
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||
load('tea'); const initial = requests();
|
||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||
initial[0].flush(response(0, 'tea')); fixture.detectChanges();
|
||||
const req = requests();
|
||||
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
||||
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
});
|
||||
it('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);
|
||||
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');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
});
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '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);
|
||||
next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
apply(['2025-S2']); http.expectNone(() => true);
|
||||
});
|
||||
it('selección múltiple cancela, no consulta ni suma meses para un semestre', () => {
|
||||
load('cacu'); const pending = requests(); apply(['2025-01', '2025-02'], 'mes');
|
||||
expect(pending.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().state === 'Selección no consolidable')).toBe(true); http.expectNone(() => true);
|
||||
apply(['2025-01'], 'mes'); requests().forEach((r,i) => { expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush(response(i, 'cacu', '2025-01')); });
|
||||
});
|
||||
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
|
||||
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama')));
|
||||
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
||||
});
|
||||
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
||||
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.slice(1).map(d => d.id));
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(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 => {
|
||||
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 conserva los otros KPI y los filtros', () => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters);
|
||||
page.catalog.set(page.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before.slice(1)); expect(page.filters).toEqual(filters);
|
||||
expect(panels()).toHaveLength(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(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('Cargando catálogo');
|
||||
http.expectOne('/cacu/indicadores').flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(page.catalogError()).toBeTruthy(); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull(); expect(panels()).toHaveLength(0);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles');
|
||||
page.retryCatalog(); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges();
|
||||
expect(page.catalogError()).toBe(''); expect(page.catalogLoading()).toBe(false);
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin filas'] as const)('KPI publicado con resultado %s conserva tarjeta y definición', scenario => {
|
||||
load('cacu'); const before = panels();
|
||||
const data = response(1);
|
||||
if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1;
|
||||
if (scenario === 'nulo') data.filas[0]['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', () => {
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(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 Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true);
|
||||
const latest = requests(); expect(latest).toHaveLength(1);
|
||||
const hidden = response(0, 'cacu', '2025-S2'); hidden.filas[0]['suprimido'] = 1; latest[0].flush(hidden);
|
||||
requests()[0].flush(response(0)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => r.flush(response(i + 1))); fixture.detectChanges();
|
||||
expect(panels().every(p => p.temporalReference === '2025-S1')).toBe(true);
|
||||
const page = fixture.componentInstance; page.filters!.editors.semestre!.draft = { mode: 'todos' };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
requests().forEach((r, i) => { const data = response(i + 1, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); }); fixture.detectChanges();
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.temporalReference === '2025-S2')).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges();
|
||||
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
|
||||
}
|
||||
load('cacu', false, ['2025-S1'], true);
|
||||
expect(fixture.componentInstance.initialPeriodBlocked).toBe(false);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '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'], true);
|
||||
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
|
||||
const old = requests(); expect(old).toHaveLength(1);
|
||||
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
|
||||
requests().forEach((r, i) => r.flush(response(i, 'cama')));
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
|
||||
resumed[0].flush(response(0)); fixture.detectChanges();
|
||||
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
|
||||
expect(panels().every(p => p.temporalReference === '2025-S1')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicado explícito y luego Todos nunca buscan periodos anteriores', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1']); const outgoing = requests();
|
||||
apply(['2025-S1']); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
requests().forEach((r, i) => { const data = response(i); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const latest = requests(); expect(latest).toHaveLength(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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { Dominio, Indicador } from './indicadores.models';
|
||||
import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory';
|
||||
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi';
|
||||
import { PeriodAvailability, sortedPeriods } from './indicadores-periodos';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
|
||||
interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; version?: string; }
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-panel',
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="result().notes ?? []" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
styles: ':host { display: block; min-width: 0; }',
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) definition!: KpiDefinition;
|
||||
@Input() indicador?: Indicador;
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
private readonly queries = inject(IndicadoresKpiQueries);
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly requests = new Subject<void>();
|
||||
private key = '';
|
||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||
get temporalReference() {
|
||||
if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod();
|
||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||
}
|
||||
retry() { this.requests.next(); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap((): Observable<KpiDisplay> => {
|
||||
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
||||
this.usedPeriod.set(undefined);
|
||||
if (!applied) return of({ state: 'Esperando filtro aplicado' });
|
||||
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
|
||||
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
|
||||
if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' });
|
||||
let periods: string[];
|
||||
if (applied.selection.mode === 'todos') {
|
||||
if (!this.indicador) return of({ state: 'Sin reportes disponibles' });
|
||||
const availability = this.availability;
|
||||
if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true });
|
||||
if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' });
|
||||
const available = availability.byIndicator[definition.id];
|
||||
if (!available) return of({ state: 'Error de disponibilidad' });
|
||||
periods = sortedPeriods(available.filter(p => p.tipo === applied.tipo).map(p => p.periodo));
|
||||
if (!periods.length) return of({ state: 'Sin reportes disponibles' });
|
||||
if (!this.initialPresentation) periods = periods.slice(0, 1);
|
||||
} else periods = applied.selection.periodos;
|
||||
// One request per KPI at a time: the three configured panels start only after
|
||||
// the existing availability queue (concurrency four) has finished.
|
||||
const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable<KpiDisplay> => {
|
||||
const period = periods[index];
|
||||
const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } };
|
||||
return this.queries.datos(domain, definition.id, applied.tipo, period, this.indicador?.version).pipe(
|
||||
map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period,
|
||||
version: typeof data['version'] === 'string' ? data['version'] : undefined } as KpiDisplay)),
|
||||
catchError(error => of<KpiDisplay>({ period,
|
||||
state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta',
|
||||
info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })),
|
||||
switchMap(result => {
|
||||
// Network/contract transport failures stay visible and can be retried.
|
||||
if (result.state === 'Error de consulta') return of(result);
|
||||
if (result.state === 'Disponible' && result.value !== undefined) return of({ ...result, earlier: index > 0,
|
||||
info: [result.info, index > 0 && allSuppressed ? 'Existen reportes posteriores con datos ocultos por tamaño.' : ''].filter(Boolean).join(' ') });
|
||||
const first = latest ?? result;
|
||||
return index + 1 < periods.length
|
||||
? search(index + 1, first, allSuppressed && result.state === 'Dato oculto por tamaño') : of(first);
|
||||
}));
|
||||
};
|
||||
return search(0).pipe(startWith({ state: this.initialPresentation && applied.selection.mode === 'todos'
|
||||
? 'Buscando último dato visible…' : 'Cargando…', loading: true }));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(result => {
|
||||
this.usedPeriod.set(result.period);
|
||||
this.result.set(result);
|
||||
if (this.applied) this.snapshots.publishKpi(this.dominio, this.indicador ?? this.definition, this.applied,
|
||||
{ ...result, period: this.temporalReference, unit: this.definition.unit }, result.version);
|
||||
});
|
||||
}
|
||||
ngOnChanges() {
|
||||
const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied?.revision, this.applied && selectionKey(this.applied),
|
||||
this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]);
|
||||
if (key === this.key) return;
|
||||
this.key = key;
|
||||
this.requests.next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
:host { display: block; min-width: 0; overflow-wrap: anywhere; }
|
||||
section + section { margin-top: var(--issste-space-4); }
|
||||
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; }
|
||||
.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.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); }
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorMetadata } from './indicador-metadata';
|
||||
|
||||
function render(data: unknown) {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const fixture = TestBed.createComponent(IndicadorMetadata);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('indicador', 'future');
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores/future/metadatos').flush(data as Record<string, unknown>);
|
||||
fixture.detectChanges();
|
||||
return { fixture, http, text: fixture.nativeElement.textContent as string };
|
||||
}
|
||||
|
||||
describe('Metadatos metodológicos opcionales', () => {
|
||||
it('muestra descripción sin ficha y trata etiquetas recibidas como texto', () => {
|
||||
const { fixture, http, text } = render({ titulo: 'Título del catálogo', descripcion: 'Guía <img src=x onerror=alert(1)>\nSegunda línea', ficha: null });
|
||||
expect(text).toContain('Guía <img src=x onerror=alert(1)>');
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(text).toContain('Segunda línea');
|
||||
expect(text).not.toContain('Ficha metodológica');
|
||||
expect(text).not.toContain('Título del catálogo');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra todos los campos no vacíos de la ficha', () => {
|
||||
const { fixture, http, text } = render({
|
||||
descripcion: 'Información general.',
|
||||
ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' },
|
||||
});
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha 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 <em>edición 2</em>', ref: 'Indicador 7' }],
|
||||
poblaciones: [{ grupo: 'TOTAL', codigo: 'initial-population', descripcion: 'Pacientes con estudio publicado.' }],
|
||||
categorias: { NORMAL: { etiqueta: 'Normal' } },
|
||||
});
|
||||
expect(text).toContain('Descripción publicada.');
|
||||
expect(text).toContain('Guía publicada <em>edición 2</em> · Indicador 7');
|
||||
expect(text).toContain('Pacientes con estudio publicado.');
|
||||
expect(fixture.nativeElement.querySelector('em')).toBeNull();
|
||||
expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/);
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('conserva compatibilidad con el payload anterior que sólo trae categorías', () => {
|
||||
const { fixture, http, text } = render({ categorias: { NORMAL: { etiqueta: 'Normal' } } });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Normal');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('no anuncia ausencia cuando hay ficha utilizable aunque sus demás campos estén vacíos', () => {
|
||||
const { fixture, http, text } = render({ ficha: { codigo: ' IND-03 ' } });
|
||||
expect(text).toContain('IND-03'); expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, of, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, IndicadorMetadatos } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-metadata',
|
||||
styleUrl: './indicador-metadata.scss',
|
||||
template: `
|
||||
@if (loading) { <p role="status">Cargando información metodológica…</p> }
|
||||
@if (description; as text) {
|
||||
<section aria-labelledby="metadata-description-title">
|
||||
<h4 id="metadata-description-title">Descripción</h4>
|
||||
<p class="metadata-copy">{{ text }}</p>
|
||||
</section>
|
||||
}
|
||||
@if (fichaFields.length) {
|
||||
<section aria-labelledby="metadata-ficha-title">
|
||||
<h4 id="metadata-ficha-title">Ficha metodológica</h4>
|
||||
<dl class="ficha-fields">@for (field of fichaFields; track field.key) {
|
||||
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div>
|
||||
}</dl>
|
||||
</section>
|
||||
}
|
||||
@if (references.length) {
|
||||
<section aria-labelledby="metadata-references-title">
|
||||
<h4 id="metadata-references-title">Referencias</h4>
|
||||
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) { · {{ ref.ref }} }</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (populations.length) {
|
||||
<section aria-labelledby="metadata-populations-title">
|
||||
<h4 id="metadata-populations-title">Poblaciones del estudio</h4>
|
||||
<ul>@for (population of populations; track $index) { <li>{{ population.descripcion }}</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (!loading && !hasUsableMetadata) { <p>La información metodológica ampliada no está disponible para este indicador.</p> }
|
||||
`,
|
||||
})
|
||||
export class IndicadorMetadata implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: string;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly requests = new Subject<void>();
|
||||
metadata?: IndicadorMetadatos;
|
||||
loading = false;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly fichaLabels = [
|
||||
['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'],
|
||||
['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
|
||||
] as const;
|
||||
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
|
||||
get description() { return this.hasText(this.metadata?.descripcion) ? this.metadata!.descripcion!.trim() : undefined; }
|
||||
get fichaFields() {
|
||||
const ficha = this.metadata?.ficha;
|
||||
return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : [];
|
||||
}
|
||||
get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); }
|
||||
get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); }
|
||||
get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
ngOnChanges() { this.metadata = undefined; this.loading = true; this.requests.next(); }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Granularidad</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
|
||||
<mat-option value="todos">Todos con reporte</mat-option>
|
||||
<mat-option value="manual">Elegir periodos</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (entry.draft.mode !== 'todos') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
|
||||
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }} — disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
</div>
|
||||
@if (availability) {
|
||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||
@else if (availability.status === 'error') {
|
||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para esta granularidad.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields period-builder">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>{{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-label>
|
||||
<mat-select [(ngModel)]="unit">
|
||||
@for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { <mat-option [value]="value">{{ value }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button type="button" mat-stroked-button (click)="add()">Agregar periodo</button>
|
||||
</div>
|
||||
<div class="remove" aria-label="Eliminar periodos agregados">
|
||||
@for (period of entry.added; track period) {
|
||||
<button type="button" mat-button (click)="remove(period)" [attr.aria-label]="'Eliminar periodo ' + period">Eliminar {{ period }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
@@ -0,0 +1,19 @@
|
||||
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
|
||||
section { min-width: 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
||||
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
||||
.period-builder mat-form-field { flex: 0 1 10rem; }
|
||||
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
||||
p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; }
|
||||
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; }
|
||||
.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
.draft-summary { font-weight: 500; }
|
||||
.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); }
|
||||
.error { color: var(--mat-sys-error); }
|
||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||
.remove button { min-height: 44px; }
|
||||
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
|
||||
@media (max-width: 550px) {
|
||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
|
||||
.period-builder button { margin-top: 0; }
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
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<typeof TestBed.createComponent<IndicadorPeriodFilters>>;
|
||||
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-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
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<HTMLElement>);
|
||||
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();
|
||||
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('Filtro general aplicado: Todos con reporte');
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
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 { PeriodAvailability } from './indicadores-periodos';
|
||||
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[];
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
@Output() retryAvailability = new EventEmitter<void>();
|
||||
@Output() edited = new EventEmitter<void>();
|
||||
@Output() apply = new EventEmitter<void>();
|
||||
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 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'; }
|
||||
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 !== 'semestre' || 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.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();
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<br>%{x}<br>%{y:.1f}% (%{customdata[0]} de %{customdata[1]})<extra></extra>';
|
||||
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<string, unknown>)['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('<extra>', '<br>IC %{error_y.array}<extra>');
|
||||
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}<br>dato suprimido (conteo bajo)<extra></extra>'];
|
||||
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<br>dato suprimido (conteo bajo)<extra></extra>');
|
||||
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}<br>%{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<string, unknown>)['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}<br>%{x:.1f}%<extra></extra>' }], 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 + '<br>%{x:.1f}%<extra></extra>']);
|
||||
});
|
||||
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 ['<b>Texto extenso publicado</b>', 'Á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.<br>Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01<br>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([]);
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> {
|
||||
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<string, string> {
|
||||
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<string, number>();
|
||||
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<string, unknown>, coordinate: 'x' | 'y', size: number): string[] | undefined {
|
||||
const template = trace['hovertemplate'];
|
||||
const list = typeof template === 'string' ? Array<string>(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;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
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 { 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'] };
|
||||
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<string, Record<string, unknown>>).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('<extra></extra>');
|
||||
expect(final.data[0]['hovertemplate']).not.toContain('<extra>2025-S2');
|
||||
});
|
||||
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<string, Record<string, unknown>>).forEach(c => c['grupo'] = null);
|
||||
const result = supported(data);
|
||||
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();
|
||||
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<string, Record<string, unknown>>;
|
||||
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('<extra></extra>');
|
||||
expect(trace['hovertemplate']).not.toContain('<extra>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<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||
const figure = supported(data, { ...selection, tema }).figure;
|
||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']);
|
||||
expect(figure.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<string, any>)['line']).toMatchObject({ color: C2_PALETTE.claro.outline, width: 0.7 });
|
||||
const donut = supported(c2Fixture(), selection).figure;
|
||||
expect((donut.data[0]['marker'] as Record<string, any>)['line']).toMatchObject({ color: C2_PALETTE.claro.outline, width: 0.7 });
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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<string>();
|
||||
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<string, unknown> => !!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<number>(), ids = new Set<string>();
|
||||
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<string, unknown> = { title: { text: model.title + ' · ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
margin: { l: 76, r: 28, t: 112, b: 62, pad: 4 },
|
||||
legend: selection.figura === 'fig_c2_donas'
|
||||
? { 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}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
||||
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: '<b>' + total + '</b>', 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}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
|
||||
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
|
||||
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
|
||||
marker: { colors: parents.map((_, i) => 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 };
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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<typeof TestBed.createComponent<IndicadorFigurePanel>>, 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');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
<h2>Datos y definiciones · {{ domainNames[dominio] }}</h2>
|
||||
<section aria-labelledby="domain-info-title">
|
||||
<h3 id="domain-info-title">Información del dominio</h3>
|
||||
<p>Dominio: {{ domainNames[dominio] }}.</p>
|
||||
@if (!loading && !error && periodTypes.length) {
|
||||
<p>Periodicidad disponible:
|
||||
@for (tipo of periodTypes; track tipo; let last = $last) { {{ periodNames[tipo] }}{{ last ? '.' : ', ' }} }
|
||||
</p>
|
||||
} @else { <p>Periodicidad: pendiente de información.</p> }
|
||||
</section>
|
||||
<section aria-labelledby="definitions-catalog-title">
|
||||
<h3 id="definitions-catalog-title">Catálogo de indicadores</h3>
|
||||
<p>Consulta las gráficas disponibles y la periodicidad de cada indicador.</p>
|
||||
@if (loading) { <p role="status">Cargando catálogo de indicadores…</p> }
|
||||
@else if (error) {
|
||||
<p role="alert">No se pudo cargar la información del catálogo. {{ error }}</p>
|
||||
<button mat-stroked-button type="button" (click)="retry.emit()">Reintentar catálogo</button>
|
||||
} @else if (!catalog.length) { <p role="status">No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de información.</p> }
|
||||
@else {
|
||||
@for (item of catalog; track dominio + ':' + item.id) {
|
||||
<details (toggle)="open(item.id, $event)">
|
||||
<summary>{{ item.titulo || 'Nombre pendiente de publicación' }}</summary>
|
||||
<div class="indicator-detail">
|
||||
<h4>Representaciones disponibles</h4>
|
||||
@if (item.figuras.length) {
|
||||
<ul>@for (figure of item.figuras; track figure) { <li>{{ figureDisplayName(figure, item.figuras) }}</li> }</ul>
|
||||
} @else { <p>No hay representaciones publicadas.</p> }
|
||||
<h4>Tipos de periodo admitidos</h4>
|
||||
@if (item.tipos_periodo.length) {
|
||||
<ul>@for (tipo of item.tipos_periodo; track tipo) { <li>{{ periodNames[tipo] }}</li> }</ul>
|
||||
} @else { <p>Pendiente de información.</p> }
|
||||
<h4>Cómo interpretar este indicador</h4>
|
||||
@if (interpretation(item).length) {
|
||||
<ul>@for (line of interpretation(item); track $index) { <li>{{ line }}</li> }</ul>
|
||||
}
|
||||
@if (opened.has(dominio + ':' + item.id)) {
|
||||
<app-indicador-metadata [dominio]="dominio" [indicador]="item.id" />
|
||||
} @else {
|
||||
<p class="source">{{ item.contrato ? 'La información metodológica ampliada no está disponible para este indicador.' : 'La definición metodológica está pendiente de información.' }}</p>
|
||||
}
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="definitions-methodology-title">
|
||||
<h3 id="definitions-methodology-title">Interpretación y metodología</h3>
|
||||
<p>Ten en cuenta estas limitaciones al consultar las gráficas.</p>
|
||||
<ul>
|
||||
<li>Un valor nulo significa que no hay un valor disponible; un cero es un valor observado. Los datos suprimidos tampoco representan un cero.</li>
|
||||
<li>{{ periodInterpretation }}</li>
|
||||
<li>Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.</li>
|
||||
<li>Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por denominadores pequeños.</li>
|
||||
</ul>
|
||||
<p>Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. Las notas de cada gráfica incluyen detalles adicionales para interpretar los datos mostrados.</p>
|
||||
</section>
|
||||
@@ -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; }
|
||||
@@ -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<string>();
|
||||
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<void>();
|
||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
readonly periodNames: Record<TipoPeriodo, string> = { 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);
|
||||
}
|
||||
}
|
||||
@@ -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:'<b>4</b>',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: '<b>4</b>' })]);
|
||||
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<string, unknown>[])[0]['text'] = '<b>9</b>';
|
||||
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<string, unknown>[])[0]['text'] = '<b>100</b>';
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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: '<b>10</b>' }] } },
|
||||
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 })) },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
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; period?: string; }
|
||||
export interface DonutLegendEntry { label: string; color?: string; }
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
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<string, unknown>): trace is Record<string, unknown> & { 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<string, unknown>, 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<string, unknown> & { text: string } {
|
||||
return centerCountAt(value, 0.5, 0.5);
|
||||
}
|
||||
function centerCountAt(value: unknown, x: number, y: number): value is Record<string, unknown> & { text: string } {
|
||||
return record(value) && value['x'] === x && value['y'] === y
|
||||
&& value['xref'] === 'paper' && value['yref'] === 'paper' && value['showarrow'] === false
|
||||
&& typeof value['text'] === 'string' && /^<b>\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.
|
||||
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<string>();
|
||||
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<string>();
|
||||
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 = 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];
|
||||
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<string, unknown> = 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,
|
||||
};
|
||||
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}<br>%{value}' + unit + ' (%{percent} del total de esta dona)<extra></extra>' };
|
||||
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}<br>%{value}' + unit + ' (%{percent} del grupo)<extra></extra>' },
|
||||
{ ...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: '<b>' + value + '</b>' } : a);
|
||||
return figure;
|
||||
}
|
||||
@@ -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 + '<br>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] + '<br>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] + '<br>N publicado' })]));
|
||||
expect(pages[1].figure.layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '<br>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<typeof TestBed.createComponent<IndicadorFigurePanel>>, 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<HTMLButtonElement>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!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, unknown>): 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 };
|
||||
});
|
||||
}
|
||||
@@ -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'] : [];
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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<Record<string, string>> = {
|
||||
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';
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { Indicador, TipoPeriodo } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const item = (id: string, types: TipoPeriodo[] = ['semestre', 'mes']): Indicador =>
|
||||
({ id, titulo: id, contrato: 'C1', figuras: ['f'], tipos_periodo: types });
|
||||
describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
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);
|
||||
});
|
||||
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).filter(p => p.result().status !== 'deferred'); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
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[]) {
|
||||
const control = editor(); control.changeTipo(tipo); control.changeMode('manual');
|
||||
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
|
||||
}
|
||||
function apply() { page.applyFilters(); fixture.detectChanges(); }
|
||||
|
||||
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.initialPeriodState()).toBe('ready');
|
||||
apply();
|
||||
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);
|
||||
});
|
||||
|
||||
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('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]);
|
||||
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(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
|
||||
load(); open(); respond(); const result = panels()[0].result();
|
||||
editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
draft('semestre', ['2025-S1']); fixture.detectChanges();
|
||||
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
});
|
||||
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].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);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond();
|
||||
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
|
||||
editor().select(['2025-S2', '2025-S1']); apply();
|
||||
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
||||
});
|
||||
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].setVisible(true); fixture.detectChanges();
|
||||
const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} });
|
||||
cards()[1].setVisible(true); fixture.detectChanges(); 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].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', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(0); open(1); respond();
|
||||
const panel = panels()[0], host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('mes', ['2025-01']); apply();
|
||||
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((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
r.flush({ data: [], layout: {} });
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
});
|
||||
it('incompatibilidad cancela solicitud pendiente y no queda cargando', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(); const old = request('a');
|
||||
draft('mes', ['2025-01']); apply(); expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('incompatible');
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); http.expectNone(() => true);
|
||||
});
|
||||
it('dos revisiones cancelan respuestas anteriores y carga oculta resultado previo conservando host', () => {
|
||||
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().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);
|
||||
});
|
||||
it('404 y reintento individual usan aplicado vigente y conservan borrador y otra figura', () => {
|
||||
load(); open(0); open(1); respond(); draft('semestre', ['2025-S1']); apply();
|
||||
request('a').flush('private', { status: 404, statusText: 'Not Found' }); request('b').flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const other = panels()[1].result(); editor().select([]); panels()[0].requestFigure();
|
||||
const retry = request('a'); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} }); expect(panels()[1].result()).toBe(other); expect(editor().entry.draft.mode).toBe('empty');
|
||||
});
|
||||
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().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'] });
|
||||
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();
|
||||
page.retryCatalog(); fixture.detectChanges(); load([item('a', ['semestre'])]);
|
||||
expect(page.filters!.applied.tipo).toBe('mes'); expect(page.filters!.applied.revision).toBe(1);
|
||||
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);
|
||||
});
|
||||
it('orden del catálogo no permite simular Todos mensual', () => {
|
||||
load([item('a', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
draft('mes', ['2025-01']); apply(); request('a').flush({ data: [], layout: {} });
|
||||
});
|
||||
});
|
||||
@@ -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.';
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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('-');
|
||||
}
|
||||
@@ -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<typeof TestBed.createComponent<IndicadoresPage>>, 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<string, string>([[domain, periods[1]]]);
|
||||
const catalogs = new Map<string, typeof items>([[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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<AvailablePeriod | undefined> {
|
||||
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<AvailablePeriod | undefined> => {
|
||||
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);
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
// /cama/indicadores/<id>/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<string, IndicadorDatos> = {
|
||||
"cama_birads_456_paciente": {
|
||||
"id": "cama_birads_456_paciente",
|
||||
"contrato": "C2",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"categorias": {
|
||||
"B4A": {},
|
||||
"B4B": {},
|
||||
"B4C": {},
|
||||
"B5": {},
|
||||
"B6": {},
|
||||
"SIN_DATO": {}
|
||||
},
|
||||
"filas": [
|
||||
{
|
||||
"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.');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { Dominio, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresKpiQueries {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { KPI_BY_DOMAIN, 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 };
|
||||
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): 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(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
|
||||
const c1Group = domain === 'tea' ? 'TOTAL' : 'total';
|
||||
const run = (index: number, rows: Record<string, unknown>[]) => 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: 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: 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', () => {
|
||||
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');
|
||||
});
|
||||
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' });
|
||||
});
|
||||
it.each([0, 1, 2])('nulos en %s no se convierten en cero', index => {
|
||||
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', () => {
|
||||
for (const rows of [[{ ...total, categoria: 'A', n: 5 }, { ...total, grupo: 'OTHER', categoria: 'A', n: 5 }],
|
||||
[{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'A', n: 5 }], [{ ...total, categoria: 'A', n: 5, estrato: 'edad' }]]) {
|
||||
expect(run(0, rows).state).toBe('Selección no consolidable');
|
||||
}
|
||||
});
|
||||
it('Todos con reporte con varios periodos es no consolidable, aun si uno no tiene filas', () => {
|
||||
const d = data(domain, 0, [{ ...total, categoria: 'A', n: 5 }]); d.periodos.push('2025-S2');
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN[domain][0], domain, { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable');
|
||||
});
|
||||
it('sin filas tiene estado explícito y contrato equivocado no produce cifra', () => {
|
||||
expect(run(0, []).state).toBe('Sin filas utilizables'); const d = data(domain, 0, []); d.contrato = 'C1';
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN[domain][0], domain, applied).state).toBe('Error de contrato');
|
||||
});
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
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 (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<Dominio, KpiDefinition[]> = {
|
||||
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: '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_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: '%' },
|
||||
{ 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<Dominio, string> = { tea: 'TOTAL', cacu: 'total', cama: 'total' };
|
||||
const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => 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<Dominio, (n: number, q1: number, q3: number) => 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.`,
|
||||
};
|
||||
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;
|
||||
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
||||
|
||||
// C2 definitions count each patient once per period, in disjoint categories of TOTAL.
|
||||
// C1/C3r publish a single total row. Never combine totals, strata, or periods.
|
||||
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
|
||||
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
|
||||
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
|
||||
}
|
||||
if (!data.periodos.length && !data.filas.length) return { state: 'Sin filas utilizables' };
|
||||
if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped;
|
||||
const period = data.periodos[0];
|
||||
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' ? 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' };
|
||||
if (rows.some(row => row['suprimido'] !== 0)) return { state: 'Sin filas utilizables', info: 'No se puede determinar el estado de supresión.' };
|
||||
const empty = { state: 'Sin valor disponible' };
|
||||
const row = rows[0];
|
||||
if (definition.contrato === 'C2') {
|
||||
const categories = rows.map(row => row['categoria']);
|
||||
if (categories.some(c => typeof c !== 'string' || !c) || new Set(categories).size !== categories.length) return unscoped;
|
||||
const catalog = data['categorias'];
|
||||
if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) return { state: 'Error de contrato', info: 'Falta el catálogo de categorías para verificar el total.' };
|
||||
const expected = Object.keys(catalog);
|
||||
if (expected.length !== categories.length || expected.some(c => !categories.includes(c))) return { state: 'Sin filas utilizables', info: 'Las categorías recibidas no permiten verificar un total completo.' };
|
||||
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: '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;
|
||||
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: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { TipoPeriodo } from './indicadores.models';
|
||||
import { applyGlobal, domainTypes, filterCompatibility, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
|
||||
describe('D.2 memoria global por dominio', () => {
|
||||
let memory: IndicadoresMemory;
|
||||
beforeEach(() => { TestBed.configureTestingModule({}); memory = TestBed.inject(IndicadoresMemory); });
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('inicia %s con Todos y revisión cero', domain => {
|
||||
const state = memory.restoreGlobal(domain, ['semestre', 'mes']);
|
||||
expect(state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
expect(state.editors.mes?.draft.mode).toBe('empty'); expect(pending(state)).toBe(false);
|
||||
});
|
||||
it('guarda y restaura borrador y aplicado con copias defensivas', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre', 'mes']);
|
||||
state.tipo = 'mes'; state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } };
|
||||
memory.saveGlobal('tea', state); state.editors.mes.added.push('2025-02');
|
||||
const restored = memory.restoreGlobal('tea', ['semestre', 'mes']);
|
||||
expect(restored.editors.mes?.added).toEqual(['2025-01']); expect(restored.applied.tipo).toBe('semestre');
|
||||
restored.editors.mes!.added.length = 0;
|
||||
expect(memory.restoreGlobal('tea', ['semestre', 'mes']).editors.mes?.added).toEqual(['2025-01']);
|
||||
});
|
||||
it('aísla los tres dominios sin tomar selecciones de figuras', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre']);
|
||||
state.editors.semestre = { added: ['2025-S1'], draft: { mode: 'explicit', periodos: ['2025-S1'] } };
|
||||
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 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');
|
||||
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.restoreGlobal('tea', ['semestre']).applied.revision).toBe(0);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); read.mockRestore(); write.mockRestore();
|
||||
});
|
||||
it('preserva selección ante pérdida de capacidades y explica incompatibilidad', () => {
|
||||
const state = memory.restoreGlobal('cacu', ['semestre', 'mes']);
|
||||
state.tipo = 'mes'; state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } };
|
||||
applyGlobal(state, ['semestre', 'mes']); memory.saveGlobal('cacu', state);
|
||||
const restored = memory.restoreGlobal('cacu', ['semestre']);
|
||||
expect(restored.applied).toEqual(state.applied); expect(restored.tipo).toBe('mes');
|
||||
expect(filterCompatibility(restored.applied, ['semestre']).compatible).toBe(false);
|
||||
});
|
||||
it('deduplica por semántica, incluido orden de periodos, sin incrementar revisión', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre']);
|
||||
state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] };
|
||||
expect(applyGlobal(state, ['semestre'])).toBe(true); const applied = state.applied;
|
||||
state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2', '2025-S1'] };
|
||||
expect(applyGlobal(state, ['semestre'])).toBe(false); expect(state.applied).toBe(applied); expect(applied.revision).toBe(1);
|
||||
});
|
||||
it('rechaza vacío sin sustituirlo por Todos', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre']); state.editors.semestre!.draft = { mode: 'empty' };
|
||||
expect(applyGlobal(state, ['semestre'])).toBe(false); expect(state.applied.revision).toBe(0);
|
||||
});
|
||||
it('oferta unión publicada ordenada sin inventar capacidades', () => {
|
||||
expect(domainTypes([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f'], tipos_periodo: ['mes', 'semestre'] }])).toEqual(['semestre', 'mes']);
|
||||
expect(domainTypes([])).toEqual([]);
|
||||
});
|
||||
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', () => {
|
||||
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);
|
||||
expect(filterCompatibility(applied, ['semestre']).compatible).toBe(false); expect(JSON.stringify(applied)).toBe(snapshot);
|
||||
expect(filterCompatibility({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }, ['mes', 'semestre']).compatible).toBe(false);
|
||||
});
|
||||
});
|
||||
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(false);
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { Injectable, signal } 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<PeriodDraft, { mode: 'empty' }>;
|
||||
export interface PeriodEditor { added: string[]; draft: PeriodDraft; }
|
||||
export interface FilterState {
|
||||
tipo: TipoPeriodo;
|
||||
editors: Partial<Record<TipoPeriodo, PeriodEditor>>;
|
||||
applied?: { tipo: TipoPeriodo; selection: AppliedPeriods };
|
||||
}
|
||||
export interface GlobalApplied { tipo: TipoPeriodo; selection: AppliedPeriods; revision: number; }
|
||||
export interface GlobalFilterState extends FilterState { applied: GlobalApplied; }
|
||||
export function newEditor(tipo: TipoPeriodo, first: TipoPeriodo): PeriodEditor {
|
||||
return { added: [], draft: tipo === 'semestre' && 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 === 'semestre' && 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 con reporte (semestres)'
|
||||
: draft.mode === 'empty' ? 'Sin periodos seleccionados' : draft.periodos.join(', ');
|
||||
}
|
||||
export function selectionKey(applied: Pick<GlobalApplied, 'tipo' | 'selection'>): string {
|
||||
return JSON.stringify([applied.tipo, applied.selection.mode,
|
||||
applied.selection.mode === 'explicit' ? [...applied.selection.periodos].sort() : []]);
|
||||
}
|
||||
export function pending(state: FilterState): boolean {
|
||||
const draft = state.editors[state.tipo]?.draft;
|
||||
return !state.applied || !draft || draft.mode === 'empty'
|
||||
|| selectionKey(state.applied) !== selectionKey({ tipo: state.tipo, selection: draft });
|
||||
}
|
||||
export function domainTypes(items: readonly Indicador[]): TipoPeriodo[] {
|
||||
return (['semestre', 'mes'] as const).filter(tipo => items.some(item => item.tipos_periodo.includes(tipo)));
|
||||
}
|
||||
export type Compatibility = { compatible: true } | { compatible: false; reason: string };
|
||||
// Published capabilities only; this adapter never changes a selection or probes HTTP.
|
||||
// Future consumers may use the same capability list without defining a KPI contract here.
|
||||
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.' };
|
||||
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.' };
|
||||
return { compatible: true };
|
||||
}
|
||||
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
||||
const draft = state.editors[state.tipo]?.draft;
|
||||
if (!draft || !validDraft(draft, state.tipo, types) || !pending(state)) return false;
|
||||
state.applied = { tipo: state.tipo, selection: structuredClone(draft), revision: state.applied.revision + 1 };
|
||||
return true;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresMemory {
|
||||
private readonly manuallyApplied = new Set<Dominio>();
|
||||
initialKpiPresentation(domain: Dominio) { return !this.manuallyApplied.has(domain); }
|
||||
finishInitialKpiPresentation(domain: Dominio) { this.manuallyApplied.add(domain); }
|
||||
private readonly pinnedIndicators = signal<ReadonlySet<string>>(new Set());
|
||||
isPinned(domain: Dominio, indicador: string) {
|
||||
return this.pinnedIndicators().has(JSON.stringify([domain, indicador]));
|
||||
}
|
||||
togglePinned(domain: Dominio, indicador: string) {
|
||||
const key = JSON.stringify([domain, indicador]);
|
||||
this.pinnedIndicators.update(current => {
|
||||
const next = new Set(current);
|
||||
if (next.has(key)) next.delete(key); else next.add(key);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
private readonly themes = new Map<Dominio, Tema>();
|
||||
private readonly figures = new Map<string, string>();
|
||||
figure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); }
|
||||
rememberFigure(domain: Dominio, indicador: string, figure: string) {
|
||||
this.figures.set(JSON.stringify([domain, indicador]), figure);
|
||||
}
|
||||
private readonly filters = new Map<Dominio, GlobalFilterState>();
|
||||
theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; }
|
||||
rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); }
|
||||
saveGlobal(domain: Dominio, state: GlobalFilterState) {
|
||||
this.filters.set(domain, structuredClone(state));
|
||||
}
|
||||
restoreGlobal(domain: Dominio, types: TipoPeriodo[]): GlobalFilterState {
|
||||
const stored = this.filters.get(domain);
|
||||
const state: GlobalFilterState = stored ? structuredClone(stored) : {
|
||||
tipo: 'semestre', editors: { semestre: newEditor('semestre', 'semestre') },
|
||||
applied: { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 },
|
||||
};
|
||||
for (const tipo of types) state.editors[tipo] ??= newEditor(tipo, 'semestre');
|
||||
// Preserve an application whose capabilities changed: consumers explain incompatibility,
|
||||
// rather than silently replacing or trimming the user's temporal selection.
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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.
|
||||
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
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 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
|
||||
? '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.'];
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
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 { 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';
|
||||
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', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
|
||||
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, kpiQueriesProvider] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
return RouterTestingHarness.create();
|
||||
}
|
||||
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.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(); 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);
|
||||
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');
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
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); harness.detectChanges();
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
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.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);
|
||||
const req = load('tea', harness);
|
||||
expect(req.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).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); 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();
|
||||
(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);
|
||||
const req = load('cacu', harness);
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||
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');
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
expect(req.request.params.get('tema')).toBe('claro');
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> => 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' };
|
||||
});
|
||||
}
|
||||
@@ -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<typeof TestBed.createComponent<IndicadorCatalogCard>>, 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<HTMLButtonElement>].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);
|
||||
});
|
||||
});
|
||||
@@ -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: `
|
||||
<details (toggle)="toggle($event)">
|
||||
<summary><h2>Resumen de indicadores</h2></summary>
|
||||
<p>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.</p>
|
||||
<div class="table-scroll" role="region" aria-label="Resultados numéricos de indicadores" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados de indicadores destacados y gráficas consultadas</caption>
|
||||
<thead><tr><th scope="col">Indicador</th><th scope="col">Periodo</th><th scope="col">Grupo / categoría</th><th scope="col">Resultado</th><th scope="col">Estado y notas</th></tr></thead>
|
||||
<tbody>
|
||||
@for (definition of kpis; track definition.id) {
|
||||
@let item = find(definition.id);
|
||||
@if (item) {
|
||||
@let kpi = snapshots.kpis().get(key(item));
|
||||
<tr class="kpi-reading"><th scope="row">{{ definition.title }} <span class="kind">Destacado</span></th>
|
||||
<td>{{ kpi?.period ?? period }}</td><td>—</td>
|
||||
<td>{{ kpi?.value ?? 'No disponible' }} @if (kpi?.value !== undefined) { {{ kpi?.unit }} }</td>
|
||||
<td>{{ kpi?.state ?? 'Pendiente de lectura' }} {{ kpi?.info }} {{ kpi?.notes?.join(' ') }}</td></tr>
|
||||
}
|
||||
}
|
||||
@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) {
|
||||
<tr><th scope="row">{{ item.titulo }}</th><td>{{ row.period }}</td><td>{{ row.group }} · {{ row.category }}</td>
|
||||
<td>{{ row.value }} <span class="detail">{{ row.detail }}</span></td><td>{{ row.state }} {{ data.notas?.join(' ') }}</td></tr>
|
||||
} @empty {
|
||||
<tr><th scope="row">{{ item.titulo }}</th><td>{{ period }}</td><td>—</td><td>Sin filas publicadas</td><td>{{ data.notas?.join(' ') }}</td></tr>
|
||||
}
|
||||
} @else {
|
||||
<tr><th scope="row">{{ item.titulo }}</th><td>{{ period }}</td><td>—</td><td>No disponible</td>
|
||||
<td>{{ !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') { <button type="button" (click)="snapshots.retries.update(increment)" [attr.aria-label]="'Reintentar números de ' + item.titulo">Reintentar</button> }</td></tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>`,
|
||||
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); }
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<section class="dashboard" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
<span class="domain">Dominio {{ domainLabels[dominio] }} · Investigación</span>
|
||||
<h1 id="dashboard-title">Dashboard de indicadores</h1>
|
||||
<p>Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.</p>
|
||||
</header>
|
||||
<nav aria-label="Dominios de indicadores">
|
||||
@for (domain of dominios; track domain) {
|
||||
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainLabels[domain] }}</a>
|
||||
}
|
||||
</nav>
|
||||
|
||||
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
|
||||
@for (section of sections; track section.id) {
|
||||
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
|
||||
[attr.aria-selected]="activeSection() === section.id" [tabIndex]="activeSection() === section.id ? 0 : -1"
|
||||
(click)="changeSection(section.id)">{{ section.label }}</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
|
||||
@if (!catalogLoading() && filters; as state) {
|
||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
||||
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
|
||||
<p class="section-description">La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.</p>
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
||||
(retryAvailability)="retryAvailability()"
|
||||
(edited)="editFilters()" (apply)="applyFilters()" />
|
||||
</section>
|
||||
}
|
||||
@if (initialPeriodState() === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" [attr.aria-label]="'Buscando periodo inicial de ' + domainLabels[dominio]" />
|
||||
<p role="status">Buscando el periodo más reciente con un conteo válido y positivo en «{{ initialPeriodAnchorTitle }}»…</p>
|
||||
} @else if (initialPeriodState() === 'error') {
|
||||
<mat-card role="alert"><p>No se pudo determinar el periodo inicial de {{ domainLabels[dominio] }}. {{ initialPeriodError() }}</p>
|
||||
<button mat-stroked-button (click)="retryInitialPeriod()">Reintentar periodo inicial</button>
|
||||
<p>También puedes seleccionar un periodo y pulsar Aplicar.</p></mat-card>
|
||||
} @else if (initialPeriodState() === 'empty') {
|
||||
<p role="status">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.</p>
|
||||
<button mat-stroked-button (click)="retryInitialPeriod()">Reintentar periodo inicial</button>
|
||||
} @else if (initialPeriodState() === 'unavailable') {
|
||||
<p role="status">El indicador de referencia para el periodo inicial ya no está publicado. Selecciona un periodo y pulsa Aplicar para consultar los indicadores vigentes.</p>
|
||||
} @else if (initialPeriodState() === 'manual') {
|
||||
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
|
||||
}
|
||||
@let kpis = availableKpis;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores destacados</h2>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length">
|
||||
@for (definition of kpis; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||
<div class="catalog-heading">
|
||||
<h2 id="graphic-section-title" class="section-title">Indicadores gráficos</h2>
|
||||
@if (!catalogLoading() && !catalogError() && catalog().length) {
|
||||
<p class="catalog-count" role="status">{{ catalog().length }} indicadores publicados</p>
|
||||
}
|
||||
</div>
|
||||
@if (catalogLoading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
|
||||
<p role="status">Cargando catálogo de indicadores…</p>
|
||||
} @else if (catalogError()) {
|
||||
<mat-card class="state" role="alert"><p>{{ catalogError() }}</p>
|
||||
<button mat-stroked-button (click)="retryCatalog()">Reintentar catálogo</button></mat-card>
|
||||
} @else if (!catalog().length) {
|
||||
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
|
||||
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
|
||||
} @else if (!initialPeriodBlocked) {
|
||||
@if (searchVisible()) {
|
||||
<div class="catalog-search">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Buscar indicadores</mat-label>
|
||||
<input #searchInput matInput type="search" [ngModel]="searchQuery()" (ngModelChange)="changeSearchQuery($event)"
|
||||
placeholder="Título o identificador" aria-describedby="catalog-search-help catalog-search-result" />
|
||||
<button mat-icon-button matIconSuffix type="button" (click)="clearSearch()" [disabled]="!searchQuery()"
|
||||
aria-label="Limpiar búsqueda"><mat-icon aria-hidden="true">close</mat-icon></button>
|
||||
<mat-hint id="catalog-search-help">Las coincidencias aparecen primero; todos los indicadores siguen visibles.</mat-hint>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
<p id="catalog-search-result" class="search-result">
|
||||
@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; los indicadores fijados aparecen primero.
|
||||
}
|
||||
}
|
||||
</p>
|
||||
}
|
||||
<div class="catalog-grid">
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="filters!.applied"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
@if (!initialPeriodBlocked && filters && !catalogLoading() && !catalogError() && catalog().length) {
|
||||
<app-indicadores-numeric-summary [dominio]="dominio" [catalog]="catalog()" [applied]="filters.applied" [kpis]="availableKpis" />
|
||||
}
|
||||
</div>
|
||||
|
||||
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-seguimiento" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'" />
|
||||
</section>
|
||||
|
||||
<section id="panel-datos" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-datos" tabindex="0" [hidden]="activeSection() !== 'datos'">
|
||||
<app-indicadores-definitions [dominio]="dominio" [catalog]="catalog()" [loading]="catalogLoading()" [error]="catalogError()" (retry)="retryCatalog()" />
|
||||
</section>
|
||||
</section>
|
||||
@@ -0,0 +1,75 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
|
||||
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); }
|
||||
.state { padding: 1.25rem; margin: 0; }
|
||||
.section-title { font-family: var(--issste-font-heading); font-size: 1.5rem; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
|
||||
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
|
||||
.kpi-section, .graphic-section { min-width: 0; }
|
||||
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
|
||||
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
.catalog-grid { align-items: start; }
|
||||
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
|
||||
.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
|
||||
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.catalog-search { display: flex; justify-content: flex-end; margin-top: var(--issste-space-4); }
|
||||
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
|
||||
.catalog-search button { width: 48px; height: 48px; }
|
||||
.catalog-search button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; }
|
||||
// Keep search semantics; Material supplies the single accessible clear control.
|
||||
.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(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
|
||||
nav {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--issste-space-2);
|
||||
padding: var(--issste-space-2);
|
||||
justify-content: center;
|
||||
margin: var(--issste-space-4) 0;
|
||||
border-radius: var(--issste-radius);
|
||||
}
|
||||
nav a {
|
||||
flex: 0 1 6rem;
|
||||
max-width: 10rem;
|
||||
color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border);
|
||||
background: var(--issste-surface);
|
||||
min-height: 44px;
|
||||
border-radius: var(--issste-radius);
|
||||
}
|
||||
nav a[aria-current='page'] {
|
||||
background: var(--issste-accent);
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
@media (max-width: 550px) {
|
||||
h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); }
|
||||
nav { gap: var(--issste-space-2); padding-inline: 0; }
|
||||
}
|
||||
|
||||
.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; } }
|
||||
@@ -0,0 +1,335 @@
|
||||
import { periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { 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', 'label', 'showNotes'], template: '' })
|
||||
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-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
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; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
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();
|
||||
}
|
||||
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).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 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('no presenta destacados retirados del catálogo ni consulta sus datos', () => {
|
||||
load();
|
||||
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([]);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => {
|
||||
fixture.detectChanges();
|
||||
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(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.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', () => {
|
||||
load(); const before = cards();
|
||||
const grid = fixture.nativeElement.querySelector('.catalog-grid') as HTMLElement;
|
||||
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('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
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();
|
||||
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.visible)).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).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');
|
||||
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';
|
||||
load([{ ...item, titulo: title }, second]);
|
||||
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.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', () => {
|
||||
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<HTMLElement>;
|
||||
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-06D retira el selector visual, inicia claro y conserva oscuro sin recargar catálogo', async () => {
|
||||
load();
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.global-filters mat-select')).toBeTruthy();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Tema del dominio');
|
||||
expect(page.tema).toBe('claro');
|
||||
page.changeTema('oscuro'); fixture.detectChanges();
|
||||
expect(page.tema).toBe('oscuro');
|
||||
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.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('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('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].visible).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles');
|
||||
expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
it('varias tarjetas y figuras abiertas mantienen solicitudes concurrentes independientes', () => {
|
||||
load(); toggle(0); const a = request('f1'); toggle(1); const c = request('g');
|
||||
expect(a.cancelled).toBe(false);
|
||||
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.visible)).toBe(true);
|
||||
});
|
||||
it('retirar una tarjeta cancela solo su solicitud y destruye su panel', () => {
|
||||
load(); toggle(); toggle(1); const a = request('f1'), c = request('g');
|
||||
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]);
|
||||
});
|
||||
it('404 y reintento afectan solo una figura y 200 sin puntos sigue siendo resultado', () => {
|
||||
load(); toggle(); toggle(1); const a = request('f1'), b = request('g');
|
||||
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');
|
||||
panels()[0].requestFigure(); request('f1').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control();
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
const appliedA = request('f1');
|
||||
expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
|
||||
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');
|
||||
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 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();
|
||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||
const result = panel.result();
|
||||
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);
|
||||
expect(filters.entry.draft).toEqual(draft); expect(page.filters!.applied).toEqual(applied);
|
||||
http.expectNone(() => true);
|
||||
}
|
||||
});
|
||||
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(); 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);
|
||||
});
|
||||
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');
|
||||
expect(darkA.request.params.get('tema')).toBe('oscuro'); http.expectNone(r => r.url.endsWith('/g'));
|
||||
darkA.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');
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); expect(a.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 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].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].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];
|
||||
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).rememberFigure('tea', 'removed', 'f1');
|
||||
load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll();
|
||||
});
|
||||
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<HTMLElement>).map(e => e.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
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' }] } };
|
||||
const before = JSON.stringify(raw); request('f1').flush(raw); request('g').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); toggle(); flushAll();
|
||||
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('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', () => {
|
||||
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), 'saveGlobal');
|
||||
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(writes).not.toHaveBeenCalled(); expect(saves).not.toHaveBeenCalled();
|
||||
expect(panels()[0].result()).toBe(state); http.expectNone(() => true);
|
||||
});
|
||||
it('UX-06D retira solo el aviso general del catálogo', () => {
|
||||
load(); expect(fixture.nativeElement.querySelector('.notice')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
|
||||
});
|
||||
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 mat-select') as NodeListOf<HTMLElement>;
|
||||
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]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,358 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { afterEveryRender, afterNextRender, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, inject, computed, signal, viewChild, viewChildren } 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 { 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, 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 { 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, 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<DashboardSection>('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<HTMLButtonElement>('[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<HTMLElement>>(ElementRef);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput');
|
||||
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
|
||||
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
|
||||
private renderedCards: readonly IndicadorCatalogCard[] = [];
|
||||
private visibilityObserver?: IntersectionObserver;
|
||||
private sizeObserver?: ResizeObserver;
|
||||
private readonly sizeTargets = new Set<Element>();
|
||||
private frame?: number;
|
||||
private stickyHeight = -1;
|
||||
private visibilityDestroyed = false;
|
||||
private readonly viewportChanged = () => this.visibilityChanged();
|
||||
|
||||
visibilityChanged() {
|
||||
this.queueVisibility();
|
||||
}
|
||||
private queueVisibility() {
|
||||
const browser = this.document.defaultView;
|
||||
if (this.visibilityDestroyed || !this.visibilityObserver || !browser || this.frame !== undefined) return;
|
||||
this.frame = browser.requestAnimationFrame(() => {
|
||||
this.frame = undefined;
|
||||
this.evaluateVisibility();
|
||||
});
|
||||
}
|
||||
private clearVisibility() {
|
||||
this.visibilityObserver?.disconnect();
|
||||
this.visibilityObserver = undefined;
|
||||
this.observedRegions.clear();
|
||||
this.renderedCards = [];
|
||||
if (this.frame !== undefined) this.document.defaultView?.cancelAnimationFrame(this.frame);
|
||||
this.frame = undefined;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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 [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 region = card.visibilityRegion?.nativeElement;
|
||||
if (region && !this.observedRegions.has(region)) {
|
||||
this.observedRegions.set(region, card);
|
||||
this.visibilityObserver?.observe(region);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this.sizeObserver ??= new ResizeObserver(this.viewportChanged);
|
||||
const targets = [this.document.querySelector('.institutional-header'), this.element.nativeElement.querySelector('.catalog-grid')]
|
||||
.filter((target): target is Element => target !== null);
|
||||
for (const target of this.sizeTargets) {
|
||||
if (!targets.includes(target)) { this.sizeObserver.unobserve(target); this.sizeTargets.delete(target); }
|
||||
}
|
||||
for (const target of targets) {
|
||||
if (!this.sizeTargets.has(target)) { this.sizeTargets.add(target); this.sizeObserver.observe(target); }
|
||||
}
|
||||
}
|
||||
if (changed) this.visibilityChanged();
|
||||
}
|
||||
private refreshVisibilityObserver() {
|
||||
const height = Math.max(0, this.document.querySelector('.institutional-header')?.getBoundingClientRect().bottom ?? 0);
|
||||
if (this.visibilityObserver && Math.abs(height - this.stickyHeight) < 1) return;
|
||||
this.stickyHeight = height;
|
||||
this.visibilityObserver?.disconnect();
|
||||
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.observedRegions.has(entry.target))) this.queueVisibility();
|
||||
}, { root: null, rootMargin: `-${height}px 0px 200px 0px`, threshold: 0 });
|
||||
this.visibilityObserver = observer;
|
||||
for (const region of this.observedRegions.keys()) observer.observe(region);
|
||||
}
|
||||
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
|
||||
// cannot activate a card that has since moved outside the current viewport.
|
||||
for (const card of this.renderedCards) {
|
||||
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);
|
||||
}
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
clearSearch() {
|
||||
this.changeSearchQuery('');
|
||||
this.searchInput()?.nativeElement.focus({ preventScroll: true });
|
||||
}
|
||||
changeSearchQuery(query: string) {
|
||||
this.preserveCardFocus();
|
||||
this.searchQuery.set(query);
|
||||
}
|
||||
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
|
||||
togglePinned(item: Indicador) {
|
||||
this.preserveCardFocus();
|
||||
this.memory.togglePinned(this.dominio, item.id);
|
||||
}
|
||||
private preserveCardFocus() {
|
||||
const focused = this.document.activeElement;
|
||||
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 periodService = inject(IndicadoresPeriodos);
|
||||
private readonly initialPeriod = inject(IndicadoresInitialPeriod);
|
||||
private readonly cancelInitialPeriod = new Subject<void>();
|
||||
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<void>();
|
||||
readonly availability = signal(emptyAvailability());
|
||||
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<Dominio, string> = { 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].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly searchQuery = signal('');
|
||||
readonly searchVisible = computed(() => this.catalog().length >= 5);
|
||||
readonly searchResults = computed(() => {
|
||||
const items = this.catalog();
|
||||
const query = this.normalizeSearch(this.searchQuery());
|
||||
const prioritize = (group: Indicador[]) => [
|
||||
...group.filter(item => this.isPinned(item)),
|
||||
...group.filter(item => !this.isPinned(item)),
|
||||
];
|
||||
if (!query) return { items: prioritize(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: [...prioritize(matches), ...prioritize(remaining)], 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';
|
||||
filters?: GlobalFilterState;
|
||||
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.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();
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
||||
constructor() {
|
||||
afterEveryRender(() => this.syncVisibility());
|
||||
const browser = this.document.defaultView;
|
||||
if (typeof IntersectionObserver !== 'undefined') {
|
||||
browser?.addEventListener('scroll', this.viewportChanged, { passive: true });
|
||||
browser?.addEventListener('resize', this.viewportChanged);
|
||||
}
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.filtersEdited();
|
||||
this.visibilityDestroyed = true;
|
||||
this.clearVisibility();
|
||||
this.sizeObserver?.disconnect();
|
||||
this.sizeTargets.clear();
|
||||
browser?.removeEventListener('scroll', this.viewportChanged);
|
||||
browser?.removeEventListener('resize', this.viewportChanged);
|
||||
});
|
||||
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.cancelInitialPeriod.next();
|
||||
this.initialPeriodState.set('ready');
|
||||
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 }) => {
|
||||
this.catalogLoading.set(false);
|
||||
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
|
||||
this.catalog.set(items);
|
||||
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;
|
||||
this.dominio = dominio;
|
||||
this.tema = this.memory.theme(dominio);
|
||||
this.catalogRequests.next();
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
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<typeof TestBed.createComponent<IndicadoresPage>>, 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 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 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-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', () => {
|
||||
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);
|
||||
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']]);
|
||||
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();
|
||||
});
|
||||
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(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.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');
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
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';
|
||||
|
||||
// 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,
|
||||
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 =>
|
||||
(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);
|
||||
} };
|
||||
},
|
||||
};
|
||||
|
||||
// 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 } };
|
||||
@@ -0,0 +1,79 @@
|
||||
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';
|
||||
import { IndicadoresRequests } from './indicadores-requests';
|
||||
|
||||
export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; }
|
||||
export interface PeriodAvailability {
|
||||
status: 'loading' | 'ready' | 'error';
|
||||
byIndicator: Record<string, AvailablePeriod[]>;
|
||||
options: Record<TipoPeriodo, string[]>;
|
||||
errors: Record<string, string>;
|
||||
}
|
||||
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<string, unknown> {
|
||||
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<string, AvailablePeriod>();
|
||||
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);
|
||||
private readonly requests = inject(IndicadoresRequests);
|
||||
// Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached.
|
||||
private readonly cache = new Map<string, Observable<AvailablePeriod[]>>();
|
||||
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.requests.run(() => this.http.get<unknown>(`/${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<PeriodAvailability> {
|
||||
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;
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
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';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
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[] = ['Edad', 'Evaluación inicial', 'Sexo', 'Seguimiento', 'Evaluación final'].map((titulo, i) => ({
|
||||
id: 'i' + i, titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'],
|
||||
}));
|
||||
|
||||
describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
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('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
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; 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)!; }
|
||||
function ids() { return cards().map(c => c.indicador.id); }
|
||||
function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; }
|
||||
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
|
||||
async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); }
|
||||
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); }
|
||||
|
||||
it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => {
|
||||
const control = button('i3');
|
||||
expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0);
|
||||
expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false');
|
||||
expect(control.getAttribute('aria-label')).toContain('Fijar indicador');
|
||||
for (const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
|
||||
expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador');
|
||||
await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => {
|
||||
const original = page.catalog(), snapshot = JSON.stringify(original);
|
||||
await pin('i4'); await pin('i2'); await pin('i0');
|
||||
expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']);
|
||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
||||
});
|
||||
it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => {
|
||||
await pin('i3'); await pin('i4');
|
||||
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']);
|
||||
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true);
|
||||
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']);
|
||||
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
|
||||
});
|
||||
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => {
|
||||
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle();
|
||||
expect(ids()[0]).toBe('i0');
|
||||
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
|
||||
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
|
||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
|
||||
});
|
||||
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => {
|
||||
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true);
|
||||
});
|
||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i4'); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
|
||||
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
|
||||
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
|
||||
});
|
||||
it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
|
||||
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
|
||||
await pin('i2'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i2')).toBe(true);
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
it('mover la tarjeta conserva foco en su botón existente', async () => {
|
||||
const control = button('i4'); control.focus(); await pin('i4');
|
||||
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, 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();
|
||||
|
||||
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').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);
|
||||
}
|
||||
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').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.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]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
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';
|
||||
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<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
||||
const disconnects: ReturnType<typeof vi.fn>[] = [];
|
||||
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 {
|
||||
disconnect = vi.fn(); unobserve = vi.fn();
|
||||
// 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, 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);
|
||||
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).setVisible(true);
|
||||
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 · j · g');
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
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();
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(1);
|
||||
});
|
||||
it('cambiar representación purga el host saliente y conserva el host del otro indicador', async () => {
|
||||
respond(); await settle();
|
||||
const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
const outgoing = charts[0].componentInstance.host.nativeElement;
|
||||
const other = charts[1].componentInstance.host.nativeElement;
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
card.selectFigure('g'); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(outgoing); expect(runtime.purge).not.toHaveBeenCalledWith(other);
|
||||
http.expectOne(r => r.url.endsWith('/i/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
||||
const current = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(current[0].componentInstance.host.nativeElement).not.toBe(outgoing);
|
||||
expect(current[1].componentInstance.host.nativeElement).toBe(other);
|
||||
expect(runtime.react.mock.calls.filter(c => c[0] === other)).toHaveLength(1);
|
||||
});
|
||||
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);
|
||||
});
|
||||
it('D.2 conserva hosts reales ocultando resultados anteriores durante carga e incompatibilidad', async () => {
|
||||
respond(); await settle();
|
||||
const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
const page = fixture.componentInstance;
|
||||
page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance)).toEqual(charts.map(c => c.componentInstance));
|
||||
for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy();
|
||||
expect(runtime.purge).not.toHaveBeenCalled();
|
||||
respond(); await settle();
|
||||
for (const host of hosts) expect(host.closest('[hidden]')).toBeNull();
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance.host.nativeElement)).toEqual(hosts);
|
||||
// Published capability change is evaluated by each existing consumer.
|
||||
const current = page.catalog()[0];
|
||||
page.catalog.set(page.catalog().map(item => ({ ...item, tipos_periodo: ['mes'] }))); fixture.detectChanges(); await settle();
|
||||
for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelectorAll('.incompatible')).toHaveLength(2);
|
||||
expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -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<T>(request: () => Observable<T>): Observable<T> {
|
||||
return new Observable<T>(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()!();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
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';
|
||||
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<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
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(), 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);
|
||||
});
|
||||
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).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'); }
|
||||
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.visible)).toBe(true);
|
||||
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.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('');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => {
|
||||
load(); await settle();
|
||||
const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'));
|
||||
const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement;
|
||||
const clear = field.querySelector('button')!;
|
||||
expect(clear.hasAttribute('matIconSuffix')).toBe(true);
|
||||
expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1);
|
||||
expect(input().type).toBe('search');
|
||||
for (const query of ['sexo', 'Indicador destacado', '']) {
|
||||
await search(query);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
|
||||
expect(cards()).toHaveLength(5);
|
||||
}
|
||||
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')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); 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));
|
||||
expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field);
|
||||
await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => {
|
||||
load(); await settle();
|
||||
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
|
||||
expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true);
|
||||
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda');
|
||||
const icon = clear.querySelector('mat-icon')!;
|
||||
expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(clear.textContent).not.toContain('Limpiar');
|
||||
expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px');
|
||||
await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0);
|
||||
// jsdom does not synthesize native keyboard activation. Verify that keys remain
|
||||
// available to the browser; Enter/Space activation is a Chrome acceptance check.
|
||||
for (const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
clear.focus(); clear.click(); fixture.detectChanges(); await settle();
|
||||
expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true);
|
||||
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.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();
|
||||
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);
|
||||
expect(new Set(titleIds).size).toBe(beforePanels.length);
|
||||
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, '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(5);
|
||||
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();
|
||||
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', '']) {
|
||||
if (query) await search(query);
|
||||
else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); }
|
||||
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.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', '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);
|
||||
expect(beforePanels.map(p => p.titleId)).toEqual(titleIds);
|
||||
for (const id of titleIds) {
|
||||
const heading = document.getElementById(id)!;
|
||||
expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id);
|
||||
}
|
||||
beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).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.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');
|
||||
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('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 = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf<HTMLElement>).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 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].visible).toBe(false);
|
||||
page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe('');
|
||||
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; 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));
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLButtonElement>('[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<HTMLElement>('#' + 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<HTMLElement>('#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<HTMLElement>('#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<HTMLButtonElement>('[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<HTMLButtonElement>('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();
|
||||
});
|
||||
});
|
||||
@@ -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<Indicador, 'id' | 'version'>, 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<string, Observable<IndicadorDatos>>();
|
||||
private readonly payloads = signal<ReadonlyMap<string, IndicadorDatos>>(new Map());
|
||||
readonly numeric = signal<ReadonlyMap<string, NumericSnapshot>>(new Map());
|
||||
readonly kpis = signal<ReadonlyMap<string, KpiSnapshot>>(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<Indicador, 'id' | 'version'>, 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<NumericSnapshot>({ 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<Indicador, 'id' | 'version'>, 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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<typeof TestBed.createComponent<IndicadorFigurePanel>>, 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('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<HTMLButtonElement>;
|
||||
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);
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -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<string,string>)[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();
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').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<string, { order: number; label: string; color?: string; parent?: string }>();
|
||||
const rows = new Map<string, Record<string, unknown>>();
|
||||
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}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), 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 };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<h2>Seguimiento · {{ domainLabel }}</h2>
|
||||
@if (dominio !== 'cacu') {
|
||||
<p>El seguimiento aún no está disponible.</p>
|
||||
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Paciente / identificación</th><th scope="col">Proceso o etapa</th><th scope="col">Estado</th><th scope="col">Fecha de referencia</th><th scope="col">Responsable</th><th scope="col">Acciones</th></tr></thead>
|
||||
<tbody><tr><td colspan="6">No hay registros de seguimiento disponibles.</td></tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else {
|
||||
<form (ngSubmit)="apply()">
|
||||
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||
</select></label>
|
||||
<label>Estatus de seguimiento <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||
</select></label>
|
||||
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@if (status === 'loading') { <p role="status">Cargando seguimiento…</p> }
|
||||
@if (status === 'pending') { <p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p> }
|
||||
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
|
||||
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
|
||||
@if (data; as response) {
|
||||
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th>Identificador seudónimo</th><th>Grupo de edad</th><th>Estatus de seguimiento</th><th>Última citología</th><th>Último resultado de VPH</th><th>Estudio más reciente</th><th>Días de toma a diagnóstico</th><th>Prioridad</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr>
|
||||
<td>{{ item.id_seudonimo }}</td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
} @empty { <tr><td colspan="8">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<nav aria-label="Paginación de seguimiento">
|
||||
<button type="button" [disabled]="response.paginacion.page <= 1" (click)="navigate(response.paginacion.page - 1)">Anterior</button>
|
||||
<span>Página {{ response.paginacion.page }} de {{ response.paginacion.total_pages }} · {{ response.paginacion.total_items }} registros</span>
|
||||
<button type="button" [disabled]="response.paginacion.page >= response.paginacion.total_pages" (click)="navigate(response.paginacion.page + 1)">Siguiente</button>
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
@@ -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<SeguimientoQuery | null>();
|
||||
private initialized = false;
|
||||
private previousDomain?: Dominio;
|
||||
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
||||
message = '';
|
||||
data?: SeguimientoResponse;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-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';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
|
||||
}));
|
||||
|
||||
// jsdom geometry and browser notifications are explicit, independent inputs.
|
||||
class IntersectionControl {
|
||||
static instances: IntersectionControl[] = [];
|
||||
readonly targets = new Set<Element>();
|
||||
observe = vi.fn((target: Element) => this.targets.add(target));
|
||||
unobserve = vi.fn((target: Element) => this.targets.delete(target));
|
||||
disconnect = vi.fn(() => this.targets.clear());
|
||||
constructor(readonly callback: IntersectionObserverCallback, readonly options: IntersectionObserverInit) {
|
||||
IntersectionControl.instances.push(this);
|
||||
}
|
||||
emit(target: Element, isIntersecting = true) {
|
||||
this.callback([{ target, isIntersecting, intersectionRatio: isIntersecting ? 1 : 0 } as IntersectionObserverEntry], this as unknown as IntersectionObserver);
|
||||
}
|
||||
}
|
||||
class ResizeControl {
|
||||
static instances: ResizeControl[] = [];
|
||||
readonly targets = new Set<Element>();
|
||||
observe = vi.fn((target: Element) => this.targets.add(target));
|
||||
unobserve = vi.fn((target: Element) => this.targets.delete(target));
|
||||
disconnect = vi.fn(() => this.targets.clear());
|
||||
constructor(readonly callback: ResizeObserverCallback) { ResizeControl.instances.push(this); }
|
||||
emit() { this.callback([], this as unknown as ResizeObserver); }
|
||||
}
|
||||
|
||||
describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
let memory: IndicadoresMemory;
|
||||
let sticky: HTMLElement;
|
||||
let geometry: WeakMap<Element, DOMRect>;
|
||||
let frames: Map<number, FrameRequestCallback>;
|
||||
let sequence: number;
|
||||
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
||||
function rect(top: number, left = 0, width = 600, height = 80): DOMRect {
|
||||
return { x: left, y: top, top, left, width, height, right: left + width, bottom: top + height, toJSON: () => ({}) } as DOMRect;
|
||||
}
|
||||
beforeEach(() => {
|
||||
IntersectionControl.instances = []; ResizeControl.instances = [];
|
||||
geometry = new WeakMap(); frames = new Map(); sequence = 0;
|
||||
vi.stubGlobal('IntersectionObserver', IntersectionControl); vi.stubGlobal('ResizeObserver', ResizeControl);
|
||||
vi.stubGlobal('innerWidth', 1440); vi.stubGlobal('innerHeight', 800);
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { frames.set(++sequence, callback); return sequence; });
|
||||
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => { frames.delete(id); });
|
||||
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function(this: Element) { return geometry.get(this) ?? rect(0, 0, 0, 0); });
|
||||
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, kpiQueriesProvider,
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
create();
|
||||
});
|
||||
function create() {
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController); memory = TestBed.inject(IndicadoresMemory);
|
||||
}
|
||||
afterEach(() => { fixture.destroy(); sticky.remove(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
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); }
|
||||
async function render() { fixture.detectChanges(); await fixture.whenStable(); }
|
||||
async function load(catalog = items, domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); await render();
|
||||
positions(cards().map((_, i) => [1000 + i * 200, 0]));
|
||||
}
|
||||
function positions(values: number[][]) {
|
||||
cards().forEach((card, i) => {
|
||||
geometry.set(card.host.nativeElement, rect(values[i][0], values[i][1]));
|
||||
geometry.set(card.visibilityRegion!.nativeElement, rect(values[i][0], values[i][1], 600, 620));
|
||||
});
|
||||
}
|
||||
function observer() { return IntersectionControl.instances.at(-1)!; }
|
||||
async function frame() {
|
||||
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].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.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(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('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('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');
|
||||
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.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();
|
||||
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, 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;
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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.<br>Base depurada del proyecto TEA · Centro Médico ISSSTELEÓN – UANL · Fecha de corte: 2025-08-01<br>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('<br>', '\n'), second.text.replaceAll('<br>', '\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.', '<b>Explicación sintética.</b>') },
|
||||
{ text: footer.text.replace('Explicación sintética.', '<script>') },
|
||||
{ text: footer.text.replace('Explicación sintética.', '<img src=x onerror=alert(1)>') },
|
||||
])('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('<br>', '<BR />');
|
||||
source.layout['annotations'] = [{ ...footer, text }];
|
||||
expect(figurePresentation(source, selection).footnotes).toEqual([footer.text.replaceAll('<br>', '\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('<br>', '\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: '<b>12</b>', 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('<br>', '\n')]);
|
||||
expect(figurePresentation(figure(), selected('tea', id)).footnotes).toEqual([]);
|
||||
});
|
||||
it.each(['Fuente: X.', 'Nota: ' + 'Texto extenso. '.repeat(100), 'Primera\n\nSegunda<BR />Tercera<br>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(/<br\s*\/?\s*>/gi, '\n')]);
|
||||
expect(result.figure.layout['annotations']).toEqual([]);
|
||||
});
|
||||
it.each([
|
||||
{ text: '<b>Nota</b>' }, { text: '<script>alert(1)</script>' }, { text: '<img>' },
|
||||
{ text: '<a href="https://example.invalid">Fuente</a>' }, { 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<br>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);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user