feat(indicadores): interacción dona-barras, homologación visual y escenario clínico EU7 #5
@@ -4,6 +4,17 @@
|
||||
<img class="institutional-logo" src="images/LogoISSSTELEON.png" alt="ISSSTELEON"
|
||||
width="1125" height="358" />
|
||||
<span class="platform-title">{{ title }}</span>
|
||||
@if (activeDomain(); as domain) {
|
||||
<button class="domain-selector" mat-button [matMenuTriggerFor]="domainMenu"
|
||||
[attr.aria-label]="'Dominio actual: ' + domainLabels[domain] + '. Cambiar dominio'">
|
||||
{{ domainLabels[domain] }} <span aria-hidden="true">▾</span>
|
||||
</button>
|
||||
<mat-menu #domainMenu="matMenu" aria-label="Cambiar dominio de indicadores">
|
||||
@for (option of otherDomains(); track option) {
|
||||
<a mat-menu-item [routerLink]="['/indicadores', option]">{{ domainLabels[option] }}</a>
|
||||
}
|
||||
</mat-menu>
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ for (const dominio of ['tea', 'cacu', 'cama']) {
|
||||
expect(page.dominio).toBe(dominio);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne(`/${dominio}/indicadores`).flush([]);
|
||||
expect(harness.routeNativeElement?.querySelectorAll('nav a').length).toBe(3);
|
||||
expect(harness.routeNativeElement?.querySelector('nav')).toBeNull();
|
||||
http.verify();
|
||||
});
|
||||
}
|
||||
|
||||
+18
-2
@@ -38,6 +38,18 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.domain-selector {
|
||||
flex: 0 0 auto;
|
||||
margin-inline-start: auto;
|
||||
background-color: var(--issste-accent);
|
||||
color: var(--issste-text);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
|
||||
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.domain-selector:disabled { background-color: var(--issste-accent); color: var(--issste-text-secondary); }
|
||||
|
||||
main {
|
||||
padding: var(--issste-space-4) var(--issste-page-gutter) 5.5rem;
|
||||
scroll-margin-top: var(--issste-header-clearance);
|
||||
@@ -71,6 +83,8 @@ main {
|
||||
|
||||
.platform-title {
|
||||
font-size: 1.125rem;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,9 +97,11 @@ main {
|
||||
}
|
||||
|
||||
.platform-title {
|
||||
flex-basis: 100%;
|
||||
text-align: center;
|
||||
font-size: 1rem;
|
||||
}
|
||||
.header-content { gap: .25rem; }
|
||||
.institutional-logo { width: 112px; }
|
||||
.domain-selector { padding-inline: .5rem; }
|
||||
}
|
||||
|
||||
.back-to-top {
|
||||
|
||||
+30
-1
@@ -3,12 +3,14 @@ import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { App } from './app';
|
||||
import { routes } from './app.routes';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
describe('App — UX-06B', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [App],
|
||||
providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()],
|
||||
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
@@ -53,6 +55,33 @@ describe('App — UX-06B', () => {
|
||||
TestBed.inject(HttpTestingController).expectNone(() => true);
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['tea', 'TEA', 'CaCu', 'CaMa'],
|
||||
['cacu', 'CaCu', 'TEA', 'CaMa'],
|
||||
['cama', 'CaMa', 'TEA', 'CaCu'],
|
||||
] as const)('announces %s as the active domain and offers the other domains in the shell', async (domain, active, ...others) => {
|
||||
const fixture = render();
|
||||
await TestBed.inject(Router).navigateByUrl(`/indicadores/${domain}`);
|
||||
fixture.detectChanges();
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const catalog = http.expectOne({ method: 'GET', url: `/${domain}/indicadores` });
|
||||
catalog.flush([]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const element = fixture.nativeElement as HTMLElement;
|
||||
const selector = element.querySelector<HTMLButtonElement>('.domain-selector')!;
|
||||
expect(selector.textContent).toContain(active);
|
||||
expect(selector.getAttribute('aria-label')).toBe(`Dominio actual: ${active}. Cambiar dominio`);
|
||||
selector.click();
|
||||
fixture.detectChanges();
|
||||
const menuItems = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]'));
|
||||
expect(menuItems.map(item => item.textContent?.trim())).toEqual(others);
|
||||
expect(element.querySelector('nav')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
describe('App — UX-06D volver al inicio', () => {
|
||||
|
||||
+18
-3
@@ -1,15 +1,29 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { Component, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
import { Component, computed, ElementRef, inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core';
|
||||
import { NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatMenuModule } from '@angular/material/menu';
|
||||
import { filter } from 'rxjs';
|
||||
|
||||
@Component({
|
||||
imports: [RouterOutlet],
|
||||
imports: [RouterOutlet, RouterLink, MatButtonModule, MatMenuModule],
|
||||
selector: 'app-root',
|
||||
styleUrl: './app.scss',
|
||||
templateUrl: './app.html',
|
||||
})
|
||||
export class App implements OnInit, OnDestroy {
|
||||
protected readonly title = 'Plataforma de Indicadores';
|
||||
private readonly router = inject(Router);
|
||||
private readonly currentUrl = signal(this.router.url);
|
||||
protected readonly activeDomain = computed(() => {
|
||||
const match = /^\/indicadores\/(tea|cacu|cama)(?:\/|$)/.exec(this.currentUrl());
|
||||
return match?.[1] as 'tea' | 'cacu' | 'cama' | undefined;
|
||||
});
|
||||
protected readonly domainLabels = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' } as const;
|
||||
protected readonly otherDomains = computed(() => (['tea', 'cacu', 'cama'] as const)
|
||||
.filter(domain => domain !== this.activeDomain()));
|
||||
private readonly routeSubscription = this.router.events.pipe(filter(event => event instanceof NavigationEnd))
|
||||
.subscribe(event => this.currentUrl.set(event.urlAfterRedirects));
|
||||
readonly showBackToTop = signal(false);
|
||||
@ViewChild('mainContent') private mainContent?: ElementRef<HTMLElement>;
|
||||
private readonly browserWindow = inject(DOCUMENT).defaultView;
|
||||
@@ -28,6 +42,7 @@ export class App implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.routeSubscription.unsubscribe();
|
||||
this.browserWindow?.removeEventListener('scroll', this.updateScroll);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,936 @@
|
||||
{
|
||||
"_nota": "Datos SIMULADOS con la forma exacta de GET /cacu/indicadores/cacu_eu7/datos (contrato C2, kit 054837b). Sin 'reportes' (procedencia). Las tres respuestas son del mismo semestre y suman lo mismo.",
|
||||
"general": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": null,
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "NORMAL",
|
||||
"n": 798,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "ASC-US",
|
||||
"n": 62,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "LIEBG",
|
||||
"n": 46,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "ASC-H",
|
||||
"n": 17,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "LIEAG",
|
||||
"n": 19,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "CIS",
|
||||
"n": 4,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": null,
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 87,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": []
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "estatus_seguimiento",
|
||||
"valores_estrato": [
|
||||
"VIGILANCIA",
|
||||
"POST_COLPOSCOPIA",
|
||||
"POST_TRATAMIENTO",
|
||||
"INFO_INSUFICIENTE"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"VIGILANCIA": "Vigilancia",
|
||||
"POST_COLPOSCOPIA": "Post colposcopia",
|
||||
"POST_TRATAMIENTO": "Post tratamiento",
|
||||
"INFO_INSUFICIENTE": "Información insuficiente"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 610,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 38,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 22,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 6,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 5,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 48,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "NORMAL",
|
||||
"n": 92,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-US",
|
||||
"n": 14,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEBG",
|
||||
"n": 16,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "ASC-H",
|
||||
"n": 7,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "LIEAG",
|
||||
"n": 9,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "CIS",
|
||||
"n": 2,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 11,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "NORMAL",
|
||||
"n": 41,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-US",
|
||||
"n": 6,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEBG",
|
||||
"n": 5,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "ASC-H",
|
||||
"n": 3,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "LIEAG",
|
||||
"n": 4,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 7,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "NORMAL",
|
||||
"n": 55,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-US",
|
||||
"n": 4,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEBG",
|
||||
"n": 3,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "ASC-H",
|
||||
"n": 1,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "LIEAG",
|
||||
"n": 1,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "CIS",
|
||||
"n": 0,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 21,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "VIGILANCIA",
|
||||
"n": 730,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_COLPOSCOPIA",
|
||||
"n": 151,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "POST_TRATAMIENTO",
|
||||
"n": 67,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "INFO_INSUFICIENTE",
|
||||
"n": 85,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "grupo_edad",
|
||||
"valores_estrato": [
|
||||
"<25",
|
||||
"25-34",
|
||||
"35-44",
|
||||
"45-54",
|
||||
"55-64"
|
||||
],
|
||||
"etiquetas_estrato": {
|
||||
"<25": "<25",
|
||||
"25-34": "25-34",
|
||||
"35-44": "35-44",
|
||||
"45-54": "45-54",
|
||||
"55-64": "55-64"
|
||||
},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {
|
||||
"NORMAL": {
|
||||
"etiqueta": "Normal",
|
||||
"color": "#9DBFE3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 1
|
||||
},
|
||||
"ASC-US": {
|
||||
"etiqueta": "ASC-US",
|
||||
"color": "#2F6DB3",
|
||||
"grupo": "NO_ANORMAL",
|
||||
"gravedad": 2
|
||||
},
|
||||
"LIEBG": {
|
||||
"etiqueta": "LIEBG",
|
||||
"color": "#E8C28E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 3
|
||||
},
|
||||
"ASC-H": {
|
||||
"etiqueta": "ASC-H",
|
||||
"color": "#D98E4A",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 4
|
||||
},
|
||||
"LIEAG": {
|
||||
"etiqueta": "LIEAG",
|
||||
"color": "#B55A1F",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 5
|
||||
},
|
||||
"CIS": {
|
||||
"etiqueta": "Carcinoma in situ",
|
||||
"color": "#7A2E0E",
|
||||
"grupo": "ANORMAL",
|
||||
"gravedad": 6
|
||||
},
|
||||
"SIN_DATO": {
|
||||
"etiqueta": "Sin dato",
|
||||
"color": "#C9CDD2",
|
||||
"grupo": "SIN_DATO",
|
||||
"gravedad": null
|
||||
}
|
||||
},
|
||||
"grupos_de_categoria": {
|
||||
"NO_ANORMAL": "Sin anomalía",
|
||||
"ANORMAL": "Anormal",
|
||||
"SIN_DATO": "Sin dato"
|
||||
},
|
||||
"notas": [
|
||||
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
|
||||
],
|
||||
"filas": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "NORMAL",
|
||||
"n": 40,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-US",
|
||||
"n": 5,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEBG",
|
||||
"n": 4,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "ASC-H",
|
||||
"n": 0,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "LIEAG",
|
||||
"n": 0,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "CIS",
|
||||
"n": 0,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 6,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "NORMAL",
|
||||
"n": 190,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-US",
|
||||
"n": 18,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEBG",
|
||||
"n": 17,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "ASC-H",
|
||||
"n": 4,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "LIEAG",
|
||||
"n": 4,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "CIS",
|
||||
"n": 0,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 22,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "NORMAL",
|
||||
"n": 230,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-US",
|
||||
"n": 20,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEBG",
|
||||
"n": 14,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "ASC-H",
|
||||
"n": 6,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "LIEAG",
|
||||
"n": 7,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "CIS",
|
||||
"n": 2,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 25,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "NORMAL",
|
||||
"n": 205,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-US",
|
||||
"n": 12,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEBG",
|
||||
"n": 7,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "ASC-H",
|
||||
"n": 4,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "LIEAG",
|
||||
"n": 5,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 20,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "NORMAL",
|
||||
"n": 133,
|
||||
"orden": 0,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-US",
|
||||
"n": 7,
|
||||
"orden": 1,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEBG",
|
||||
"n": 4,
|
||||
"orden": 2,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "ASC-H",
|
||||
"n": 3,
|
||||
"orden": 3,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "LIEAG",
|
||||
"n": 3,
|
||||
"orden": 4,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "CIS",
|
||||
"n": 1,
|
||||
"orden": 5,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"categoria": "SIN_DATO",
|
||||
"n": 14,
|
||||
"orden": 6,
|
||||
"suprimido": 0
|
||||
}
|
||||
],
|
||||
"totales_estrato": [
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "<25",
|
||||
"n": 55,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "25-34",
|
||||
"n": 255,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "35-44",
|
||||
"n": 304,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "45-54",
|
||||
"n": 254,
|
||||
"suprimido": 0
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"grupo": "TOTAL",
|
||||
"estrato": "55-64",
|
||||
"n": 165,
|
||||
"suprimido": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -79,14 +79,14 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2',
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
||||
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] });
|
||||
fixture.detectChanges();
|
||||
const helps = fixture.nativeElement.querySelectorAll('.methodology-toggle') as NodeListOf<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');
|
||||
const metadata = http.expectOne('/cacu/indicadores/cacu_eu13/metadatos');
|
||||
http.expectNone('/cacu/indicadores/cacu_eu13/metadatos');
|
||||
metadata.flush({ figuras_detalle: [
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Instrucción para donas.'] },
|
||||
{ figura: 'fig_c2_barras', descripcion: null, como_leer: ['Instrucción para barras.'] },
|
||||
|
||||
@@ -16,11 +16,12 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
@@ -33,9 +34,13 @@ import { IndicadoresService } from './indicadores.service';
|
||||
(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">
|
||||
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
<p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p>
|
||||
@if (selectedFigure) {
|
||||
@if (isEu7) {
|
||||
<div #visibilityRegion class="eu7-region">
|
||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!pair.length || otherFigures.length) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
@@ -59,16 +64,31 @@ import { IndicadoresService } from './indicadores.service';
|
||||
</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);
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||
.graphic-region { min-height: 620px; }
|
||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.graphic-region { flex: 1; min-width: 0; }
|
||||
:host(.dual-card) { grid-column: 1 / -1; }
|
||||
.dual-panels { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--issste-space-4); }
|
||||
.representation-panel { min-width: 0; }
|
||||
.representation-panel > h3 { margin-bottom: 0; }
|
||||
@media (max-width: 900px) { .dual-panels { grid-template-columns: minmax(0, 1fr); } }
|
||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||
app-indicador-figure-panel { grid-row: 2; }
|
||||
// Nine shared tracks: name, controls, help, title, legend, plot, notes,
|
||||
// full labels and stratified detail. Content determines their height.
|
||||
@supports (grid-template-rows: subgrid) {
|
||||
.graphic-region { grid-auto-rows: auto; grid-template-rows: auto auto auto auto auto minmax(0, 1fr) auto auto auto; }
|
||||
.representation-panel { grid-row: span 9; grid-template-rows: subgrid; }
|
||||
app-indicador-figure-panel { grid-row: 2 / span 8; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: none; align-items: start; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) .representation-panel { grid-row: auto; grid-template-rows: auto auto; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) app-indicador-figure-panel { grid-row: auto; grid-template-rows: auto auto auto; }
|
||||
.graphic-region:has(app-indicador-figure-card.methodology-expanded) app-indicador-figure-card { grid-row: auto; grid-template-rows: auto auto auto auto auto auto; }
|
||||
}
|
||||
@media (min-width: 901px) {
|
||||
.dual-panels { grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: var(--issste-space-4); }
|
||||
}
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
|
||||
@@ -100,6 +120,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
});
|
||||
}
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<p>El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.</p>
|
||||
<p>Las barras usan el total con resultado válido de cada escenario, excluyendo «Sin dato». Al seleccionar un grupo o categoría se conserva ese denominador.</p>
|
||||
<p>El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.</p>
|
||||
<p>Selecciona un grupo para expandirlo y una categoría para resaltarla. Repite el clic para liberar la selección. El centro o el botón Volver regresa de categoría a grupo y después a TOTAL. También puedes usar Tab y Enter o Espacio en la leyenda.</p>
|
||||
<p>Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.</p>
|
||||
@if (metadata; as info) {
|
||||
@if (info.descripcion) { <p>{{ info.descripcion }}</p> }
|
||||
@if (info.ficha; as ficha) {
|
||||
@if (ficha.pregunta) { <p>{{ ficha.pregunta }}</p> }
|
||||
@if (ficha.definicion) { <p>{{ ficha.definicion }}</p> }
|
||||
@if (ficha.unidad) { <p>Unidad: {{ ficha.unidad }}</p> }
|
||||
@if (ficha.nota) { <p>{{ ficha.nota }}</p> }
|
||||
}
|
||||
<details><summary>Metadatos publicados de las figuras originales</summary>
|
||||
<p>Estas descripciones corresponden a las figuras publicadas originales. En esta vista coordinada, «Sin dato» queda fuera de la dona y las barras son porcentajes por escenario.</p>
|
||||
@for (detail of info.figuras_detalle; track detail.figura) {
|
||||
@if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') {
|
||||
<p>{{ detail.descripcion }}</p>
|
||||
@for (line of detail.como_leer; track $index) { <p>{{ line }}</p> }
|
||||
}
|
||||
}
|
||||
@for (reference of info.referencias; track $index) { <p>{{ reference.etiqueta }} {{ reference.ref }}</p> }
|
||||
</details>
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de dona y barras EU7">
|
||||
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }} · {{ periodIndex + 1 }} / {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }} · Selección: {{ selectionLabel }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados · {{ m.periodo }}</h3>
|
||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'EU7 · Dona de dos anillos · ' + m.periodo + ' · ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado válido para la dona.' }}</p> }
|
||||
<p>{{ sinDatoNote }}</p>
|
||||
</section>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico · {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
||||
@if (m.escenarios.length && barsFigure) {
|
||||
<app-plotly-chart [figure]="barsFigure" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7 · Barras por escenario clínico · ' + m.periodo + ' · ' + selectionLabel" />
|
||||
}
|
||||
@for (s of m.escenarios; track s.id) { <p>{{ s.etiqueta }}: {{ scenarioText(s) }}.</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados y celdas suprimidas</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
|
||||
<table><caption>Datos generales · {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
|
||||
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
<table><caption>Escenarios clínicos · {{ m.periodo }} · Porcentajes sin «Sin dato»</caption>
|
||||
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
|
||||
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,29 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
.periods span { text-align: center; }
|
||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
|
||||
@@ -0,0 +1,150 @@
|
||||
import { Component, input, output } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import fixtureData from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub {
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>();
|
||||
plotClick = output<unknown>();
|
||||
}
|
||||
describe('EU7 integración Angular y caché compartida', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'],
|
||||
filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorEu7Escenario>>;
|
||||
let http: HttpTestingController;
|
||||
let data: typeof fixtureData;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData);
|
||||
f = TestBed.createComponent(IndicadorEu7Escenario);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); vi.useRealTimers(); });
|
||||
function requests() {
|
||||
const general = http.expectOne(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
|
||||
const escenarios = http.expectOne(r => r.url.endsWith('/datos') && r.params.get('estrato') === 'estatus_seguimiento');
|
||||
expect(general.request.params.get('periodos')).toBe(escenarios.request.params.get('periodos'));
|
||||
return { general, escenarios };
|
||||
}
|
||||
function flush() { const r = requests(); r.general.flush(data.general); r.escenarios.flush(data.estatus_seguimiento); f.detectChanges(); }
|
||||
it('carga diferida; dos GET compartidos con el KPI y ningún GET por clic, tema o navegación de selección', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.model!.total).toBe(946);
|
||||
const general = data.general; const original = structuredClone(applied);
|
||||
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
|
||||
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
|
||||
const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub;
|
||||
chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection.categoria).toBe('LIEAG');
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG');
|
||||
f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({});
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
|
||||
});
|
||||
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
|
||||
const periods: [string, string] = ['2025-S1', '2025-S2'];
|
||||
for (const d of [data.general, data.estatus_seguimiento]) {
|
||||
d.periodos = periods; d.filas = [...d.filas.map(r => ({ ...r, periodo: '2025-S1', n: r.n * 2 })), ...d.filas] as typeof d.filas;
|
||||
d.totales_estrato = [...d.totales_estrato.map(t => ({ ...t, periodo: '2025-S1', n: t.n * 2 })), ...d.totales_estrato];
|
||||
}
|
||||
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
|
||||
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
|
||||
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
||||
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
||||
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
|
||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
||||
});
|
||||
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.flush(data.general);
|
||||
r.escenarios.flush({}, { status: 500, statusText: 'Internal Server Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); http.expectNone(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
|
||||
http.expectOne(r => r.params.get('estrato') === 'estatus_seguimiento').flush(data.estatus_seguimiento); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('timeout cancela transportes y permite recuperación', async () => {
|
||||
vi.useFakeTimers(); f.detectChanges(); const r = requests();
|
||||
await vi.advanceTimersByTimeAsync(40001); f.detectChanges();
|
||||
expect(r.general.cancelled && r.escenarios.cancelled).toBe(true);
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.textContent).toContain('tardó demasiado');
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('error de red permite reintento sin figuras engañosas', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
|
||||
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.componentInstance.donutFigure).toBeUndefined();
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
|
||||
f.detectChanges(); const old = requests();
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S1'] } });
|
||||
f.detectChanges(); expect(old.general.cancelled && old.escenarios.cancelled).toBe(true);
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = ['2025-S1']; d.filas.forEach(r => r.periodo = '2025-S1'); d.totales_estrato.forEach(t => t.periodo = '2025-S1'); }
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); flush(); expect(f.componentInstance.model!.periodo).toBe('2025-S1');
|
||||
});
|
||||
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
|
||||
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
|
||||
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
|
||||
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
|
||||
});
|
||||
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
|
||||
Object.assign(data.general.filas[0], { n: 987654, suprimido: 1 });
|
||||
Object.assign(data.estatus_seguimiento.filas[0], { n: 987654, suprimido: 1 });
|
||||
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
|
||||
expect(f.nativeElement.textContent).not.toContain('987654');
|
||||
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
|
||||
});
|
||||
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
|
||||
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
|
||||
const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure;
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
|
||||
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
|
||||
});
|
||||
it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(1);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['tea', 'M23_pacientes_evaluados'], ['cama', 'cama_birads_456_paciente'], ['tea', 'cacu_eu7']]) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(0);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(2);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-eu7-escenario.html',
|
||||
styleUrl: './indicador-eu7-escenario.scss',
|
||||
})
|
||||
export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection: Seleccion = {};
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: Modelo;
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: Modelo[] = [];
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
|
||||
get sinDatoNote() {
|
||||
const m = this.model;
|
||||
if (!m) return '';
|
||||
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
||||
const n = m.sinDato.n;
|
||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: m.total === null ? `Fuera de la dona: ${n} pacientes sin resultado válido. Total con resultado no disponible.`
|
||||
: `Fuera de la dona: ${n} de ${m.total + n} pacientes sin resultado válido en el periodo.`;
|
||||
}
|
||||
get generalCells() {
|
||||
const m = this.model;
|
||||
return !m || m.vacio ? [] : [...m.categorias.map(c => ({ etiqueta: c.etiqueta, celda: m.celdas[c.id] })),
|
||||
{ etiqueta: m.sinDatoEtiqueta, celda: m.sinDato }];
|
||||
}
|
||||
get scenarioCells() {
|
||||
const m = this.model;
|
||||
return !m ? [] : m.escenarios.flatMap(s => [...m.categorias.map(c => ({ escenario: s.etiqueta, categoria: c.etiqueta,
|
||||
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })),
|
||||
{ escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]);
|
||||
}
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
percentText(value: number | null) { return value === null ? 'No disponible' : value.toFixed(1) + ' %'; }
|
||||
scenarioText(s: Escenario) { return s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' : `${s.den} pacientes con resultado`; }
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
|
||||
this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras, this.indicador.filtros]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.pages = []; this.periods = []; this.model = undefined;
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
// Visibility and metadata changes must not restart Plotly rendering.
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([general, escenarios]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modelo(general, escenarios, p));
|
||||
this.periodIndex = 0; this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof Eu7Incompatible ? error.message
|
||||
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
|
||||
&& this.applied.selection.periodos.length > 1 ? ' La respuesta corresponde al conjunto de periodos solicitado.' : '');
|
||||
this.status.set(error instanceof Eu7Incompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex]; this.selection = {};
|
||||
this.draw(); this.status.set(this.model ? this.model.vacio ? 'empty' : 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || this.status() !== 'ready') return;
|
||||
this.selection = clic(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
@@ -15,7 +16,7 @@
|
||||
</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'">
|
||||
<div class="figure-heading">
|
||||
@if (state.status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<div class="figure-skeleton"><p class="state" role="status">Cargando figura…</p><div class="skeleton" aria-hidden="true"></div></div>
|
||||
@@ -35,8 +36,9 @@
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
</div>
|
||||
@if (chartFigure) {
|
||||
<div [hidden]="state.status !== 'ready'">
|
||||
<div class="figure-legend">
|
||||
@if (state.status === 'ready' && state.hierarchy; as hierarchy) {
|
||||
<div #donutNavigation class="donut-navigation" tabindex="-1" aria-label="Explorar grupos de la dona">
|
||||
<p class="donut-status" role="status">{{ activeParent ? 'Categorías de ' + activeParent + '. Anillo exterior: porcentajes dentro de este grupo. Anillo interior: todos los grupos.' : 'Selecciona un segmento para ver sus categorías. También puedes explorar los grupos con Tab y Enter o Espacio.' }}</p>
|
||||
@@ -84,12 +86,19 @@
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
@if (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>
|
||||
}
|
||||
</div>
|
||||
<div class="figure-labels" [hidden]="state.status !== 'ready'">
|
||||
@if (state.categoryLabels?.length) {
|
||||
<details class="category-labels">
|
||||
<summary>Nombres completos de las categorías</summary>
|
||||
@@ -100,6 +109,5 @@
|
||||
</ul>
|
||||
</details>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</mat-card>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
:host { display: grid; min-width: 0; }
|
||||
.interpretation {
|
||||
margin-bottom: var(--issste-space-4);
|
||||
margin: 0;
|
||||
padding: 0 1rem .75rem;
|
||||
color: var(--issste-text);
|
||||
font-family: var(--issste-font-body);
|
||||
line-height: 1.5;
|
||||
@@ -14,12 +15,26 @@
|
||||
.interpretation ul { margin: 0; padding-left: 1.25rem; }
|
||||
.interpretation li + li { margin-top: .25rem; }
|
||||
.period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); }
|
||||
.methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal;
|
||||
.methodology-toggle { margin-top: .75rem; min-height: 44px; max-width: 100%; height: auto; white-space: normal;
|
||||
--mat-button-outlined-label-text-color: var(--issste-text); --mat-button-outlined-outline-color: var(--issste-border); }
|
||||
.methodology-detail p { margin: 0; }
|
||||
.methodology-detail p + p { margin-top: var(--issste-space-2); }
|
||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figure-card { overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||
.interpretation { grid-row: 1; }
|
||||
.figure-legend { grid-row: 3; min-width: 0; }
|
||||
.plot-slot { grid-row: 4; min-width: 0; align-content: start; }
|
||||
.plot-slot[hidden] { display: none; }
|
||||
.figure-footer { grid-row: 5; min-width: 0; align-content: end; }
|
||||
.figure-labels { grid-row: 6; min-width: 0; }
|
||||
@supports (grid-template-rows: subgrid) {
|
||||
:host, .figure-card { grid-template-rows: subgrid; }
|
||||
.figure-card { grid-row: span 6; }
|
||||
}
|
||||
:host(.methodology-expanded), :host(.methodology-expanded) .figure-card { grid-template-rows: auto auto auto auto auto auto; }
|
||||
:host(.methodology-expanded) .figure-card { grid-row: auto; }
|
||||
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
|
||||
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
||||
@@ -49,7 +64,7 @@
|
||||
.category-labels ul { margin: .25rem 0 0; padding-left: 1.25rem; }
|
||||
.category-labels li + li { margin-top: .5rem; }
|
||||
|
||||
.figure-skeleton { min-height: 620px; display: flex; flex-direction: column; }
|
||||
.figure-skeleton { min-height: 12rem; display: flex; flex-direction: column; }
|
||||
.skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; }
|
||||
.donut-navigation {
|
||||
position: relative;
|
||||
|
||||
@@ -48,6 +48,30 @@ describe('IndicadorFigureCard', () => {
|
||||
state({ status: 'ready', figure: original, presentationFigure: copy });
|
||||
return copy;
|
||||
}
|
||||
it.each(['bar', 'box', 'scatter'])('%s conserva el dimensionamiento intrínseco de Plotly', async type => {
|
||||
const automatic: PlotlyFigure = { data: [{ type, x: ['A'], y: [2] }], layout: { autosize: true } };
|
||||
ready(automatic); await settle();
|
||||
const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
||||
expect(chart.style.getPropertyValue('--plot-height')).toBe('');
|
||||
expect(automatic.layout['height']).toBeUndefined();
|
||||
const tall = { ...automatic, layout: { ...automatic.layout, height: 830 } };
|
||||
ready(tall); await settle();
|
||||
expect(chart.style.getPropertyValue('--plot-height')).toBe('');
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart);
|
||||
expect(tall.layout.height).toBe(830);
|
||||
});
|
||||
it('la leyenda de exploración precede al lienzo y conserva su host y altura al expandir', async () => {
|
||||
const { figure, data } = donutFixture();
|
||||
state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data)! }); await settle();
|
||||
const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
||||
const slot = plot.closest('.plot-slot')!;
|
||||
const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement;
|
||||
expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
fixture.componentInstance.expandParent('G2'); await settle();
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot);
|
||||
expect(plot.style.getPropertyValue('--plot-height')).toBe('440px');
|
||||
expect(fixture.nativeElement.querySelector('.figure-card .interpretation')).toBeTruthy();
|
||||
});
|
||||
it('C2 expande por Plotly y teclado, vuelve con foco y conserva host; reinicia al cambiar resultado', async () => {
|
||||
const { figure, data } = donutFixture();
|
||||
const hierarchy = donutHierarchy(figure, data)!;
|
||||
@@ -105,6 +129,13 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']);
|
||||
expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']);
|
||||
const heading = fixture.nativeElement.querySelector('.figure-heading') as HTMLElement;
|
||||
const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement;
|
||||
const slot = fixture.nativeElement.querySelector('.plot-slot') as HTMLElement;
|
||||
const notes = fixture.nativeElement.querySelector('.figure-footer') as HTMLElement;
|
||||
expect(heading.compareDocumentPosition(legendElement) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(slot.compareDocumentPosition(notes) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => {
|
||||
const { figure, data } = donutFixture();
|
||||
@@ -124,9 +155,9 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura');
|
||||
expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
|
||||
expect(section.querySelector('img, script, a')).toBeNull();
|
||||
expect(section.previousElementSibling?.tagName).toBe('APP-PLOTLY-CHART');
|
||||
expect(section.parentElement?.previousElementSibling?.querySelector('app-plotly-chart')).toBeTruthy();
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull();
|
||||
expect(section.nextElementSibling?.classList.contains('category-labels')).toBe(true);
|
||||
expect(section.parentElement?.parentElement?.querySelector('.figure-labels .category-labels')).toBeTruthy();
|
||||
for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
|
||||
state({ status });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
@@ -277,6 +308,7 @@ describe('IndicadorFigureCard', () => {
|
||||
const button = section.querySelector('button')!;
|
||||
const detail = section.querySelector('[id]') as HTMLElement;
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false);
|
||||
expect(button.getAttribute('aria-controls')).toBe(detail.id);
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(button.tagName).toBe('BUTTON');
|
||||
@@ -289,10 +321,12 @@ describe('IndicadorFigureCard', () => {
|
||||
expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation);
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(true);
|
||||
state({ status: 'loading' });
|
||||
expect(detail.hidden).toBe(false);
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(detail.hidden).toBe(true);
|
||||
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false);
|
||||
expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail);
|
||||
});
|
||||
it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => {
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface FigureState {
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
|
||||
@@ -15,14 +15,24 @@ import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorFigureCard],
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
|
||||
<header class="panel-controls">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
||||
<span class="selection-status" [class.selection-active]="!!generalSelectionContext" tabindex="0" role="status"
|
||||
[attr.aria-label]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'"
|
||||
[matTooltip]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'">
|
||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||
</span>
|
||||
}
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
@@ -50,8 +60,10 @@ import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
@@ -62,12 +74,29 @@ import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
}
|
||||
</div>
|
||||
</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; }
|
||||
:host { display: grid; min-width: 0; }
|
||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||
.selection-active { color: var(--issste-text); font-weight: 600; }
|
||||
.selection-status:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.stratified-detail { min-width: 0; overflow-wrap: anywhere; }
|
||||
@supports (grid-template-rows: subgrid) {
|
||||
:host, .figure-panel { grid-template-rows: subgrid; }
|
||||
.figure-panel { grid-row: span 8; }
|
||||
.panel-controls { grid-row: 1; }
|
||||
app-indicador-figure-card { grid-row: 2 / span 6; }
|
||||
.stratified-detail { grid-row: 8; }
|
||||
}
|
||||
:host:has(app-indicador-figure-card.methodology-expanded),
|
||||
.figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-template-rows: auto auto auto; }
|
||||
.figure-panel:has(app-indicador-figure-card.methodology-expanded) { grid-row: auto; }
|
||||
.distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; }
|
||||
.distribution-control legend { padding: 0; font-weight: 600; }
|
||||
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
||||
@@ -136,6 +165,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||
private stratifiedData?: IndicadorDatos;
|
||||
private generalData?: IndicadorDatos;
|
||||
private generalState?: FigureState;
|
||||
generalSelectionContext?: string;
|
||||
get capabilities() { return stratifiedCapabilities(this.indicador); }
|
||||
get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; }
|
||||
changeDimension(value: DimensionEstrato | '') {
|
||||
@@ -155,6 +187,16 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
source: 'datos', footnotes: data.notas,
|
||||
emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' };
|
||||
}
|
||||
private presentGeneral(state: FigureState, selection: FigureSelection): FigureState {
|
||||
const selected = this.generalData && state.figure
|
||||
? c2GeneralSelection(state.figure, this.generalData, selection, this.localSelection) : undefined;
|
||||
this.generalSelectionContext = selected?.context;
|
||||
const presentation = this.present(selected?.figure ?? state.figure!, selection);
|
||||
// Keep the complete original figure in state. Width/profile changes and
|
||||
// restoration always derive afresh, including published percentage arrays.
|
||||
return { ...state, ...presentation, figure: state.figure,
|
||||
footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
}
|
||||
private readySelection?: FigureSelection;
|
||||
private plotWidth?: number;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
@@ -183,6 +225,11 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
if (generation === this.generation && revision === this.applied?.revision) {
|
||||
if (state.status === 'ready') {
|
||||
this.readySelection = selection;
|
||||
if (!this.dimension && this.indicador.contrato === 'C2'
|
||||
&& selection?.figura === 'fig_c2_barras' && this.indicador.figuras.includes('fig_c2_donas')) {
|
||||
this.generalState = state;
|
||||
state = this.presentGeneral(state, selection);
|
||||
}
|
||||
if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1
|
||||
? selection.periodos[0] : state.figure && donutPeriod(state.figure);
|
||||
}
|
||||
@@ -203,6 +250,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(
|
||||
switchMap(data => {
|
||||
if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.');
|
||||
if (selection.figura === 'fig_c2_barras') this.generalData = data;
|
||||
const periods = selection.periodos ?? data.periodos;
|
||||
if (selection.figura === 'fig_c2_donas' && periods.length > 1) {
|
||||
const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) }));
|
||||
@@ -260,7 +308,8 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas';
|
||||
if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut)
|
||||
&& state.status === 'ready' && state.figure && this.readySelection) {
|
||||
const presentation = this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
const presentation = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
|
||||
: this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
// A width change within the same label budget must not hide/repaint an
|
||||
// equivalent graph (for example when only the scrollbar gutter changes).
|
||||
@@ -279,10 +328,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||
} else if (changes['localSelection'] && this.generalState && this.readySelection && this.result().status === 'ready') {
|
||||
this.result.set(this.presentGeneral(this.generalState, this.readySelection));
|
||||
}
|
||||
const state = this.result();
|
||||
if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) {
|
||||
const next = this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
const next = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
|
||||
: this.present(state.figure, this.readySelection, state.hierarchy);
|
||||
this.result.set({ ...state, ...next, footnotes: state.source === 'datos' ? state.footnotes : next.footnotes });
|
||||
}
|
||||
return;
|
||||
@@ -296,6 +348,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
this.generation++;
|
||||
this.figureRequests.next(null);
|
||||
this.currentKey = '';
|
||||
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
|
||||
this.result.set({ status: 'deferred', message });
|
||||
}
|
||||
}
|
||||
@@ -308,6 +361,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
if (!this.visible) return;
|
||||
this.currentKey = this.requestKey();
|
||||
this.stratifiedData = undefined; this.cells = [];
|
||||
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
|
||||
this.donutPages = [];
|
||||
const applied = this.applied;
|
||||
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
|
||||
@@ -4,8 +4,8 @@ import { c2Color, c2Theme } from './indicadores-c2-palette';
|
||||
|
||||
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
||||
// No level-3 wire format is assumed. General bars keep the complete partition;
|
||||
// stratified bars have their own decoder and consume the shared local selection.
|
||||
// No level-3 wire format is assumed. This decoder keeps the complete partition;
|
||||
// local selection is applied to a separate, verified presentation copy.
|
||||
export interface C2Node { id: string; label: string; parentId?: string; }
|
||||
export interface C2Selection { path: readonly string[]; }
|
||||
export function c2Descendants(nodes: readonly C2Node[], selection: C2Selection): readonly C2Node[] {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { FigureSelection, PlotlyFigure } from './indicadores.models';
|
||||
import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const applied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] };
|
||||
describe('barras generales conectadas con la selección compartida de la dona', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http: HttpTestingController;
|
||||
const panel = () => fixture.componentInstance;
|
||||
const select = (local: DonutSelection) => { fixture.componentRef.setInput('localSelection', local); fixture.detectChanges(); };
|
||||
const request = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
const displayed = () => panel().result().presentationFigure!;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController);
|
||||
for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_barras', tema: 'claro', applied })) fixture.componentRef.setInput(k, v);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function load() { fixture.detectChanges(); request().flush(c2Fixture()); fixture.detectChanges(); }
|
||||
it('grupo → categoría → restaurar actualiza sólo la presentación, sin GET ni cambio de filtro', () => {
|
||||
load(); const original = panel().result().figure, before = structuredClone(original), all = structuredClone(displayed());
|
||||
const filter = structuredClone(panel().applied), host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']);
|
||||
select({ parent: 'G2', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B', 'C']);
|
||||
select({ parent: 'G2', category: 'B', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B']);
|
||||
expect(panel().result().figure).toBe(original); expect(original).toEqual(before);
|
||||
expect(fixture.nativeElement.querySelector('.selection-status').getAttribute('aria-label')).toContain('G2 · B · 2025-S2');
|
||||
select({}); expect(displayed()).toEqual(all); expect(panel().generalSelectionContext).toBeUndefined();
|
||||
expect(panel().applied).toEqual(filter); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true);
|
||||
});
|
||||
it('mantiene el mismo estado compacto antes, durante y después de seleccionar, fuera del lienzo', () => {
|
||||
load();
|
||||
const status = fixture.nativeElement.querySelector('.selection-status') as HTMLElement;
|
||||
const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
||||
const height = plot.style.getPropertyValue('--plot-height');
|
||||
expect(status.textContent).toContain('Distribución completa');
|
||||
expect(status.closest('.panel-controls')).toBeTruthy();
|
||||
select({ parent: 'G2', period: '2025-S2' });
|
||||
expect(fixture.nativeElement.querySelector('.selection-status')).toBe(status);
|
||||
expect(status.textContent).toContain('Selección activa');
|
||||
expect(status.getAttribute('aria-label')).toContain('denominador de la distribución completa');
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-note')).toHaveLength(0);
|
||||
expect(plot.style.getPropertyValue('--plot-height')).toBe(height);
|
||||
select({});
|
||||
expect(status.textContent).toContain('Distribución completa');
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('el estado compacto general no describe una distribución estratificada ni oculta su error', () => {
|
||||
fixture.componentRef.setInput('indicador', { ...item, filtros: [
|
||||
{ estrato: 'grupo_edad', etiqueta: 'Edad', valores: [{ valor: 'adulto', etiqueta: 'Adulto' }] },
|
||||
] });
|
||||
load(); select({ parent: 'G2', period: '2025-S2' });
|
||||
panel().chooseStratified(); request().flush({}, { status: 500, statusText: 'Failure' }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.selection-status')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy();
|
||||
expect(panel().result().status).toBe('error');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('una selección recibida mientras carga se aplica al terminar sin otro GET', () => {
|
||||
fixture.detectChanges(); const pending = request(); select({ parent: 'G2', period: '2025-S2' });
|
||||
pending.flush(c2Fixture()); fixture.detectChanges(); expect(displayed().data[0]['y']).toEqual(['B', 'C']); http.expectNone(() => true);
|
||||
});
|
||||
it('ancho y perfil conservan selección y notas desde el original', () => {
|
||||
load(); select({ parent: 'G2', period: '2025-S2' }); panel().updatePlotWidth(320);
|
||||
fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges();
|
||||
expect(displayed().data[0]['y']).toEqual(['B', 'C']); expect(panel().result().footnotes).toEqual(c2Fixture().notas);
|
||||
select({}); expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['unknown', 'wrong-parent', 'wrong-period', 'missing-period'])('%s restaura la presentación completa', kind => {
|
||||
load(); const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' });
|
||||
select({ parent: kind === 'unknown' ? 'desconocido' : kind === 'wrong-parent' ? 'G1' : 'G2', category: 'B', period: kind === 'missing-period' ? undefined : kind === 'wrong-period' ? '2026-S1' : '2025-S2' });
|
||||
expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['null', 'suppressed', 'simple'])('%s mantiene la figura completa sin nuevas peticiones', kind => {
|
||||
const data = c2Fixture();
|
||||
if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record<string, Record<string, unknown>>).forEach(c => c['grupo'] = null); }
|
||||
else { data.filas[0]['n'] = null; if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; }
|
||||
fixture.detectChanges(); request().flush(data);
|
||||
if (kind !== 'simple') http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ type: 'bar', orientation: 'h', name: '2025-S2', x: [null, 3, 1], y: ['A', 'B', 'C'] }], layout: {} });
|
||||
const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' });
|
||||
expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
it('un cambio de filtro invalida el periodo anterior aunque conserve las mismas etiquetas', () => {
|
||||
load(); select({ parent: 'G2', category: 'B', period: '2025-S2' });
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges();
|
||||
expect(panel().generalSelectionContext).toBeUndefined();
|
||||
const data = c2Fixture(); data.periodos = ['2026-S1']; data.filas.forEach(r => r['periodo'] = '2026-S1'); request().flush(data);
|
||||
expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true);
|
||||
});
|
||||
it('la dona hermana aporta el periodo, navegar restaura todas las series y no cambia el filtro global', () => {
|
||||
const periods = ['2025-S2', '2025-S1'], data = c2Fixture();
|
||||
data.periodos = periods; data.filas.push(...data.filas.map(r => ({ ...r, periodo: periods[1], n: Number(r['n']) * 2 })));
|
||||
const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tipoPeriodo: 'semestre', tema: 'claro', periodos: [periods[0]] };
|
||||
const single = c2Figure(c2Fixture(), selection); if (single.status !== 'supported') throw new Error(single.reason);
|
||||
const original: PlotlyFigure = { data: [single.figure.data[0], { ...structuredClone(single.figure.data[0]), name: periods[1], x: [12, 6, 2], text: ['60%', '30%', '10%'] }], layout: single.figure.layout };
|
||||
delete original.layout['meta'];
|
||||
fixture.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } });
|
||||
fixture.detectChanges(); request().flush(data); http.expectOne(r => r.url.includes('/figuras/')).flush(original); fixture.detectChanges();
|
||||
const full = structuredClone(displayed()), donut = TestBed.createComponent(IndicadorFigurePanel);
|
||||
for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied: panel().applied })) donut.componentRef.setInput(k, v);
|
||||
donut.componentInstance.hierarchySelected.subscribe(s => fixture.componentRef.setInput('localSelection', s));
|
||||
donut.detectChanges(); http.expectNone(() => true);
|
||||
const card = () => donut.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
||||
card().expandParent('G2'); fixture.detectChanges(); expect(displayed().data).toHaveLength(1); expect(displayed().data[0]['name']).toBe(periods[0]);
|
||||
donut.componentInstance.changeDonutPeriod(1); donut.detectChanges(); fixture.detectChanges();
|
||||
expect(displayed()).toEqual(full); expect(donut.componentInstance.donutPeriodIndex).toBe(1);
|
||||
card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges();
|
||||
expect(displayed().data[0]).toMatchObject({ name: periods[1], x: [6], y: ['B'], text: ['30%'] });
|
||||
expect(panel().applied.selection).toEqual({ mode: 'explicit', periodos: periods }); expect(panel().result().figure).toEqual(original);
|
||||
card().returnToParents(); fixture.detectChanges(); expect(displayed()).toEqual(full);
|
||||
http.expectNone(() => true); donut.destroy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||
import { FigureSelection, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
const local = { parent: 'G2', period: '2025-S2' };
|
||||
function bars(data = c2Fixture()): PlotlyFigure {
|
||||
const result = c2Figure(data, selection);
|
||||
if (result.status !== 'supported') throw new Error(result.reason);
|
||||
return result.figure;
|
||||
}
|
||||
describe('selección local segura de barras generales C2', () => {
|
||||
it('sin selección conserva la distribución completa', () => {
|
||||
const data = c2Fixture(), source = bars(data), before = structuredClone(source);
|
||||
expect(c2GeneralSelection(source, data, selection, {})).toBeUndefined();
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
|
||||
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
|
||||
const view = c2GeneralSelection(source, data, selection, local)!;
|
||||
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } });
|
||||
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
|
||||
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
|
||||
expect(view.context).toContain('G2 · 2025-S2');
|
||||
expect({ data, source }).toEqual(before);
|
||||
(view.figure.data[0]['x'] as number[])[0] = 999;
|
||||
expect(source).toEqual(before.source);
|
||||
});
|
||||
it.each([true, false])('categoría con padre declarado: %s, conserva porcentaje original sin renormalizar', withParent => {
|
||||
const data = c2Fixture(), source = bars(data);
|
||||
source.data[0]['text'] = ['60%', '30%', '10%'];
|
||||
source.data[0]['customdata'] = [['A', 10], ['B', 10], ['C', 10]];
|
||||
source.data[0]['hovertemplate'] = '%{y}: %{x} (%{text})';
|
||||
const view = c2GeneralSelection(source, data, selection, { ...local, parent: withParent ? 'G2' : undefined, category: 'B' })!;
|
||||
expect(view.figure.data[0]).toMatchObject({ x: [3], y: ['B'], text: ['30%'], customdata: [['B', 10]], hovertemplate: '%{y}: %{x} (%{text})' });
|
||||
expect(view.context).toContain('denominador de la distribución completa del periodo');
|
||||
});
|
||||
it('preserva colores escalares, arrays de errores y atributos escalares desconocidos', () => {
|
||||
const data = c2Fixture(), source = bars(data);
|
||||
source.data[0]['marker'] = { color: '#abcdef' };
|
||||
source.data[0]['error_x'] = { array: [1, 2, 3], arrayminus: [0, 1, 2] };
|
||||
source.data[0]['future'] = { retained: true };
|
||||
expect(c2GeneralSelection(source, data, selection, local)!.figure.data[0]).toMatchObject({ marker: { color: '#abcdef' }, error_x: { array: [2, 3], arrayminus: [1, 2] }, future: { retained: true } });
|
||||
});
|
||||
it.each([
|
||||
{ parent: 'inexistente', period: local.period }, { category: 'inexistente', period: local.period },
|
||||
{ parent: 'G1', category: 'B', period: local.period }, { parent: 'G2' },
|
||||
{ ...local, period: '2026-S1' }, { period: local.period },
|
||||
])('selección inválida %j mantiene la vista completa', candidate => {
|
||||
const data = c2Fixture(), source = bars(data), before = structuredClone(source);
|
||||
expect(c2GeneralSelection(source, data, selection, candidate)).toBeUndefined();
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
it.each(['simple', 'partial-hierarchy', 'missing-row', 'null', 'suppressed', 'missing-unit', 'denominator', 'ambiguous-label'])('contrato %s no produce un filtrado parcial', kind => {
|
||||
const data = c2Fixture(), source = bars(data), catalog = data['categorias'] as Record<string, Record<string, unknown>>;
|
||||
if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(catalog).forEach(c => c['grupo'] = null); }
|
||||
if (kind === 'partial-hierarchy') catalog['A']['grupo'] = null;
|
||||
if (kind === 'missing-row') data.filas.shift();
|
||||
if (kind === 'null') data.filas[0]['n'] = null;
|
||||
if (kind === 'suppressed') data.filas[0]['suprimido'] = 1;
|
||||
if (kind === 'missing-unit') delete data['unidad'];
|
||||
if (kind === 'denominator') data['denominador'] = 999;
|
||||
if (kind === 'ambiguous-label') catalog['A']['etiqueta'] = 'B';
|
||||
const before = structuredClone({ source, data });
|
||||
expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined();
|
||||
expect({ source, data }).toEqual(before);
|
||||
});
|
||||
it.each(['partial', 'mismatch', 'duplicate-period', 'unnamed', 'wrong-type', 'frames', 'menu', 'unknown-array', 'short-array', 'explicit-ticks', 'normalization', 'metadata-period', 'metadata-denominator', 'secondary-axis', 'external-data'])('figura %s conserva la presentación publicada', kind => {
|
||||
const data = c2Fixture(), source = bars(data);
|
||||
if (kind === 'partial') { source.data[0]['x'] = [3, 1]; source.data[0]['y'] = ['B', 'C']; }
|
||||
if (kind === 'mismatch') source.data[0]['x'] = [7, 3, 1];
|
||||
if (kind === 'duplicate-period') source.data.push(structuredClone(source.data[0]));
|
||||
if (kind === 'unnamed') delete source.data[0]['name'];
|
||||
if (kind === 'wrong-type') source.data[0]['type'] = 'scatter';
|
||||
if (kind === 'frames') source.frames = [{ name: 'future' }];
|
||||
if (kind === 'menu') source.layout['updatemenus'] = [];
|
||||
if (kind === 'unknown-array') source.data[0]['future'] = [1, 2, 3];
|
||||
if (kind === 'short-array') source.data[0]['text'] = ['60%'];
|
||||
if (kind === 'explicit-ticks') source.layout['yaxis'] = { tickvals: [0, 1, 2] };
|
||||
if (kind === 'normalization') source.layout['barnorm'] = 'percent';
|
||||
if (kind === 'metadata-period') source.layout['meta'] = { period: '2026-S1' };
|
||||
if (kind === 'metadata-denominator') source.layout['meta'] = { denominator: 999 };
|
||||
if (kind === 'secondary-axis') source.data[0]['yaxis'] = 'y2';
|
||||
if (kind === 'external-data') source.data[0]['xsrc'] = 'remote';
|
||||
const before = structuredClone(source);
|
||||
expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); expect(source).toEqual(before);
|
||||
});
|
||||
it('cero explícito permanece cero y no se reconstruye un valor null/suprimido', () => {
|
||||
const data = c2Fixture(); data.filas[2]['n'] = 0;
|
||||
const source = bars(data);
|
||||
expect(c2GeneralSelection(source, data, selection, { ...local, category: 'C' })!.figure.data[0]['x']).toEqual([0]);
|
||||
data.filas[2]['n'] = null; data.filas[2]['suprimido'] = 1;
|
||||
source.data[0]['x'] = [6, 3, null];
|
||||
expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined();
|
||||
expect(source.data[0]['x']).toEqual([6, 3, null]);
|
||||
});
|
||||
it('multiperiodo conserva únicamente la traza seleccionada y sus porcentajes, sin sumar periodos', () => {
|
||||
const data = c2Fixture(), source = bars(data);
|
||||
delete source.layout['meta']; // Published multiperiod bars have per-trace periods.
|
||||
data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1', n: Number(r['n']) * 2 })));
|
||||
const second = { ...structuredClone(source.data[0]), name: '2025-S1', x: [12, 6, 2], text: ['60%', '30%', '10%'] };
|
||||
source.data.push(second);
|
||||
const multiple = { ...selection, periodos: [...data.periodos] }, before = structuredClone({ data, source });
|
||||
const view = c2GeneralSelection(source, data, multiple, { ...local, period: '2025-S1' })!;
|
||||
expect(view.figure.data).toHaveLength(1);
|
||||
expect(view.figure.data[0]).toMatchObject({ name: '2025-S1', x: [6, 2], y: ['B', 'C'], text: ['30%', '10%'] });
|
||||
expect(c2GeneralSelection(source, data, selection, { ...local, period: '2025-S1' })).toBeUndefined();
|
||||
expect(c2GeneralSelection(source, data, multiple, {})).toBeUndefined();
|
||||
expect({ data, source }).toEqual(before);
|
||||
});
|
||||
it('Todos con reporte: un periodo sin traza publicada conserva la vista completa disponible', () => {
|
||||
const data = c2Fixture(), source = bars(data);
|
||||
data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1' })));
|
||||
const before = structuredClone(source);
|
||||
expect(c2GeneralSelection(source, data, { ...selection, periodos: undefined }, { ...local, period: '2025-S1' })).toBeUndefined();
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
it.each([
|
||||
{ id: 'cacu_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
{ id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
{ id: 'cama_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Benigno', ANORMAL: 'Cáncer', SIN_DATO: 'Sin dato' },
|
||||
categories: [['BENIGNO', 'Benigno', 'NO_ANORMAL'], ['CARCINOMA_IN_SITU', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA_INVASOR', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
])('$id: relaciones publicadas con conteos sintéticos, sin reglas por ID', candidate => {
|
||||
const data = c2Fixture(); data.id = candidate.id; data['unidad'] = candidate.unit;
|
||||
data['grupos_de_categoria'] = candidate.groups;
|
||||
data['categorias'] = Object.fromEntries(candidate.categories.map(([id, etiqueta, grupo]) => [id, { etiqueta, grupo }]));
|
||||
data.filas = candidate.categories.map(([categoria], orden) => ({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, orden, n: orden + 1, suprimido: 0 }));
|
||||
const s = { ...selection, indicador: candidate.id }, adapted = c2Figure(data, s);
|
||||
if (adapted.status !== 'supported') throw new Error(adapted.reason);
|
||||
const source = adapted.figure, parent = candidate.groups.ANORMAL;
|
||||
expect(c2GeneralSelection(source, data, s, { parent, period: local.period })!.figure.data[0]['y'])
|
||||
.toEqual(candidate.categories.filter(c => c[2] === 'ANORMAL').map(c => c[1]));
|
||||
const category = candidate.categories.find(c => c[2] === 'ANORMAL')![1];
|
||||
expect(c2GeneralSelection(source, data, s, { parent, category, period: local.period })!.figure.data[0]['y']).toEqual([category]);
|
||||
// Re-identification does not change capabilities or behavior.
|
||||
data.id = 'otro-identificador';
|
||||
expect(c2GeneralSelection(source, data, { ...s, indicador: data.id }, { parent, period: local.period })).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { periodDatos } from './indicadores-donut-periods';
|
||||
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
// Only known per-point arrays may be sliced. Unknown array semantics require
|
||||
// the complete presentation, rather than risking misaligned metadata.
|
||||
const pointArrays = new Set([
|
||||
'x', 'y', 'text', 'hovertext', 'customdata', 'ids', 'hovertemplate', 'texttemplate', 'textposition',
|
||||
'base', 'width', 'offset', 'marker.color', 'marker.opacity', 'marker.line.color', 'marker.line.width',
|
||||
'marker.pattern.shape', 'marker.pattern.size', 'marker.pattern.solidity', 'marker.pattern.fgcolor', 'marker.pattern.bgcolor',
|
||||
'error_x.array', 'error_x.arrayminus', 'error_y.array', 'error_y.arrayminus',
|
||||
'textfont.color', 'textfont.size', 'textfont.family', 'insidetextfont.color', 'insidetextfont.size', 'insidetextfont.family',
|
||||
'outsidetextfont.color', 'outsidetextfont.size', 'outsidetextfont.family',
|
||||
]);
|
||||
|
||||
export interface C2GeneralSelection { figure: PlotlyFigure; context: string; }
|
||||
// Select published observations, never recompute a denominator or interpret a
|
||||
// visual parent as filas[].grupo (the latter is the statistical population).
|
||||
export function c2GeneralSelection(source: PlotlyFigure, data: IndicadorDatos,
|
||||
selection: FigureSelection, local: DonutSelection): C2GeneralSelection | undefined {
|
||||
const period = local.period;
|
||||
if (selection.figura !== 'fig_c2_barras' || (!local.parent && !local.category) || !period
|
||||
|| !data.periodos.includes(period) || (selection.periodos && !selection.periodos.includes(period))
|
||||
|| source.frames?.length || source.layout['sliders'] !== undefined || source.layout['updatemenus'] !== undefined
|
||||
|| !!source.layout['barnorm'] || Object.keys(source.layout).some(key => /^[xy]axis\d+$/.test(key))) return;
|
||||
const adapted = c2Figure(periodDatos(data, period), { ...selection, periodos: [period] });
|
||||
if (adapted.status !== 'supported' || !adapted.model.parents.length || !adapted.model.categories.length) return;
|
||||
const { categories, parents } = adapted.model;
|
||||
const meta = source.layout['meta'];
|
||||
if (record(meta) && ((meta['period'] !== undefined && meta['period'] !== period)
|
||||
|| (meta['denominator'] !== undefined && meta['denominator'] !== adapted.model.total))) return;
|
||||
const parent = local.parent ? parents.find(p => p.label === local.parent) : undefined;
|
||||
const category = local.category ? categories.find(c => c.label === local.category) : undefined;
|
||||
if ((local.parent && !parent) || (local.category && !category)
|
||||
|| (parent && category && 'group:' + category.parentId !== parent.id)) return;
|
||||
const selected = categories.filter(c => (!parent || 'group:' + c.parentId === parent.id) && (!category || c.id === category.id));
|
||||
if (!selected.length) return;
|
||||
// A trace must explicitly identify its period and match the entire verified
|
||||
// partition before any categories are hidden. Never filter a partial trace.
|
||||
const names = source.data.map(t => t['name']);
|
||||
if (new Set(names).size !== names.length || source.data.some(t => t['type'] !== 'bar' || t['orientation'] !== 'h'
|
||||
|| typeof t['name'] !== 'string' || !data.periodos.includes(t['name']))) return;
|
||||
const trace = source.data.find(t => t['name'] === period);
|
||||
if (!trace || !Array.isArray(trace['x']) || !Array.isArray(trace['y'])
|
||||
|| ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined)
|
||||
|| (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y')
|
||||
|| trace['x'].length !== categories.length || trace['y'].length !== categories.length
|
||||
|| new Set(trace['y']).size !== categories.length) return;
|
||||
const labels = trace['y'] as unknown[], values = trace['x'] as unknown[];
|
||||
if (categories.some(c => { const i = labels.indexOf(c.label); return i < 0 || values[i] !== c.value; })) return;
|
||||
const indices = labels.flatMap((label, i) => selected.some(c => c.label === label) ? [i] : []);
|
||||
let compatible = true;
|
||||
const slice = (value: unknown, path: string): unknown => {
|
||||
if (Array.isArray(value)) {
|
||||
if (!pointArrays.has(path) || value.length !== categories.length) { compatible = false; return value; }
|
||||
return indices.map(i => structuredClone(value[i]));
|
||||
}
|
||||
if (record(value)) return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, slice(v, path ? path + '.' + key : key)]));
|
||||
return value;
|
||||
};
|
||||
const filtered = slice(trace, '') as Record<string, unknown>;
|
||||
if (!compatible) return;
|
||||
const axis = source.layout['yaxis'];
|
||||
if (record(axis) && (axis['tickvals'] !== undefined || axis['ticktext'] !== undefined
|
||||
|| (axis['type'] !== undefined && axis['type'] !== 'category'))) return;
|
||||
const figure = structuredClone(source);
|
||||
figure.data = [filtered];
|
||||
if (record(figure.layout['yaxis']) && Array.isArray(figure.layout['yaxis']['categoryarray'])) {
|
||||
figure.layout['yaxis']['categoryarray'] = figure.layout['yaxis']['categoryarray'].filter(v => selected.some(c => c.label === v));
|
||||
}
|
||||
return { figure, context: 'Vista local de la dona: ' + [local.parent, local.category, period].filter(Boolean).join(' · ')
|
||||
+ '. Sólo se muestran las categorías seleccionadas de este periodo. Los conteos y porcentajes conservan el denominador de la distribución completa del periodo.' };
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
|
||||
|
||||
function eu7Datos() {
|
||||
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
|
||||
}
|
||||
describe('EU7 modelo de presentación del entregable', () => {
|
||||
let data: ReturnType<typeof eu7Datos>;
|
||||
beforeEach(() => data = eu7Datos());
|
||||
const periodo = '2025-S2';
|
||||
const model = () => modelo(data.general, data.escenarios, periodo);
|
||||
it('946 con resultado y 87 sin dato; anillos pie conservan categorías, colores y no mutan el original', () => {
|
||||
const original = structuredClone(data), m = model(), f = dona(m, {}, 'claro');
|
||||
expect(m.total).toBe(946); expect(m.sinDato.n).toBe(87);
|
||||
expect(f.data.map(t => t['type'])).toEqual(['pie', 'pie', 'pie']);
|
||||
expect(f.data[2]['labels']).not.toContain('Sin dato');
|
||||
expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]);
|
||||
expect(data).toEqual(original);
|
||||
});
|
||||
it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => {
|
||||
const m = model(); let s: Seleccion = {};
|
||||
const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG');
|
||||
s = clic(m, s, 'grupos', g); expect(s).toEqual({ grupo: 'ANORMAL' });
|
||||
s = clic(m, s, 'categorias', c); expect(s).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||
expect(clic(m, s, 'categorias', c)).toEqual({ grupo: 'ANORMAL' });
|
||||
s = clic(m, s, 'centro', 0); expect(s).toEqual({ grupo: 'ANORMAL' });
|
||||
s = clic(m, s, 'centro', 0); expect(s).toEqual({});
|
||||
expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({});
|
||||
expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({});
|
||||
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' });
|
||||
expect(clic(m, {}, 'otra', c)).toEqual({});
|
||||
expect(clic(m, {}, 'grupos', -1)).toEqual({});
|
||||
expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' });
|
||||
});
|
||||
it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => {
|
||||
const m = model(), f = barras(m, {}, 'claro');
|
||||
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8));
|
||||
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
|
||||
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
|
||||
.toEqual(['5.0', '24.3', '21.7', '7.8']);
|
||||
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
expect(category.data).toHaveLength(1);
|
||||
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
|
||||
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
|
||||
});
|
||||
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
|
||||
if (kind === 'estrato') data.escenarios['estrato'] = 'grupo_edad';
|
||||
if (kind === 'categorias') (data.escenarios['categorias'] as any)['LIEAG'].etiqueta = 'Otra';
|
||||
if (kind === 'periodos') data.escenarios.periodos = ['2025-S1'];
|
||||
if (kind === 'orden') data.escenarios.filas[0]['orden'] = 5;
|
||||
if (kind === 'duplicado') data.escenarios.filas.push(data.escenarios.filas[0]);
|
||||
if (kind === 'version') data.escenarios['version'] = 'otra';
|
||||
if (kind === 'filtros') data.escenarios['filtros'] = { grupo_edad: '25-34' };
|
||||
if (kind === 'total') (data.escenarios['totales_estrato'] as any[])[0].n++;
|
||||
if (kind === 'diferencia') data.general.filas[0]['n'] = 800;
|
||||
expect(model).toThrow();
|
||||
});
|
||||
it('no acepta periodos omitidos por el servidor ni respuestas fuera de la selección', () => {
|
||||
expect(() => periodosCompatibles(data.general, data.escenarios, 'semestre', ['2025-S1', periodo])).toThrow();
|
||||
expect(() => periodosCompatibles(data.general, data.escenarios, 'mes', [periodo])).toThrow();
|
||||
});
|
||||
it('rechaza procedencias diferentes entre respuestas incluso con conteos iguales', () => {
|
||||
data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }];
|
||||
expect(model).toThrow(/reportes distintos/);
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: todos los puntos son null y no hay denominador inventado', kind => {
|
||||
const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!;
|
||||
if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row);
|
||||
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
|
||||
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
|
||||
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
|
||||
expect(JSON.stringify(f)).not.toContain('123456');
|
||||
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin fila'])('general con %s nunca produce una dona parcial ni convierte null en cero', kind => {
|
||||
if (kind === 'sin fila') data.general.filas.splice(0, 1);
|
||||
else Object.assign(data.general.filas[0], { n: null, suprimido: kind === 'suprimido' ? 1 : 0 });
|
||||
const m = model(); expect(m.total).toBeNull(); expect(dona(m, {}, 'claro').data).toEqual([]);
|
||||
});
|
||||
it('escenario ausente no se inventa; solo se dibujan escenarios con filas publicadas', () => {
|
||||
const removed = data.escenarios.filas.filter(f => f['estrato'] === 'INFO_INSUFICIENTE');
|
||||
data.escenarios.filas = data.escenarios.filas.filter(f => f['estrato'] !== 'INFO_INSUFICIENTE');
|
||||
data.general.filas.forEach(f => f['n'] = (f['n'] as number) - (removed.find(r => r['categoria'] === f['categoria'])!['n'] as number));
|
||||
const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE');
|
||||
expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3);
|
||||
});
|
||||
it('escenario vacío y periodo de ceros no producen porcentajes 0/0', () => {
|
||||
data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0);
|
||||
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
|
||||
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
|
||||
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
||||
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
|
||||
});
|
||||
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
||||
data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = [];
|
||||
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
|
||||
expect(m.celdas['NORMAL'].n).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
||||
export const ESTRATO = 'estatus_seguimiento';
|
||||
const SIN_DATO = 'SIN_DATO';
|
||||
export interface Seleccion { grupo?: string; categoria?: string; }
|
||||
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface Grupo { id: string; etiqueta: string; color: string; }
|
||||
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export interface Escenario {
|
||||
id: string; etiqueta: string; celdas: Record<string, Celda>;
|
||||
den: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible';
|
||||
}
|
||||
export interface Modelo {
|
||||
periodo: string; categorias: Categoria[]; grupos: Grupo[];
|
||||
celdas: Record<string, Celda>; total: number | null; sinDato: Celda;
|
||||
escenarios: Escenario[]; vacio: boolean; notas: string[];
|
||||
sinDatoEtiqueta: string;
|
||||
}
|
||||
export class Eu7Incompatible extends Error {}
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const fail = (message: string): never => { throw new Eu7Incompatible(message); };
|
||||
function celda(fila?: Record<string, unknown>): Celda {
|
||||
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
|
||||
return typeof fila?.['n'] === 'number' && fila['suprimido'] === 0
|
||||
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
|
||||
}
|
||||
function suma(celdas: Celda[]): number | null {
|
||||
if (celdas.some(c => c.n === null)) return null;
|
||||
const value = celdas.reduce((s, c) => s + c.n!, 0);
|
||||
return Number.isSafeInteger(value) ? value : fail('Conteos fuera de rango.');
|
||||
}
|
||||
function estado(celdas: Celda[]): Escenario['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
|
||||
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
function catalogo(data: IndicadorDatos): Categoria[] {
|
||||
const cats = data['categorias'], grupos = data['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.');
|
||||
const result = Object.entries(cats).map(([id, c]) => {
|
||||
if (!registro(c) || typeof c['etiqueta'] !== 'string' || !c['etiqueta'].trim()
|
||||
|| typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])
|
||||
|| typeof c['grupo'] !== 'string' || typeof grupos[c['grupo']] !== 'string'
|
||||
|| (id === SIN_DATO) !== (c['grupo'] === SIN_DATO)) return fail('Categorías EU7 incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: c['color'], grupo: c['grupo'] };
|
||||
});
|
||||
if (result.length < 2 || new Set(result.map(c => c.etiqueta)).size !== result.length) return fail('Categorías EU7 ambiguas.');
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Validate the common temporal scope before exposing any period's figures. */
|
||||
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||
for (const d of [general, escenarios]) {
|
||||
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string'
|
||||
|| !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||||
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
|
||||
return fail('Los datos EU7 no corresponden al indicador o al periodo aplicado.');
|
||||
}
|
||||
}
|
||||
if (general.periodos.length !== escenarios.periodos.length || general.periodos.some(p => !escenarios.periodos.includes(p))
|
||||
|| (solicitados && (solicitados.length !== general.periodos.length || solicitados.some(p => !general.periodos.includes(p))))
|
||||
|| general['version'] !== escenarios['version'] || general['unidad'] !== escenarios['unidad']) {
|
||||
return fail('Las respuestas general y estratificada no comparten periodos, versión o unidad.');
|
||||
}
|
||||
return solicitados ? [...solicitados] : [...general.periodos].sort();
|
||||
}
|
||||
|
||||
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
|
||||
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo {
|
||||
periodosCompatibles(general, porEscenario, general.tipo_periodo);
|
||||
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
|
||||
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo)
|
||||
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|
||||
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|
||||
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
|
||||
return fail('Respuestas EU7 inválidas para el escenario clínico sin filtros locales.');
|
||||
}
|
||||
const cats = catalogo(general), other = catalogo(porEscenario);
|
||||
const nombres = general['grupos_de_categoria'] as Record<string, string>;
|
||||
const otrosNombres = porEscenario['grupos_de_categoria'] as Record<string, string>;
|
||||
if (cats.length !== other.length || cats.some(c => {
|
||||
const o = other.find(v => v.id === c.id);
|
||||
return !o || o.etiqueta !== c.etiqueta || o.color !== c.color || o.grupo !== c.grupo
|
||||
|| nombres[c.grupo] !== otrosNombres[c.grupo];
|
||||
})) return fail('Los catálogos general y estratificado son diferentes.');
|
||||
const orden = new Map<string, number>();
|
||||
const indexar = (d: IndicadorDatos, estratificado: boolean) => {
|
||||
const index = new Map<string, Record<string, unknown>>();
|
||||
for (const row of d.filas.filter(f => f['periodo'] === periodo)) {
|
||||
const c = row['categoria'], e = row['estrato'], n = row['n'], o = row['orden'];
|
||||
if (row['grupo'] !== 'TOTAL' || typeof c !== 'string' || !cats.some(cat => cat.id === c)
|
||||
|| (estratificado ? typeof e !== 'string' || !valores.includes(e) : e != null)
|
||||
|| typeof o !== 'number' || !Number.isSafeInteger(o) || o < 0
|
||||
|| ![0, 1].includes(row['suprimido'] as number)
|
||||
|| (n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) return fail('Fila EU7 inválida.');
|
||||
const key = JSON.stringify([estratificado ? e : null, c]);
|
||||
if (index.has(key) || (orden.has(c) && orden.get(c) !== o)) return fail('Filas u orden EU7 ambiguos.');
|
||||
orden.set(c, o); index.set(key, row);
|
||||
}
|
||||
return index;
|
||||
};
|
||||
const g = indexar(general, false), e = indexar(porEscenario, true);
|
||||
const reporte = (d: IndicadorDatos) => {
|
||||
const reports = d['reportes'];
|
||||
if (reports === undefined) return undefined;
|
||||
if (!Array.isArray(reports) || !reports.every(registro)) return fail('Procedencia EU7 inválida.');
|
||||
const active = reports.filter(r => r['periodo'] === periodo);
|
||||
if (active.length !== 1) return fail('Procedencia del periodo EU7 ambigua.');
|
||||
return active[0];
|
||||
};
|
||||
const rg = reporte(general), re = reporte(porEscenario);
|
||||
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
|
||||
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id],
|
||||
color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) }));
|
||||
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||
const totals = porEscenario['totales_estrato'];
|
||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||
const escenarios: Escenario[] = (valores as string[]).filter(v => [...e.values()].some(row => row['estrato'] === v)).map(id => {
|
||||
const cells = Object.fromEntries(cats.map(c => [c.id, celda(e.get(JSON.stringify([id, c.id])))]));
|
||||
const matches = (totals as Record<string, unknown>[] | undefined)?.filter(t => t['periodo'] === periodo && t['estrato'] === id) ?? [];
|
||||
if (matches.length > 1 || matches.some(t => t['grupo'] !== 'TOTAL' || ![0, 1].includes(t['suprimido'] as number)
|
||||
|| (t['n'] !== null && (typeof t['n'] !== 'number' || !Number.isSafeInteger(t['n']) || t['n'] < 0)))) return fail('Total de escenario ambiguo.');
|
||||
const total = matches[0] && celda(matches[0]);
|
||||
const estadoEscenario = estado([...Object.values(cells), ...(total ? [total] : [])]);
|
||||
const completo = suma(Object.values(cells));
|
||||
if (completo !== null && total?.n != null && completo !== total.n) return fail('El total del escenario difiere de sus categorías.');
|
||||
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
|
||||
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
|
||||
});
|
||||
// Compare only fully published sums. Never derive a hidden value by subtraction.
|
||||
if (escenarios.length) {
|
||||
for (const c of cats) {
|
||||
const total = suma(escenarios.map(s => s.celdas[c.id]));
|
||||
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
|
||||
}
|
||||
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
|
||||
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
|
||||
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
|
||||
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
||||
}
|
||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||
const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id]));
|
||||
export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string {
|
||||
return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta
|
||||
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL';
|
||||
}
|
||||
/** Same state machine as the deliverable, with guards for unrelated/stale events. */
|
||||
export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number): Seleccion {
|
||||
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
|
||||
if (traza === 'grupos') {
|
||||
const g = m.grupos[indice]?.id;
|
||||
return !g ? sel : sel.grupo === g ? {} : { grupo: g };
|
||||
}
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.categorias[indice];
|
||||
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||
return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id };
|
||||
}
|
||||
export function porcentaje(s: Escenario, categoria: string): number | null {
|
||||
const n = s.celdas[categoria]?.n;
|
||||
return s.den !== null && s.den > 0 && n != null ? 100 * n / s.den : null;
|
||||
}
|
||||
/** Three pies share one square plot area; SIN_DATO never enters their values. */
|
||||
export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
if (m.total === null || m.total === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema);
|
||||
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0);
|
||||
const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0);
|
||||
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
|
||||
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||
const total = values.reduce((s, n) => s + n, 0);
|
||||
return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `<br>${(100 * v / total).toFixed(0)} %` : ''));
|
||||
};
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
||||
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes · %{customdata[1]} % del total con resultado<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
||||
textfont: { size: 11 }, customdata: custom(exterior),
|
||||
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
/** Selection never changes the original denominator or renormalizes a subset. */
|
||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
|
||||
const y = m.escenarios.map(s => escapar(s.etiqueta));
|
||||
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
|
||||
return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => {
|
||||
const x = m.escenarios.map(s => porcentaje(s, c.id));
|
||||
return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x,
|
||||
marker: { color: c.color, line: { color: p.background, width: 1 } },
|
||||
text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
|
||||
customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]),
|
||||
hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` };
|
||||
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 24, l: 150, r: 36, b: 90 }, showlegend: false,
|
||||
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
||||
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
|
||||
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 100] },
|
||||
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
|
||||
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
|
||||
: sel.grupo || sel.categoria ? `<b>${sumas[i]!.toFixed(1)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${s.den})` : '' })),
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -108,7 +108,9 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => {
|
||||
choose(); http.expectNone(r => r.url.includes('/figuras/'));
|
||||
cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); });
|
||||
fixture.detectChanges(); flushFigures(periods[1], items.length); http.expectNone(() => true);
|
||||
// EU7 now owns a coordinated C2 view. This temporal fixture publishes only
|
||||
// placeholder f/g figures, so that card must stop as incompatible, without GET.
|
||||
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true);
|
||||
});
|
||||
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
|
||||
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
|
||||
@@ -126,9 +128,10 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
|
||||
choose(); const applied = page.filters!.applied;
|
||||
page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true);
|
||||
cards()[0].setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
cards()[0].selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
expect(cards()[0].selectedFigure).toBe('g'); http.expectNone(() => true);
|
||||
const card = cards().find(card => !card.isEu7)!;
|
||||
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
|
||||
expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready');
|
||||
});
|
||||
it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => {
|
||||
|
||||
@@ -44,28 +44,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
const harness = await setup();
|
||||
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
load(domain, harness); harness.detectChanges();
|
||||
const links = Array.from(harness.routeNativeElement!.querySelectorAll('nav a')) as HTMLAnchorElement[];
|
||||
expect(links.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu', 'CaMa']);
|
||||
expect(links.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu', '/indicadores/cama']);
|
||||
const selected = links.find(a => a.getAttribute('aria-current') === 'page')!;
|
||||
expect(selected.getAttribute('href')).toBe('/indicadores/' + domain);
|
||||
expect(links.filter(a => a.hasAttribute('aria-current'))).toHaveLength(1);
|
||||
// Check the compiled CSSOM rule against the actual encapsulated element.
|
||||
// jsdom's computed link decoration can remain stale after aria-current changes.
|
||||
const activeRule = Array.from(document.styleSheets).flatMap(sheet => Array.from(sheet.cssRules))
|
||||
.find((rule): rule is CSSStyleRule => rule instanceof CSSStyleRule
|
||||
&& rule.selectorText.includes('[aria-current=') && selected.matches(rule.selectorText))!;
|
||||
expect(activeRule).toBeTruthy();
|
||||
expect(activeRule.style.getPropertyValue('text-decoration')).toBe('none');
|
||||
expect(activeRule.style.getPropertyValue('font-weight')).toBe('700');
|
||||
expect(activeRule.style.getPropertyValue('background')).toBe('var(--issste-accent)');
|
||||
for (const link of links) {
|
||||
expect(link.tabIndex).toBe(0);
|
||||
link.focus(); expect(document.activeElement).toBe(link);
|
||||
const key = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true });
|
||||
link.dispatchEvent(key); expect(key.defaultPrevented).toBe(false);
|
||||
expect(selected.getAttribute('aria-current')).toBe('page');
|
||||
}
|
||||
expect(harness.routeNativeElement!.querySelector('nav')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
|
||||
|
||||
@@ -178,16 +178,20 @@ describe('card doble, jerarquía y carga numérica diferida', () => {
|
||||
expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('drill-down y restauración de dona no alteran barras, JSON original ni generan consultas', () => {
|
||||
it('drill-down filtra la presentación de barras y restaurar recupera la distribución sin alterar JSON ni consultar', () => {
|
||||
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges();
|
||||
const bars = structuredClone(panels()[1].result().figure);
|
||||
const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard);
|
||||
const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result();
|
||||
const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf<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);
|
||||
expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B', 'C']);
|
||||
expect(panels()[1].result().figure).toBe(barState.figure); expect(panels()[1].result().figure).toEqual(bars);
|
||||
cards[0].selectCategory('B'); fixture.detectChanges();
|
||||
expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B']);
|
||||
(fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); http.expectNone(() => true);
|
||||
expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before);
|
||||
expect(panels()[1].result().presentationFigure).toEqual(barState.presentationFigure); http.expectNone(() => true);
|
||||
});
|
||||
it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => {
|
||||
snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true);
|
||||
|
||||
@@ -4,12 +4,6 @@
|
||||
<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"
|
||||
|
||||
@@ -9,7 +9,7 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.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 { align-items: stretch; }
|
||||
.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; }
|
||||
@@ -24,32 +24,8 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
@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; }
|
||||
|
||||
@@ -112,22 +112,15 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
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-06B deja la navegación entre dominios en el shell y no duplica botones en la página', () => {
|
||||
expect(fixture.nativeElement.querySelector('nav')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelectorAll('[routerLink]')).toHaveLength(0);
|
||||
expect(cards()).toHaveLength(0);
|
||||
// Constructing the page legitimately initializes its domain catalog.
|
||||
const catalogRequest = http.expectOne('/tea/indicadores');
|
||||
expect(catalogRequest.request.method).toBe('GET');
|
||||
catalogRequest.flush([]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('UX-06D retira el selector visual, inicia claro y conserva oscuro sin recargar catálogo', async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { ActivatedRoute } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
@@ -30,7 +30,7 @@ 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],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNumericSummary],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
|
||||
@@ -40,7 +40,8 @@ describe('Secciones compartidas por dominio', () => {
|
||||
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]);
|
||||
// Domain selection belongs to App; this route-only harness verifies page sections.
|
||||
expect(root.querySelector('nav')).toBeNull();
|
||||
for (const tab of tabs) {
|
||||
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
|
||||
expect(panel.getAttribute('aria-labelledby')).toBe(tab.id);
|
||||
|
||||
Reference in New Issue
Block a user