Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 26fe1ccbb3 | |||
| 94c63c460c | |||
| 05a9967906 | |||
| 1c0bdf6184 | |||
| 70aa739f97 | |||
| 394f2c626b | |||
| 644803cf21 | |||
| 8e9a40dec4 | |||
| 1bdec1b838 | |||
| 220d5b9d26 | |||
| fbfd97ec31 | |||
| 18692acc88 | |||
| 6c84dab730 | |||
| 12ce93f58c | |||
| dcaf1a8832 | |||
| 04d529392e | |||
| 6f3e7e22f9 | |||
| 12a0398903 | |||
| 03e51c07cc | |||
| e6be341ad9 | |||
| 85ec11ab0f | |||
| db9ab0d1a7 | |||
| af70d6f378 | |||
| 1940f4fa47 | |||
| ec406d5d2d | |||
| 7b82427713 | |||
| ec642df834 | |||
| 540506bde0 | |||
| 14fd765122 | |||
| a30dbbb102 |
@@ -0,0 +1,81 @@
|
||||
# Bitácora de textos de pantalla
|
||||
|
||||
Textos que la WebApp escribe a mano en lugar de tomarlos del kit (`indicadores_kit`), por qué
|
||||
y qué hay que mantener al día. Lo más reciente, arriba.
|
||||
|
||||
## 2026-10-25 · «Valores publicados»
|
||||
|
||||
- Las tablas desplegables decían «Valores publicados y celdas suprimidas» o «… y cajas no
|
||||
disponibles», que confundía. Ahora dicen «Valores publicados».
|
||||
- La tabla de contingencia de citología y biopsia (Tasa de confirmación histopatológica) estaba
|
||||
siempre a la vista; ahora va plegada bajo «Valores publicados», como las demás.
|
||||
- En el kit (IND1 0.3.2), la ficha de «Pacientes con citología anómala» ya no cita
|
||||
`kpi_catalog.yaml` en sus referencias: era un archivo interno de trabajo. Las referencias de
|
||||
las demás fichas de cáncer cervicouterino citan las guías europeas y se quedan.
|
||||
|
||||
## Pendientes (2026-10-25)
|
||||
|
||||
- **Método estadístico en la ficha técnica.** Pospuesto: escrito en cada TOML implica subir la
|
||||
versión de muchos indicadores.
|
||||
- **Más campos en la ficha de cáncer cervicouterino**, armados con lo que `/metadatos` ya manda y
|
||||
la ficha no muestra: cada grupo con sus categorías («LIEAG o más: LIEAG (CIN 2 y 3), Carcinoma
|
||||
in situ, Carcinoma invasor»), filtros y estratificadores, qué población es el numerador o el
|
||||
denominador, y quitar «Código». Pospuesto por el volumen de texto a revisar.
|
||||
- **«Calidad de espécimen satisfactoria».** Los textos lo dirán así, pero la consulta
|
||||
(`ultima_valida` del kit) acepta toda citología con resultado cuya calidad no sea
|
||||
insatisfactoria, incluidas las que no tienen calidad registrada. Se cambiará la consulta para
|
||||
exigir «satisfactoria». En el hospital el campo es obligatorio, así que los números no deberían
|
||||
cambiar; en el simulador sí, porque genera un 5 % sin calidad (`proporcion_sin_calidad`).
|
||||
- **Tiempo de tamizaje a diagnóstico: «benigno».** La descripción y la definición dicen «(normal,
|
||||
benigno, lesión o cáncer)», pero la lista de diagnósticos (`cacu.diagnostico.cie`) no tiene un
|
||||
grupo benigno: examen y pesquisa normales, VPH, hallazgo anormal en citología, displasia,
|
||||
carcinoma in situ y cáncer. Las poblaciones ya dicen «normal, de VPH, de lesión o de cáncer».
|
||||
Falta decidir si «benigno» se cambia por «VPH».
|
||||
- **Valores escritos en el texto.** Las poblaciones de los indicadores de cáncer cervicouterino
|
||||
dicen el valor de sus parámetros (180 días, ASC-H, LIEAG o carcinoma in situ…) en lugar de su
|
||||
nombre. Si un parámetro cambia, hay que cambiar el texto; lo avisa el comentario de la versión
|
||||
en cada TOML.
|
||||
- **IND1 no aplica la fecha de corte ni la calidad del espécimen.** Cuenta cualquier resultado
|
||||
anómalo de una citología del periodo, aunque se haya reportado después del corte o la muestra
|
||||
sea insatisfactoria. EU7 y Confirmación histopatológica sí aplican las dos reglas. Alinearlo
|
||||
cambia los números: va con el cambio de la consulta de «calidad satisfactoria».
|
||||
- **La nota de la ficha de los tiempos** («La caja va del primer al tercer cuartil y la línea es
|
||||
la mediana…») sirve bajo la figura, pero también aparece como «Nota» en la ficha técnica, donde
|
||||
no hay caja. Sin decidir.
|
||||
|
||||
## 2026-10-25 · «Sin dato» de la dona de resultados citológicos
|
||||
|
||||
- La nota bajo la dona decía «pacientes sin resultado válido en el periodo»; ahora dice
|
||||
«pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de
|
||||
corte», que es lo que cuenta la consulta (`indicador-eu7-escenario.ts`). Sin total: «Total de
|
||||
la dona no disponible.» (antes «Total con resultado no disponible.»).
|
||||
- Dona vacía: «Sin pacientes con resultado disponible para la dona.»
|
||||
|
||||
## 2026-10-25 · «CaCu» es un nombre interno
|
||||
|
||||
- En pantalla, «CaCu» pasa a «cáncer cervicouterino» (`domainLabels` de `indicadores-page.ts` y
|
||||
`domainNames` de `indicadores-definitions.ts`). Con mayúscula donde abre el texto: la línea
|
||||
«Cáncer cervicouterino, investigación» (`domainTitles`). TEA y CaMa no cambian de nombre.
|
||||
- El botón del encabezado para cambiar de proyecto (`app.ts`) sigue diciendo «CaCu»: es
|
||||
provisional (usuario). Solo es la etiqueta: la dirección sigue siendo `/indicadores/cacu`.
|
||||
- La línea del encabezado ya no dice «Dominio»: «<proyecto>, investigación».
|
||||
- «Dashboard de indicadores» pasa a «Indicadores» y el subtítulo a «Explora los indicadores de
|
||||
<proyecto>.» (antes: «…de indicadores <proyecto> generadas por el servicio de reportes»).
|
||||
- «Datos y definiciones» ya no dice «Dominio: <proyecto>.»: repetía el título.
|
||||
- Siguen igual «Cambiar dominio» y su lectura en voz alta.
|
||||
|
||||
## 2026-10-25 · Tarjetas de indicadores de oportunidad de CaCu
|
||||
|
||||
- Las tarjetas de CaCu ya no muestran las notas del kit (`notas` de `/datos`, que son el pie de
|
||||
las figuras: repetían la definición completa y, en los tiempos, hablaban de la caja). Dicen
|
||||
solo su línea, escrita en `indicadores-kpi.ts`. TEA y CaMa no cambian
|
||||
(`indicador-kpi-panel.ts`).
|
||||
- «Pacientes evaluadas»: «Pacientes con citología tomada en el periodo.» El número no cambia:
|
||||
incluye a las pacientes cuyo espécimen fue insatisfactorio (en la dona van en «Sin dato»).
|
||||
- «Tiempo de tamizaje a diagnóstico»: «*n* citologías; primer cuartil: *x* días; tercer
|
||||
cuartil: *y* días.» Sin «Q1» ni «Q3»: el público es médico.
|
||||
- «Datos y definiciones» de CaCu dice, bajo el dominio, que «Pacientes evaluadas» incluye las
|
||||
citologías con espécimen insatisfactorio.
|
||||
|
||||
Si cambia la definición de `cacu_eu7` o de `cacu_dias_toma_diagnostico` en el kit, revisar
|
||||
estos textos.
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ it('permite acceso directo a /indicadores sin guard ni autenticación', async ()
|
||||
const harness = await RouterTestingHarness.create();
|
||||
await harness.navigateByUrl('/indicadores', IndicadoresPage);
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
||||
expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores');
|
||||
expect(harness.routeNativeElement?.textContent).toContain('Indicadores');
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
http.verify();
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,22 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
||||
respond();
|
||||
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
|
||||
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
|
||||
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
|
||||
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||
fixture.componentInstance.apply();
|
||||
let req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
req.flush(fixtureData); fixture.detectChanges();
|
||||
fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
expect(req.request.params.get('page')).toBe('2');
|
||||
req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
||||
});
|
||||
it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => {
|
||||
fixture.detectChanges(); http.expectNone(()=>true); respond();
|
||||
const root:HTMLElement=fixture.nativeElement;
|
||||
@@ -23,12 +39,18 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||
expect(root.textContent).toContain('Ventana consultada:');
|
||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/);
|
||||
expect(root.querySelector('tbody tr td:last-child')?.textContent).toBe('No disponible');
|
||||
expect(root.querySelector('tbody tr td:nth-child(8)')?.textContent).toBe('No disponible');
|
||||
expect(root.querySelector('thead')?.textContent).not.toContain('Acciones');
|
||||
expect(root.querySelectorAll('tbody button.patient-link')).toHaveLength(10);
|
||||
expect(root.querySelector('tbody button.patient-link')?.getAttribute('aria-label')).toContain(fixture.componentInstance.data?.items[0].id_seudonimo);
|
||||
expect(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15');
|
||||
expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull();
|
||||
});
|
||||
|
||||
@@ -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,26 +16,43 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ' · ' + indicador.titulo"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
<div [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
<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 (isConfirmacion) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!pair.length || otherFigures.length) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
@@ -50,7 +67,7 @@ import { IndicadoresService } from './indicadores.service';
|
||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||
<div class="representation-panel">
|
||||
@if (isDual) { <h3>{{ figureDisplayName(figure, indicador.figuras) }}</h3> }
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [independentPeriods]="independentPeriods" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -59,16 +76,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 +132,10 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
});
|
||||
}
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
@@ -123,6 +159,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() pinned = false;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
readonly pinChanged = output<void>();
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de la confirmación histopatológica">
|
||||
<button type="button" aria-label="Periodo anterior de la confirmación" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la confirmación" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Grados del anillo exterior">
|
||||
@for (c of m.grados; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
<ul class="rate-states">
|
||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||
</ul>
|
||||
</section>
|
||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de contingencia de citología y biopsia" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||
<tbody>@for (fila of m.filas; track fila.id) {
|
||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,37 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.confirmacion { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
.periods span { text-align: center; }
|
||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
|
||||
.rate-states:empty { display: none; }
|
||||
/* Rates on the left, donut on the right (the reverse of EU7). */
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } }
|
||||
@@ -0,0 +1,140 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-confirmacion-citologia',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-confirmacion-citologia.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection?: SeleccionConfirmacion;
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloConfirmacion;
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloConfirmacion[] = [];
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() {
|
||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
|
||||
// The most recent period first, as the prototype; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof ConfirmacionIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConfirmacionIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
this.selection = this.model ? seleccionBase(this.model) : undefined;
|
||||
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model || !this.selection) return;
|
||||
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de dona y barras EU7">
|
||||
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
|
||||
<p>{{ sinDatoNote }}</p>
|
||||
</section>
|
||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
||||
@if (m.escenarios.length && barsFigure) {
|
||||
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
|
||||
<table><caption>Datos generales, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
|
||||
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
|
||||
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
|
||||
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,33 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
.periods span { text-align: center; }
|
||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
@@ -0,0 +1,187 @@
|
||||
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>(); animated = 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);
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
||||
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
||||
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
||||
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
|
||||
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);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
|
||||
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
||||
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
||||
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
||||
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
|
||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
||||
});
|
||||
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.flush(data.general);
|
||||
r.escenarios.flush({}, { status: 500, statusText: 'Internal Server Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); http.expectNone(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
|
||||
http.expectOne(r => r.params.get('estrato') === 'estatus_seguimiento').flush(data.estatus_seguimiento); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('timeout cancela transportes y permite recuperación', async () => {
|
||||
vi.useFakeTimers(); f.detectChanges(); const r = requests();
|
||||
await vi.advanceTimersByTimeAsync(40001); f.detectChanges();
|
||||
expect(r.general.cancelled && r.escenarios.cancelled).toBe(true);
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.textContent).toContain('tardó demasiado');
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('error de red permite reintento sin figuras engañosas', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
|
||||
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.componentInstance.donutFigure).toBeUndefined();
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
|
||||
f.detectChanges(); const old = requests();
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S1'] } });
|
||||
f.detectChanges(); expect(old.general.cancelled && old.escenarios.cancelled).toBe(true);
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = ['2025-S1']; d.filas.forEach(r => r.periodo = '2025-S1'); d.totales_estrato.forEach(t => t.periodo = '2025-S1'); }
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); flush(); expect(f.componentInstance.model!.periodo).toBe('2025-S1');
|
||||
});
|
||||
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
|
||||
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
|
||||
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
|
||||
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
|
||||
});
|
||||
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
|
||||
Object.assign(data.general.filas[0], { n: 987654, suprimido: 1 });
|
||||
Object.assign(data.estatus_seguimiento.filas[0], { n: 987654, suprimido: 1 });
|
||||
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
|
||||
expect(f.nativeElement.textContent).not.toContain('987654');
|
||||
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
|
||||
});
|
||||
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
|
||||
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
|
||||
const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure;
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
|
||||
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
toggle.click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes');
|
||||
f.componentRef.setInput('metadata', {
|
||||
descripcion: 'Descripción del indicador',
|
||||
ficha: { pregunta: '¿Pregunta?', definicion: 'Definición', unidad: 'pacientes', nota: 'Nota de ficha' },
|
||||
referencias: [{ tipo: 'cita', etiqueta: 'Referencia', ref: null }],
|
||||
figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Barras por escenario.', como_leer: ['Lee las barras así.', ' '] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona así.'] },
|
||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra figura', como_leer: ['No va.'] },
|
||||
],
|
||||
}); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[];
|
||||
expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']);
|
||||
expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']);
|
||||
expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.');
|
||||
expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']);
|
||||
for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior'])
|
||||
expect(help.textContent).not.toContain(absent);
|
||||
expect(help.querySelector('details')).toBeNull();
|
||||
f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges();
|
||||
expect(help.textContent).toContain('no publica instrucciones de lectura');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(1);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['tea', 'M23_pacientes_evaluados'], ['cama', 'cama_birads_456_paciente'], ['tea', 'cacu_eu7']]) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(0);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(2);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { percentText } from './indicadores-format';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-eu7-escenario.html',
|
||||
styleUrl: './indicador-eu7-escenario.scss',
|
||||
})
|
||||
export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection: Seleccion = {};
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: Modelo;
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: Modelo[] = [];
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
|
||||
get sinDatoNote() {
|
||||
const m = this.model;
|
||||
if (!m) return '';
|
||||
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
||||
const n = m.sinDato.n;
|
||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
|
||||
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
|
||||
}
|
||||
get generalCells() {
|
||||
const m = this.model;
|
||||
return !m || m.vacio ? [] : [...m.categorias.map(c => ({ etiqueta: c.etiqueta, celda: m.celdas[c.id] })),
|
||||
{ etiqueta: m.sinDatoEtiqueta, celda: m.sinDato }];
|
||||
}
|
||||
get scenarioCells() {
|
||||
const m = this.model;
|
||||
return !m ? [] : m.escenarios.flatMap(s => [...m.categorias.map(c => ({ escenario: s.etiqueta, categoria: c.etiqueta,
|
||||
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })),
|
||||
{ escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]);
|
||||
}
|
||||
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return EU7_FIGURES.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
percentText(value: number | null) { return percentText(value); }
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
|
||||
this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras, this.indicador.filtros]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.pages = []; this.periods = []; this.model = undefined;
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
// Visibility and metadata changes must not restart Plotly rendering.
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
|
||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([general, escenarios]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modelo(general, escenarios, p));
|
||||
this.periodIndex = 0; this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof Eu7Incompatible ? error.message
|
||||
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
|
||||
&& this.applied.selection.periodos.length > 1 ? ' La respuesta corresponde al conjunto de periodos solicitado.' : '');
|
||||
this.status.set(error instanceof Eu7Incompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex]; this.selection = {};
|
||||
this.draw(); this.status.set(this.model ? this.model.vacio ? 'empty' : 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || this.status() !== 'ready') return;
|
||||
this.selection = clic(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ' · ' + dominio + ' · ' + figuraId"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||
[attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
|
||||
(click)="toggleMethodology()">
|
||||
<mat-icon aria-hidden="true">help_outline</mat-icon>
|
||||
@@ -12,10 +13,16 @@
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">{{ periodInterpretation }}</p>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
<h3 class="footnotes-title">Notas de la figura</h3>
|
||||
<section class="methodological-footnotes" aria-label="Notas de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
<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 +42,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 +92,15 @@
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
@if (state.footnotes?.length) {
|
||||
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
@if (cutoffDate; as cutoff) { <p class="figure-cutoff">Fecha de corte: {{ cutoff }}</p> }
|
||||
</div>
|
||||
<div class="figure-labels" [hidden]="state.status !== 'ready'">
|
||||
@if (state.categoryLabels?.length) {
|
||||
<details class="category-labels">
|
||||
<summary>Nombres completos de las categorías</summary>
|
||||
@@ -100,6 +111,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; }
|
||||
@@ -29,8 +44,11 @@
|
||||
.notes { padding: 1rem; overflow-wrap: anywhere; }
|
||||
.notes h2 { font-size: 1rem; }
|
||||
.notes p { line-height: 1.5; }
|
||||
.footnotes-title { margin: var(--issste-space-4) 0 var(--issste-space-2); font-size: .9375rem; font-family: var(--issste-font-heading); }
|
||||
.figure-cutoff { margin: 0; padding: .5rem 1rem .75rem; font-size: .8125rem; color: var(--issste-text-secondary); }
|
||||
.dark .figure-cutoff { color: var(--mat-sys-outline); }
|
||||
.methodological-footnotes {
|
||||
padding: .75rem 1rem 1rem;
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
@@ -49,7 +67,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();
|
||||
@@ -114,25 +145,33 @@ describe('IndicadorFigureCard', () => {
|
||||
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
|
||||
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => {
|
||||
it.each(['tea', 'cacu', 'cama'])('presenta notas %s como texto seguro dentro de «Cómo leer» y deja visible la fecha de corte', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
|
||||
const notes = ['Fuente: A & B\nSegunda línea', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
const notes = ['Nota de la ficha\nFuente: A & B · Fecha de corte: 2025-08-01\nLeyenda', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
|
||||
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
|
||||
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement;
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura');
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas de la figura');
|
||||
expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
|
||||
expect(section.querySelector('img, script, a')).toBeNull();
|
||||
expect(section.previousElementSibling?.tagName).toBe('APP-PLOTLY-CHART');
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull();
|
||||
expect(section.nextElementSibling?.classList.contains('category-labels')).toBe(true);
|
||||
const detail = section.closest('.methodology-detail') as HTMLElement;
|
||||
expect(detail).not.toBeNull(); expect(detail.hidden).toBe(true);
|
||||
expect(section.previousElementSibling?.textContent).toBe('Notas de la figura');
|
||||
// Interpretation lines come first; the notes are paragraphs, never list items.
|
||||
expect(detail.querySelector('ul')!.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(section.querySelector('li')).toBeNull();
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details, .figure-footer')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.figure-footer').textContent.trim()).toBe('Fecha de corte: 2025-08-01');
|
||||
expect(fixture.nativeElement.querySelector('.figure-labels .category-labels')).toBeTruthy();
|
||||
for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
|
||||
state({ status });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
|
||||
}
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva');
|
||||
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
|
||||
});
|
||||
it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => {
|
||||
const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} };
|
||||
@@ -253,9 +292,9 @@ describe('IndicadorFigureCard', () => {
|
||||
state({ status: 'loading' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
state({ status: 'incompatible', message: 'Granularidad no publicada' });
|
||||
state({ status: 'incompatible', message: 'Intervalo de tiempo no publicado' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Granularidad no publicada');
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Intervalo de tiempo no publicado');
|
||||
ready({ data: [{ y: [50] }], layout: {} }); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
|
||||
expect(firstHost.closest('[hidden]')).toBeNull();
|
||||
@@ -277,6 +316,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 +329,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', () => {
|
||||
@@ -424,7 +466,7 @@ describe('IndicadorFigureCard', () => {
|
||||
button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
expect(button.textContent).toContain('Cómo leer');
|
||||
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba · ' + dominio + ' · fig_c1_puntos');
|
||||
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba, ' + dominio + ', fig_c1_puntos');
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true);
|
||||
const warnings = detail.querySelector('ul')!;
|
||||
@@ -434,7 +476,7 @@ describe('IndicadorFigureCard', () => {
|
||||
if (dominio === 'tea') {
|
||||
expect(warnings.textContent).toContain('Wilson al 95 %');
|
||||
expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan');
|
||||
expect(warnings.textContent).toContain('denominadores pequeños');
|
||||
expect(warnings.textContent).toContain('tamaño de muestra pequeño');
|
||||
} else expect(warnings.textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
|
||||
expect([...warnings.querySelectorAll('li')].map(p => p.textContent))
|
||||
.toEqual(fixture.componentInstance.interpretation);
|
||||
@@ -452,7 +494,7 @@ describe('IndicadorFigureCard', () => {
|
||||
expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([
|
||||
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
|
||||
'Los límites de dibujo no representan necesariamente extremos observados.',
|
||||
'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
|
||||
'Pueden mostrarse etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
|
||||
'Los puntos suprimidos no representan tasas observadas de 0 %.',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { contractInterpretation, figureMetadataInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
@@ -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',
|
||||
@@ -142,23 +143,23 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
: this.figuraId.startsWith('fig_c2') ? 'C2'
|
||||
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
|
||||
}
|
||||
private get complementaryLineCount(): number {
|
||||
return this.contract === 'C1' ? 1
|
||||
: this.contract === 'C2' ? (this.dominio === 'tea' ? 2 : 1) : 0;
|
||||
}
|
||||
get methodologyDetail(): readonly string[] {
|
||||
return this.interpretation.slice(0, this.complementaryLineCount);
|
||||
}
|
||||
get visibleInterpretation(): readonly string[] {
|
||||
return this.interpretation.slice(this.complementaryLineCount);
|
||||
}
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
readonly figureTitle = figureTitle;
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get interpretation(): readonly string[] {
|
||||
return figureMetadataInterpretation(this.metadata, this.figuraId)
|
||||
?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
return figureInterpretation(this.metadata, this.figuraId, this.contract, this.dominio,
|
||||
this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
}
|
||||
// The figure's notes live in "Cómo leer"; the cut-off date stays under the plot
|
||||
// because it is the only temporal reference of the data on the card.
|
||||
get cutoffDate(): string | undefined {
|
||||
if (this.state.status !== 'ready') return undefined;
|
||||
for (const note of this.state.footnotes ?? []) {
|
||||
const match = /Fecha de corte: (\d{4}-\d{2}-\d{2})/.exec(note);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'tamaño de muestra pequeño', '100 % no implica certeza poblacional']],
|
||||
['C2', ['conteos por categoría', 'distribución de cada grupo y periodo', 'SIN_DATO']],
|
||||
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
|
||||
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
|
||||
@@ -182,7 +182,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(heading.id).toBe(id); expect(id).not.toBe('');
|
||||
expect(section.getAttribute('aria-labelledby')).toBe(id);
|
||||
expect(section.firstElementChild).toBe(heading);
|
||||
expect(heading.textContent).toBe('tea · i1 · Uno · f1');
|
||||
expect(heading.textContent).toBe('tea, i1, Uno, f1');
|
||||
expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false);
|
||||
const style = getComputedStyle(heading);
|
||||
expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden');
|
||||
|
||||
@@ -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">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<section class="figure-panel" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
<header class="panel-controls">
|
||||
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
|
||||
@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) {
|
||||
<span class="selection-status" [class.selection-active]="!!generalSelectionContext" tabindex="0" role="status"
|
||||
[attr.aria-label]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'"
|
||||
[matTooltip]="generalSelectionContext ?? 'Distribución completa, sin selección local de la dona.'">
|
||||
{{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }}
|
||||
</span>
|
||||
}
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
@@ -46,28 +56,47 @@ import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
@if (result().status === 'ready' && donutPages.length > 1) {
|
||||
<nav class="donut-periods" aria-label="Periodos de la dona">
|
||||
<button type="button" aria-label="Periodo anterior de la dona" [disabled]="donutPeriodIndex <= 0" (click)="changeDonutPeriod(-1)">‹</button>
|
||||
<span role="status" aria-live="polite">{{ activeDonutPeriod }} · {{ donutPeriodIndex + 1 }} / {{ donutPages.length }}</span>
|
||||
<span role="status" aria-live="polite">{{ activeDonutPeriod }}, {{ donutPeriodIndex + 1 }} de {{ donutPages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
<details><summary>Valores publicados y celdas suprimidas</summary>
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
|
||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
||||
</tbody></table></div>
|
||||
</details>
|
||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: 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; }
|
||||
@@ -98,6 +127,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() visible = true;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
@Input() localSelection: DonutSelection = {};
|
||||
@@ -136,6 +166,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 +188,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 +226,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 +251,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 +309,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 +329,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 +349,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 +362,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);
|
||||
|
||||
@@ -33,13 +33,13 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} },
|
||||
filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] };
|
||||
}
|
||||
it('consulta secuencialmente por granularidad, detiene al visible y explica supresión posterior', () => {
|
||||
it('consulta secuencialmente por intervalo de tiempo, detiene al visible y explica supresión posterior', () => {
|
||||
const latest = request(periods[0]); http.expectNone(() => true);
|
||||
expect(fixture.componentInstance.result().loading).toBe(true);
|
||||
latest.flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().value).toBe(5);
|
||||
expect(fixture.nativeElement.textContent).toContain('Último dato visible · 2025-S1');
|
||||
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1');
|
||||
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -48,7 +48,7 @@ describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
const second = request(periods[1]); http.expectNone(() => true);
|
||||
second.flush(data(periods[1], 'suppressed'));
|
||||
request(periods[2]).flush(data(periods[2]));
|
||||
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible · 2024-S2');
|
||||
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2024-S2');
|
||||
expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño');
|
||||
});
|
||||
it('agotado el inventario conserva el estado del último reporte', () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -13,11 +13,14 @@ describe('KPI integración con autoridad global', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
// KPI scope only: graphic cards stay outside the viewport, so coordinated views
|
||||
// (such as the CaCu paired times) do not add their own /datos requests.
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
function load(domain: Dominio, missing = false, periods = ['2025-S1'], initial = domain === 'tea') {
|
||||
// Ordinary consumer tests begin after initialization; dedicated P0 suites
|
||||
// exercise the real shared search for all three domains.
|
||||
@@ -27,11 +30,22 @@ describe('KPI integración con autoridad global', () => {
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
|
||||
function requests() { return http.match(r => r.url.endsWith('/datos')); }
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function requests() { return originalRequests(); }
|
||||
function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
|
||||
{ periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||
}
|
||||
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
|
||||
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||
@@ -53,12 +67,13 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||
});
|
||||
it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
for (const r of req) { expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.has('tema')).toBe(false); }
|
||||
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges();
|
||||
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']);
|
||||
expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta']);
|
||||
panels()[1].retry(); requests()[0].flush(response(1)); fixture.detectChanges();
|
||||
expect(panels()[1].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
});
|
||||
@@ -67,10 +82,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3);
|
||||
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(2);
|
||||
next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
apply(['2025-S2']); http.expectNone(() => true);
|
||||
});
|
||||
@@ -88,8 +103,8 @@ describe('KPI integración con autoridad global', () => {
|
||||
});
|
||||
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
||||
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.slice(1).map(d => d.id));
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2);
|
||||
const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1)));
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(4);
|
||||
const req = requests(); expect(req).toHaveLength(1); req.forEach((r,i) => r.flush(response(i+1)));
|
||||
});
|
||||
it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
@@ -99,18 +114,18 @@ describe('KPI integración con autoridad global', () => {
|
||||
try {
|
||||
page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i]));
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7].slice(0, count));
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7].slice(0, count));
|
||||
expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
|
||||
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
|
||||
if (count) {
|
||||
expect(grid!.children).toHaveLength(count);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count));
|
||||
expect(grid!.children).toHaveLength(count + 3);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count + 3));
|
||||
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
const added = requests(); expect(added).toHaveLength(0);
|
||||
added.forEach((r, i) => r.flush(response(count + i)));
|
||||
expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot);
|
||||
expect(panels()).toHaveLength(2); expect(state).toEqual(snapshot);
|
||||
} finally { page.kpisByDomain.cacu = definitions; }
|
||||
});
|
||||
it('retirar un ID del catálogo conserva los otros KPI y los filtros', () => {
|
||||
@@ -118,7 +133,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters);
|
||||
page.catalog.set(page.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before.slice(1)); expect(page.filters).toEqual(filters);
|
||||
expect(panels()).toHaveLength(2); http.expectNone(() => true);
|
||||
expect(panels()).toHaveLength(1); http.expectNone(() => true);
|
||||
});
|
||||
it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => {
|
||||
const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges();
|
||||
@@ -138,10 +153,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
load('cacu'); const before = panels();
|
||||
const data = response(1);
|
||||
if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1;
|
||||
if (scenario === 'nulo') data.filas[0]['valor'] = null;
|
||||
if (scenario === 'nulo') data.filas[0]['mediana'] = null;
|
||||
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
|
||||
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3);
|
||||
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(5);
|
||||
expect(panels()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables');
|
||||
expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
@@ -150,25 +165,27 @@ describe('KPI integración con autoridad global', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(3); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain);
|
||||
const req = requests(); expect(req).toHaveLength(3);
|
||||
req.forEach((r, i) => r.flush(response(i, domain)));
|
||||
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
|
||||
req.forEach((r, i) => r.flush({ ...response(i, domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'), expect.stringContaining('2 de 5'),
|
||||
expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`),
|
||||
expect.stringContaining('2025-S1'),
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
]));
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
// CaCu cards say only their own line; the kit notes are the figure footer.
|
||||
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(domain !== 'cacu');
|
||||
}
|
||||
});
|
||||
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||
@@ -193,7 +210,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
}
|
||||
load('cacu', false, ['2025-S1'], true);
|
||||
expect(fixture.componentInstance.initialPeriodBlocked).toBe(false);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]); http.expectNone(() => true);
|
||||
});
|
||||
it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1'], true);
|
||||
@@ -213,7 +230,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const latest = requests(); expect(latest).toHaveLength(3);
|
||||
const latest = requests(); expect(latest).toHaveLength(2);
|
||||
latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -19,7 +19,7 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="result().notes ?? []" />
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'cacu' ? [] : result().notes ?? []" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
@@ -40,7 +40,7 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||
get temporalReference() {
|
||||
if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod();
|
||||
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
|
||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||
}
|
||||
retry() { this.requests.next(); }
|
||||
@@ -49,6 +49,9 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
||||
this.usedPeriod.set(undefined);
|
||||
if (!applied) return of({ state: 'Esperando filtro aplicado' });
|
||||
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) {
|
||||
return of({ state: 'Selección no consolidable', info: 'Elige un único periodo aplicado para consultar esta mediana.' });
|
||||
}
|
||||
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
|
||||
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
section + section { margin-top: var(--issste-space-4); }
|
||||
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; }
|
||||
.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.ficha-fields { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 3fr); gap: var(--issste-space-2) var(--issste-space-4); max-width: 75ch; margin: 0; }
|
||||
.ficha-fields > div { display: contents; }
|
||||
dt { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
dd { margin: 0; }
|
||||
ul { padding-inline-start: 1.5rem; }
|
||||
li + li { margin-top: var(--issste-space-2); }
|
||||
.table-scroll { max-width: 100%; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; max-width: 75rem; }
|
||||
th, td { text-align: left; vertical-align: top; padding: var(--issste-space-2); border-bottom: 1px solid var(--issste-border); }
|
||||
thead th, tbody th { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
.ficha-table th { width: 10rem; }
|
||||
@media (max-width: 36rem) {
|
||||
.ficha-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); }
|
||||
dd { margin-bottom: var(--issste-space-2); }
|
||||
.ficha-table th { width: 6rem; }
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
expect(text).toContain('Guía <img src=x onerror=alert(1)>');
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(text).toContain('Segunda línea');
|
||||
expect(text).not.toContain('Ficha metodológica');
|
||||
expect(text).not.toContain('Ficha técnica');
|
||||
expect(text).not.toContain('Título del catálogo');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
@@ -32,11 +32,29 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
descripcion: 'Información general.',
|
||||
ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' },
|
||||
});
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha metodológica', 'Código', 'IND-01', 'Para', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha técnica', 'Código', 'IND-01', 'Para quién', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('presenta la ficha en una tabla y no muestra las reglas (parametros) aunque vengan', () => {
|
||||
const { fixture, http, text } = render({
|
||||
ficha: { codigo: 'EU-T', definicion: 'Días de la toma al diagnóstico.' },
|
||||
parametros: [{ clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario.' }],
|
||||
});
|
||||
const ficha = fixture.nativeElement.querySelector('table.ficha-table') as HTMLTableElement;
|
||||
expect([...ficha.querySelectorAll('th[scope=row]')].map(th => th.textContent)).toEqual(['Código', 'Definición']);
|
||||
expect(fixture.nativeElement.querySelectorAll('table')).toHaveLength(1);
|
||||
for (const absent of ['Reglas', 'cacu.horizontes', 'Provisional', 'Arbitrario']) expect(text).not.toContain(absent);
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('con solo parametros anuncia que no hay información ampliada', () => {
|
||||
const { fixture, http, text } = render({ parametros: [{ clave: 'comun.umbral_supresion', valor: 5, estado: 'provisional' }] });
|
||||
expect(text).toContain('no está disponible'); expect(text).not.toContain('comun.umbral_supresion');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra sólo los campos utilizables de una ficha parcial', () => {
|
||||
const { fixture, http, text } = render({ ficha: { codigo: 'IND-02', para: ' ', unidad: null, definicion: 'Definición breve', nota: '' } });
|
||||
expect(text).toContain('Código'); expect(text).toContain('IND-02');
|
||||
@@ -56,7 +74,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
it('muestra estado vacío con descripción y ficha ausentes o nulas', () => {
|
||||
const { fixture, http, text } = render({ descripcion: null, ficha: null, referencias: null, poblaciones: null });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Ficha metodológica'); expect(text).not.toContain('Descripción');
|
||||
expect(text).not.toContain('Ficha técnica'); expect(text).not.toContain('Descripción');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
@@ -68,7 +86,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
categorias: { NORMAL: { etiqueta: 'Normal' } },
|
||||
});
|
||||
expect(text).toContain('Descripción publicada.');
|
||||
expect(text).toContain('Guía publicada <em>edición 2</em> · Indicador 7');
|
||||
expect(text).toContain('Guía publicada <em>edición 2</em>, Indicador 7');
|
||||
expect(text).toContain('Pacientes con estudio publicado.');
|
||||
expect(fixture.nativeElement.querySelector('em')).toBeNull();
|
||||
expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/);
|
||||
|
||||
@@ -17,16 +17,20 @@ import { IndicadoresService } from './indicadores.service';
|
||||
}
|
||||
@if (fichaFields.length) {
|
||||
<section aria-labelledby="metadata-ficha-title">
|
||||
<h4 id="metadata-ficha-title">Ficha metodológica</h4>
|
||||
<dl class="ficha-fields">@for (field of fichaFields; track field.key) {
|
||||
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div>
|
||||
}</dl>
|
||||
<h4 id="metadata-ficha-title">Ficha técnica</h4>
|
||||
<div class="table-scroll">
|
||||
<table class="ficha-table">
|
||||
<tbody>@for (field of fichaFields; track field.key) {
|
||||
<tr><th scope="row">{{ field.label }}</th><td class="metadata-copy">{{ field.value }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
@if (references.length) {
|
||||
<section aria-labelledby="metadata-references-title">
|
||||
<h4 id="metadata-references-title">Referencias</h4>
|
||||
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) { · {{ ref.ref }} }</li> }</ul>
|
||||
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) {, {{ ref.ref }} }</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (populations.length) {
|
||||
@@ -47,7 +51,7 @@ export class IndicadorMetadata implements OnChanges {
|
||||
loading = false;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly fichaLabels = [
|
||||
['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'],
|
||||
['codigo', 'Código'], ['para', 'Para quién'], ['unidad', 'Unidad'],
|
||||
['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
|
||||
] as const;
|
||||
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Granularidad</mat-label>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
||||
</mat-select>
|
||||
@@ -24,7 +24,7 @@
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }} — disponibilidad no confirmada</mat-option> }
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
@@ -36,7 +36,7 @@
|
||||
@else if (availability.status === 'error') {
|
||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para esta granularidad.</p> }
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<section class="tiempos" aria-label="Días desde la toma: resultado y diagnóstico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@for (guide of readingGuide; track guide.clave) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
||||
</section>
|
||||
}
|
||||
<p class="caveat">{{ caveat }}</p>
|
||||
@if (metadataPending) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando tiempos de resultado y diagnóstico" /><p role="status">Cargando los mismos periodos para los dos tiempos…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (model; as m) {
|
||||
<h3 class="figure-title">Días desde la toma: resultado y diagnóstico</h3>
|
||||
@if (status() === 'empty') { <p role="status">No hay cajas publicadas para estos periodos.</p> }
|
||||
@else if (figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Tiempos por periodo, ' + par.etiquetas.reporte + ' y ' + par.etiquetas.diagnostico" />
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos por periodo" tabindex="0">
|
||||
<table><caption>Q1, mediana y Q3 en días por periodo</caption>
|
||||
<thead><tr><th scope="col">Periodo</th>@for (clave of claves; track clave) { <th scope="col">{{ par.etiquetas[clave] }}</th> }</tr></thead>
|
||||
<tbody>@for (periodo of m.periodos; track periodo) {
|
||||
<tr><th scope="row">{{ periodo }}</th>@for (clave of claves; track clave) { <td>{{ cajaTexto(m.cajas[clave][periodo]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,17 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.tiempos { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide, .caveat { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,131 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, combineLatest, of, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { cajaTexto, CLAVES, Clave, FIGURA_C3R, figuraTiempos, hayCajas, ModeloTiempos, modeloTiempos, ParTiempos,
|
||||
TiemposIncompatibles } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-tiempos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-tiempos-pareados.html',
|
||||
styleUrl: './indicador-tiempos-pareados.scss',
|
||||
})
|
||||
export class IndicadorTiemposPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParTiempos;
|
||||
// The card's indicator (diagnosis). Its partner (lab result) is hidden from the
|
||||
// catalog and requested directly by id, for data and metadata.
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly claves = CLAVES;
|
||||
readonly cajaTexto = cajaTexto;
|
||||
message = '';
|
||||
model?: ModeloTiempos;
|
||||
figure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
partnerMetadata?: IndicadorMetadatos;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private metadataSubscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
// TODO: mover al kit (como_leer de la vista coordinada de tiempos).
|
||||
get caveat() {
|
||||
return `Las dos cajas no cuentan exactamente a las mismas ${this.par.estudios}: cada indicador tiene su propio horizonte `
|
||||
+ 'y la segunda solo incluye las que llegaron a diagnóstico. La diferencia entre las medianas no es el tiempo del tramo intermedio.';
|
||||
}
|
||||
/** "Cómo leer": only what the kit publishes for each C3r figure, plus the caveat above. */
|
||||
get readingGuide() {
|
||||
const fuentes: Record<Clave, IndicadorMetadatos | undefined> = { reporte: this.partnerMetadata, diagnostico: this.metadata };
|
||||
return CLAVES.flatMap(clave => {
|
||||
const detail = fuentes[clave]?.figuras_detalle?.find(item => item.figura === FIGURA_C3R);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ clave, nombre: this.par.etiquetas[clave], descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
get metadataPending() { return !this.metadata || !this.partnerMetadata; }
|
||||
toggleHelp() {
|
||||
this.helpOpen = !this.helpOpen;
|
||||
if (!this.helpOpen) return;
|
||||
if (!this.metadata) this.metadataRequested.emit();
|
||||
if (!this.partnerMetadata) {
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.service.metadatos(this.dominio, this.par.reporte).pipe(catchError(() => of(undefined)))
|
||||
.subscribe(value => { this.partnerMetadata = value; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
|
||||
this.par.reporte, this.par.diagnostico, this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||
if (changes['dominio'] || changes['par']) { this.partnerMetadata = undefined; this.metadataSubscription?.unsubscribe(); }
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.model = undefined; this.figure = undefined;
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.figure = undefined;
|
||||
if (this.indicador.id !== this.par.diagnostico || this.indicador.contrato !== 'C3r') {
|
||||
this.message = 'El catálogo no publica el indicador de tiempo necesario para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
// The partner shares the diagnosis periodicity; its response is validated by id, contract and period.
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (!compatibility.compatible) { this.message = compatibility.reason; this.status.set('incompatible'); return; }
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.par.reporte, this.applied.tipo, periods),
|
||||
this.snapshots.datos(this.dominio, this.par.diagnostico, this.applied.tipo, periods, this.indicador.version),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([reporte, diagnostico]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.model = modeloTiempos(this.par, { reporte, diagnostico }, this.applied.tipo, periods);
|
||||
this.draw();
|
||||
this.status.set(hayCajas(this.model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.figure = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof TiemposIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof TiemposIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.figure = figuraTiempos(this.model, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { numericRows } from './indicadores-numeric-rows';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
@@ -26,7 +25,7 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
const donut = supported(data), bars = supported(data, { ...selection, figura: 'fig_c2_barras' });
|
||||
expect(donut.figure.data).toHaveLength(1); expect(donut.hierarchy).toBeUndefined();
|
||||
expect(bars.figure.data[0]['x']).toEqual(donut.figure.data[0]['values']); expect(bars.figure.data[0]['y']).toEqual(donut.figure.data[0]['labels']);
|
||||
expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo · paciente' } });
|
||||
expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo (paciente)' } });
|
||||
});
|
||||
it('el layout final de barras muestra ambos ejes y el hover no repite el periodo', () => {
|
||||
const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' });
|
||||
@@ -109,7 +108,6 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
const data = c2Fixture(); data.filas.forEach(r => r['denominador'] = 10); data['denominador'] = 10;
|
||||
const result = supported(data); expect(result.figure.layout['meta']).toMatchObject({ denominator: 10 });
|
||||
expect(result.figure.data[0]['hovertemplate']).toContain('10 paciente publicados');
|
||||
expect(numericRows(data).map(r => r.value)).toEqual(result.model.categories.map(c => String(c.value)));
|
||||
});
|
||||
it('explorar, cambiar padre y restaurar parte del original y no modifica las barras', () => {
|
||||
const data = c2Fixture(), result = supported(data), original = structuredClone(result.figure);
|
||||
|
||||
@@ -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[] {
|
||||
@@ -83,7 +83,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||
const colors = categories.map((c, i) => c2Color(c.color, i));
|
||||
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ' · ' + period }, autosize: true,
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
margin: { l: 76, r: 28, t: 112, b: 62, pad: 4 },
|
||||
legend: selection.figura === 'fig_c2_donas'
|
||||
@@ -95,7 +95,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
|
||||
marker: { color: colors, line: { color: theme.outline, width: 0.7 } },
|
||||
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
||||
layout['xaxis'] = { title: { text: 'Conteo · ' + model.unit }, rangemode: 'tozero', showgrid: true,
|
||||
layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
|
||||
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
|
||||
ticks: 'outside', tickcolor: '#AEB7C2', automargin: true };
|
||||
layout['yaxis'] = { type: 'category', categoryorder: 'array', categoryarray: [...labels].reverse(), automargin: true,
|
||||
|
||||
@@ -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: 'c2_grados_biopsia_sintetico', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
{ id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
{ 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,190 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { ActivatedRoute, provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureApplied } from './indicadores-figure-selection';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
|
||||
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
||||
});
|
||||
const catalog = [
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
||||
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'),
|
||||
item('ind1', 'Pacientes con citología anómala'),
|
||||
item('ordinary', 'Otra gráfica'),
|
||||
item('cacu_eu7', 'Distribución de resultados citológicos', 'C2'),
|
||||
];
|
||||
const periods = ['2025-S1', '2025-S2'];
|
||||
const multi: PlotlyFigure = { data: [{ type: 'scatter', x: periods, y: [null, 25],
|
||||
customdata: [[null, 0, 1], [1, 4, 0]], text: ['Suprimido', '1 de 4'], mode: 'markers' }], layout: {} };
|
||||
|
||||
describe('CaCu: oportunidad y selección independiente de todos los reportes', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]),
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } },
|
||||
provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/cacu/indicadores').flush(structuredClone(catalog));
|
||||
// Real inventory and KPI consumers: only the two published KPI request data.
|
||||
for (;;) {
|
||||
const requests = http.match(r => r.url.endsWith('/periodos'));
|
||||
if (!requests.length) break;
|
||||
for (const r of requests) r.flush({ id: r.request.url.split('/')[3],
|
||||
periodos: periods.map(periodo => ({ periodo, tipo: 'semestre' })) });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
expect(requests.map(r => r.request.url)).toEqual([
|
||||
'/cacu/indicadores/cacu_eu7/datos', '/cacu/indicadores/cacu_dias_toma_diagnostico/datos',
|
||||
]);
|
||||
for (const r of requests) {
|
||||
const id = r.request.url.split('/')[3], contrato = id === 'cacu_eu7' ? 'C2' : 'C3r';
|
||||
r.flush({ id, contrato, tipo_periodo: 'semestre', periodos: ['2025-S2'], categorias: { A: {} },
|
||||
filas: [{ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 5, suprimido: 0,
|
||||
mediana: 7, q1: 3, q3: 9, unidad: 'dias' }] });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
|
||||
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
|
||||
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
|
||||
function open(...ids: string[]) { ids.forEach(id => card(id).setVisible(true)); fixture.detectChanges(); }
|
||||
function figure(id: string) { return http.expectOne('/cacu/indicadores/' + id + '/figuras/fig_c1_puntos?tema=claro'); }
|
||||
function apply(tipo: 'mes' | 'semestre', selected: [string, ...string[]]) {
|
||||
page.filters!.tipo = tipo;
|
||||
page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('encabezados, cinco tarjetas en orden y placeholders inertes sin periodo, unidad ni HTTP', () => {
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
for (const kpi of kpis.slice(3)) {
|
||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
}
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('detección histopatológica');
|
||||
expect(card('cacu_eu13')).toBeDefined();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
|
||||
const original = page.catalog(), before = cards();
|
||||
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
||||
expect(before[0].indicador.id).toBe('cacu_eu7');
|
||||
page.togglePinned(original[0]); fixture.detectChanges();
|
||||
expect(cards()[0]).toBe(card('cacu_eu13'));
|
||||
page.changeSearchQuery('anómala'); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('ind1');
|
||||
page.changeSearchQuery(''); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('cacu_eu13');
|
||||
for (const c of before) expect(card(c.indicador.id)).toBe(c);
|
||||
expect(page.catalog()).toBe(original);
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('inicializa las dos figuras en Todos con reporte aunque el filtro general ya sea mensual; conserva carga diferida', () => {
|
||||
apply('mes', ['2026-01']);
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url));
|
||||
open('cacu_eu13', 'ind1');
|
||||
for (const id of ['cacu_eu13', 'ind1']) {
|
||||
const r = figure(id); expect(r.request.params.has('periodos')).toBe(false);
|
||||
expect(panel(id).applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
r.flush(multi);
|
||||
}
|
||||
expect(panel('cacu_eu13').applied).not.toBe(panel('ind1').applied);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Selección independiente: Todos con reporte (semestres)');
|
||||
});
|
||||
it('Aplicar no altera selección, datos, representación, host ni GET de las independientes; las ordinarias sí cambian', () => {
|
||||
open('cacu_eu13', 'ind1', 'ordinary');
|
||||
for (const id of ['cacu_eu13', 'ind1', 'ordinary']) figure(id).flush(multi);
|
||||
fixture.detectChanges();
|
||||
const retained = ['cacu_eu13', 'ind1'].map(id => ({ id, card: card(id), panel: panel(id),
|
||||
applied: panel(id).applied, result: panel(id).result() }));
|
||||
const hosts = Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'));
|
||||
card('cacu_eu13').localSelection = { parent: 'own' };
|
||||
card('ind1').localSelection = { parent: 'different' };
|
||||
for (const [tipo, selected] of [['semestre', ['2025-S1']], ['mes', ['2026-01']]] as const) {
|
||||
apply(tipo, [...selected]);
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url));
|
||||
const r = http.expectOne(r => r.url.includes('/ordinary/figuras/'));
|
||||
expect(r.request.params.get('periodos')).toBe(selected[0]); r.flush(multi);
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3],
|
||||
contrato: 'C2', tipo_periodo: tipo, periodos: [], filas: [] }));
|
||||
for (const old of retained) {
|
||||
expect(card(old.id)).toBe(old.card); expect(panel(old.id)).toBe(old.panel);
|
||||
expect(panel(old.id).applied).toBe(old.applied); expect(panel(old.id).result()).toBe(old.result);
|
||||
expect(panel(old.id).result().figure).toEqual(multi);
|
||||
}
|
||||
}
|
||||
expect(card('cacu_eu13').localSelection).toEqual({ parent: 'own' });
|
||||
expect(card('ind1').localSelection).toEqual({ parent: 'different' });
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'))).toEqual(hosts);
|
||||
expect(panel('ind1').result().figure!.data[0]['x']).toEqual(periods);
|
||||
expect(panel('ind1').result().figure!.data[0]['y']).toEqual([null, 25]);
|
||||
});
|
||||
it('resumen abierto reutiliza snapshots propios y no consulta los periodos del filtro general', () => {
|
||||
open('cacu_eu13', 'ind1');
|
||||
figure('cacu_eu13').flush(multi); figure('ind1').flush(multi);
|
||||
TestBed.inject(IndicadoresSnapshots).expanded.set(true); fixture.detectChanges();
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
expect(requests).toHaveLength(2);
|
||||
for (const r of requests) {
|
||||
expect(r.request.params.has('periodos')).toBe(false);
|
||||
r.flush({ id: r.request.url.split('/')[3], contrato: 'C1', tipo_periodo: 'semestre', periodos: periods,
|
||||
filas: [{ periodo: periods[0], grupo: 'principal', estrato: null, valor: 25, numerador: 1, denominador: 4, suprimido: 0 },
|
||||
{ periodo: periods[1], grupo: 'principal', estrato: null, valor: 50, numerador: 5, denominador: 10, suprimido: 0 }] });
|
||||
}
|
||||
apply('mes', ['2026-01']);
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/datos/.test(r.url));
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
|
||||
});
|
||||
it('reintento individual tras error usa Todos; una nueva versión de catálogo puede revalidar sin tocar otra selección', () => {
|
||||
open('cacu_eu13', 'ind1');
|
||||
figure('cacu_eu13').flush({}, { status: 503, statusText: 'Unavailable' }); figure('ind1').flush(multi);
|
||||
const other = panel('ind1').result();
|
||||
panel('cacu_eu13').requestFigure();
|
||||
const retry = figure('cacu_eu13'); expect(retry.request.params.has('periodos')).toBe(false); retry.flush({ data: [], layout: {} });
|
||||
expect(panel('ind1').result()).toBe(other);
|
||||
page.catalog.update(items => items.map(i => i.id === 'cacu_eu13' ? { ...i, version: '2' } : i)); fixture.detectChanges();
|
||||
const revalidated = figure('cacu_eu13'); expect(revalidated.request.params.has('periodos')).toBe(false); revalidated.flush(multi);
|
||||
expect(panel('ind1').result()).toBe(other);
|
||||
});
|
||||
it('la política por ID solo afecta CaCu y ninguna otra gráfica', () => {
|
||||
const general = page.filters!.applied;
|
||||
for (const domain of ['tea', 'cama'] as const) for (const id of ['cacu_eu13', 'ind1', 'cacu_eu7']) {
|
||||
expect(figureApplied(domain, id, general)).toBe(general);
|
||||
}
|
||||
expect(figureApplied('cacu', 'cacu_eu7', general)).toBe(general);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
import { Component, input, output } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
|
||||
|
||||
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
||||
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
||||
// valores_estrato as texts. Counts per cytology: NORMAL, LIEBG, LIEAG, CIS, CARCINOMA,
|
||||
// SIN_BIOPSIA (no biopsy yet), SIN_DATO (biopsy without grade), CIN2.
|
||||
const CATEGORIAS = [...GRADOS, 'SIN_BIOPSIA', 'SIN_DATO', 'CIN2'];
|
||||
const CONTEOS: Record<string, number[]> = {
|
||||
'ASC-H': [16, 11, 9, 1, 1, 20, 2, 0], LIEAG: [6, 10, 31, 8, 2, 22, 2, 1], CIS: [0, 1, 4, 4, 3, 11, 2, 0],
|
||||
};
|
||||
function respuesta(periodos = ['2026-S2'], conteos = CONTEOS): IndicadorDatos {
|
||||
const filas = periodos.flatMap(periodo => Object.entries(conteos).flatMap(([estrato, ns]) =>
|
||||
CATEGORIAS.map((categoria, orden) => ({ periodo, grupo: 'TOTAL', estrato, categoria, n: ns[orden], orden, suprimido: 0 }))));
|
||||
const color = ['#9DBFE3', '#E8C28E', '#D98E4A', '#B55A1F', '#7A2E0E'];
|
||||
const estratos = Object.keys(conteos);
|
||||
return {
|
||||
id: 'cacu_confirmacion_citologia', contrato: 'C2', tipo_periodo: 'semestre', periodos, filas, version: '1',
|
||||
estrato: 'citologia_alto_grado', valores_estrato: estratos,
|
||||
etiquetas_estrato: Object.fromEntries(estratos.map(e => [e, e === 'CIS' ? 'Carcinoma in situ' : e])),
|
||||
totales_estrato: periodos.flatMap(periodo => estratos.map(estrato => ({ periodo, grupo: 'TOTAL', estrato,
|
||||
n: conteos[estrato].reduce((a, b) => a + b, 0), suprimido: 0 }))),
|
||||
categorias: {
|
||||
...Object.fromEntries(GRADOS.map((id, i) => [id, { etiqueta: id === 'CIS' ? 'Carcinoma in situ' : id, color: color[i],
|
||||
grupo: i < 2 ? 'NO_ANORMAL' : 'ANORMAL', gravedad: i + 1 }])),
|
||||
SIN_BIOPSIA: { etiqueta: 'Sin biopsia aún', color: '#C9CDD2', grupo: null, gravedad: null },
|
||||
SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: 'SIN_DATO', gravedad: null },
|
||||
CIN2: { etiqueta: 'CIN2', color: null, grupo: 'NO_ANORMAL', gravedad: null },
|
||||
},
|
||||
grupos_de_categoria: { NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Sin dato' },
|
||||
};
|
||||
}
|
||||
|
||||
describe('Confirmación histopatológica: modelo', () => {
|
||||
it('denominador: mujeres con biopsia y grado; SIN_BIOPSIA y SIN_DATO van aparte; CIN2 cuenta en su grupo', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
expect(m.filas.map(f => f.id)).toEqual(['CIS', 'LIEAG', 'ASC-H']);
|
||||
expect(m.filas.map(f => f.etiqueta)).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
|
||||
expect(m.filas.map(f => f.den)).toEqual([12, 58, 38]);
|
||||
expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]);
|
||||
expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n])).toEqual([[11, 2], [22, 2], [20, 2]]);
|
||||
expect(m.grados.map(g => g.id)).toEqual([...GRADOS, 'CIN2']);
|
||||
expect(m.grados.find(g => g.id === 'CIN2')).toMatchObject({ grupo: 'NO_ANORMAL', color: '#8A9199' });
|
||||
expect(m.grupos.find(g => g.id === 'NO_ANORMAL')!.grados).toEqual(['NORMAL', 'LIEBG', 'CIN2']);
|
||||
expect(m.conBiopsia).toBe(108); expect(m.base).toBe('ANORMAL');
|
||||
});
|
||||
it('estratos ausentes de valores_estrato dicen «Sin mujeres con biopsia»; total suprimido suprime la fila', () => {
|
||||
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
|
||||
const m = modeloConfirmacion(d, '2026-S2');
|
||||
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
|
||||
expect(tasas(m, seleccionBase(m)).map(estadoTasa)).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
|
||||
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
|
||||
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
|
||||
const s = modeloConfirmacion(d, '2026-S2');
|
||||
expect([s.filas[1].den, s.filas[1].estado]).toEqual([null, 'Suprimido']);
|
||||
expect(s.conBiopsia).toBeNull();
|
||||
expect((figuraTasas(s, seleccionBase(s), 'claro').layout['annotations'] as { text: string }[])[1].text).toBe('Suprimido');
|
||||
});
|
||||
it('Wilson al 95 % con la fórmula del kit y extremos 0 y n', () => {
|
||||
const [bajo, alto] = wilson(11, 12);
|
||||
expect(bajo).toBeCloseTo(64.61, 1); expect(alto).toBeCloseTo(98.51, 1);
|
||||
expect(wilson(0, 10)[0]).toBe(0); expect(wilson(10, 10)[1]).toBe(100);
|
||||
});
|
||||
it('vista base LIEAG o más; grupo, grado, segundo clic al grupo y centro a la base', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
const base = seleccionBase(m);
|
||||
expect(tasas(m, base).map(t => [t.k, t.fila.den])).toEqual([[11, 12], [41, 58], [11, 38]]);
|
||||
expect(lectura(m, base)).toBe('Verdaderos positivos (valor predictivo positivo)');
|
||||
const menor = clicConfirmacion(m, base, 'grupos', m.grupos.findIndex(g => g.id === 'NO_ANORMAL'));
|
||||
expect(menor).toEqual({ grupo: 'NO_ANORMAL' }); expect(lectura(m, menor)).toBe('Sin confirmación de alto grado');
|
||||
const normal = clicConfirmacion(m, menor, 'categorias', 0);
|
||||
expect(normal).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(lectura(m, normal)).toBe('Falsos positivos: la biopsia no confirmó lesión');
|
||||
expect(tasas(m, normal).map(t => t.k)).toEqual([0, 6, 16]);
|
||||
expect(clicConfirmacion(m, normal, 'categorias', 0)).toEqual({ grupo: 'NO_ANORMAL' });
|
||||
const cis = clicConfirmacion(m, normal, 'categorias', 3);
|
||||
expect(lectura(m, cis)).toBe('Proporción con biopsia Carcinoma in situ');
|
||||
expect(clicConfirmacion(m, cis, 'centro', 0)).toEqual(base);
|
||||
});
|
||||
it('figura de tasas: una traza siempre, etiquetas «xx.x %» y «k/n», eje acotado a múltiplos de 5', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
|
||||
const f = figuraTasas(m, base, 'claro');
|
||||
expect(f.data).toHaveLength(1); expect(f.data[0]['type']).toBe('scatter');
|
||||
expect(f.data[0]['y']).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray).toEqual(['ASC-H', 'LIEAG', 'Carcinoma in situ']);
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text))
|
||||
.toEqual(['<b>91.7 %</b><br>11/12', '<b>70.7 %</b><br>41/58', '<b>28.9 %</b><br>11/38']);
|
||||
const range = (f.layout['xaxis'] as { range: number[] }).range;
|
||||
expect(range).toEqual(rangoTasas(tasas(m, base)));
|
||||
expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); expect(range[0]).toBeGreaterThanOrEqual(0); expect(range[1]).toBeLessThanOrEqual(100);
|
||||
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Verdaderos positivos (valor predictivo positivo)');
|
||||
const otra = figuraTasas(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'oscuro');
|
||||
expect(otra.data).toHaveLength(1); expect(otra.layout['paper_bgcolor']).toBe('#081839');
|
||||
});
|
||||
it('fila suprimida o nula dice Suprimido o No disponible, nunca 0, y la dona no suma un total parcial', () => {
|
||||
const d = respuesta();
|
||||
Object.assign(d.filas.find(f => f['estrato'] === 'CIS' && f['categoria'] === 'LIEAG')!, { n: null, suprimido: 1 });
|
||||
d.filas = d.filas.filter(f => !(f['estrato'] === 'ASC-H' && f['categoria'] === 'NORMAL'));
|
||||
const m = modeloConfirmacion(d, '2026-S2'), base = seleccionBase(m);
|
||||
expect(m.filas.map(f => [f.den, f.estado])).toEqual([[null, 'Suprimido'], [58, 'Publicado'], [null, 'No disponible']]);
|
||||
const f = figuraTasas(m, base, 'claro');
|
||||
expect(f.data[0]['x']).toEqual([null, 100 * 41 / 58, null]);
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(['Suprimido', '<b>70.7 %</b><br>41/58', 'No disponible']);
|
||||
expect(JSON.stringify(f.layout['annotations'])).not.toContain('0/');
|
||||
expect(m.conBiopsia).toBeNull(); expect(donaConfirmacion(m, base, 'claro').data).toHaveLength(0);
|
||||
});
|
||||
it('dona de dos anillos; la selección atenúa sin cambiar valores y el centro dice «k de N con biopsia»', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
|
||||
const d = donaConfirmacion(m, base, 'claro');
|
||||
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||
expect(d.data[1]['values']).toEqual([45, 63]);
|
||||
expect(d.data[2]['values']).toEqual([22, 22, 44, 13, 6, 1]);
|
||||
expect(d.data[0]['text']).toEqual(['<b>63</b><br>de 108 con biopsia']);
|
||||
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
|
||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
|
||||
});
|
||||
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), estrato: 'estatus_seguimiento' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
expect(() => periodosConfirmacion(respuesta(), 'semestre', ['2026-S1'])).toThrow(ConfirmacionIncompatible);
|
||||
const dup = respuesta(); dup.filas.push({ ...dup.filas[0] });
|
||||
expect(() => modeloConfirmacion(dup, '2026-S2')).toThrow(ConfirmacionIncompatible);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Confirmación histopatológica: componente', () => {
|
||||
const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorConfirmacionCitologia>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorConfirmacionCitologia);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
function flush(body: unknown = respuesta(['2026-S1', '2026-S2'])) {
|
||||
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_confirmacion_citologia/datos');
|
||||
expect(r.request.params.get('estrato')).toBe('citologia_alto_grado');
|
||||
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
|
||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||
}
|
||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
||||
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
||||
normal.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(normal.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
|
||||
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].slice(-3).map(td => td.textContent))).toEqual([['12', '11', '2'], ['58', '22', '2'], ['38', '20', '2']]);
|
||||
f.componentInstance.changePeriod(-1); f.detectChanges();
|
||||
expect(f.componentInstance.model!.periodo).toBe('2026-S1'); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
||||
});
|
||||
it('error se anuncia y el reintento recupera; respuesta incompatible no dibuja', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url.endsWith('/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); flush({ ...respuesta(['2026-S1', '2026-S2']), estrato: 'otro' });
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('filtro general incompatible no pide datos', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('pendientes');
|
||||
f.componentRef.setInput('metadata', { descripcion: 'No va', ficha: { nota: 'Tampoco' }, figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
|
||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']);
|
||||
for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
|
||||
});
|
||||
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(1);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['cama', 'cacu_confirmacion_citologia']] as const) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(0);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||
// a C2 stratified by the last valid cytology of the period; the category is the grade
|
||||
// of the biopsy it originated. Unknown or suppressed cells never become zero.
|
||||
export const ID_CONFIRMACION = 'cacu_confirmacion_citologia';
|
||||
export const ESTRATO_CITOLOGIA = 'citologia_alto_grado';
|
||||
// Outside the denominator and the donut, reported apart in the table:
|
||||
// SIN_BIOPSIA = no biopsy reported at the cut-off; SIN_DATO = biopsy reported without a grade.
|
||||
export const APARTE = [
|
||||
{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' },
|
||||
{ id: 'SIN_DATO', etiqueta: 'Biopsia sin grado' },
|
||||
] as const;
|
||||
const APARTE_IDS: readonly string[] = APARTE.map(a => a.id);
|
||||
// Grades outside the published catalog (CIN2, DESCONOCIDO…) arrive without a colour.
|
||||
const COLOR_RESPALDO = '#8A9199';
|
||||
// Fixed vertical axis, most severe cytology on top.
|
||||
export const FILAS_CITOLOGIA = [
|
||||
{ id: 'CIS', etiqueta: 'Carcinoma in situ' },
|
||||
{ id: 'LIEAG', etiqueta: 'LIEAG' },
|
||||
{ id: 'ASC-H', etiqueta: 'ASC-H' },
|
||||
] as const;
|
||||
export const Z95 = 1.959963984540054;
|
||||
|
||||
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
|
||||
export interface FilaCitologia {
|
||||
id: string; etiqueta: string; celdas: Record<string, Celda>;
|
||||
// SIN_BIOPSIA and SIN_DATO cells, when the response publishes those categories.
|
||||
aparte: Record<string, Celda>;
|
||||
// Women of the row with a biopsy: the denominator. Null when any of its cells is unknown.
|
||||
den: number | null; estado: Celda['estado'];
|
||||
}
|
||||
export interface ModeloConfirmacion {
|
||||
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
|
||||
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||||
}
|
||||
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
|
||||
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||
export class ConfirmacionIncompatible extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0;
|
||||
const fail = (message: string): never => { throw new ConfirmacionIncompatible(message); };
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||||
|
||||
/** Wilson score interval at 95 %, in percent; same formula as the kit (oro/calculo.py:wilson). */
|
||||
export function wilson(k: number, n: number): [number, number] {
|
||||
const p = k / n, z2 = Z95 * Z95, base = 1 + z2 / n;
|
||||
const centro = (p + z2 / (2 * n)) / base;
|
||||
const mitad = Z95 * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / base;
|
||||
return [100 * Math.max(0, Math.min(p, centro - mitad)), 100 * Math.min(1, Math.max(p, centro + mitad))];
|
||||
}
|
||||
|
||||
function celda(fila?: Record<string, unknown>): Celda {
|
||||
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
|
||||
return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0
|
||||
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
|
||||
}
|
||||
function suma(celdas: Celda[]): number | null {
|
||||
return celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0);
|
||||
}
|
||||
function estado(celdas: Celda[]): Celda['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
/** Validated periods of one stratified response, in request order or sorted. */
|
||||
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||
if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA
|
||||
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|
||||
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||||
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|
||||
|| datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) {
|
||||
return fail('Los datos no corresponden a la confirmación histopatológica o al periodo aplicado.');
|
||||
}
|
||||
return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort();
|
||||
}
|
||||
|
||||
/** One /datos payload -> the contingency table of a single period. */
|
||||
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): ModeloConfirmacion {
|
||||
periodosConfirmacion(datos, datos.tipo_periodo);
|
||||
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
|
||||
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
|
||||
const c = cats[a.id];
|
||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||
});
|
||||
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
});
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades share the group but not its colour.
|
||||
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.');
|
||||
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
|
||||
const index = new Map<string, Record<string, unknown>>();
|
||||
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
||||
const c = row['categoria'], e = row['estrato'];
|
||||
if (!esTotal(row['grupo']) || typeof e !== 'string' || typeof c !== 'string'
|
||||
|| (!grados.some(g => g.id === c) && !aparte.some(a => a.id === c)) || ![0, 1].includes(row['suprimido'] as number)) {
|
||||
return fail('Fila de confirmación inválida.');
|
||||
}
|
||||
const key = JSON.stringify([e, c]);
|
||||
if (index.has(key)) return fail('Filas de confirmación duplicadas.');
|
||||
index.set(key, row);
|
||||
}
|
||||
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
|
||||
const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined;
|
||||
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos de citología inválidos.');
|
||||
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
||||
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
||||
if (!totales.every(registro)) fail('Totales de citología inválidos.');
|
||||
const filas = FILAS_CITOLOGIA.map(({ id, etiqueta }) => {
|
||||
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
|
||||
const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
|
||||
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
|
||||
const cero = (): Celda => ({ n: 0, estado: 'Publicado' });
|
||||
const celdas = Object.fromEntries(grados.map(g => [g.id, ausente ? cero() : celda(index.get(JSON.stringify([id, g.id])))]));
|
||||
const otras = Object.fromEntries(aparte.map(a => [a.id, ausente ? cero() : celda(index.get(JSON.stringify([id, a.id])))]));
|
||||
// A suppressed published total suppresses the row, whatever its cells say.
|
||||
const suprimida = (totales as Record<string, unknown>[]).some(t => t['periodo'] === periodo && t['estrato'] === id && t['suprimido'] === 1);
|
||||
const valores = Object.values(celdas);
|
||||
return { id, etiqueta: rotulo, celdas, aparte: otras,
|
||||
den: suprimida ? null : suma(valores), estado: suprimida ? 'Suprimido' as const : estado(valores) };
|
||||
});
|
||||
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
|
||||
return { periodo, grados, grupos, base, filas, totales: porGrado,
|
||||
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
|
||||
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])] };
|
||||
}
|
||||
|
||||
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
|
||||
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.grados ?? [];
|
||||
}
|
||||
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
|
||||
}
|
||||
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
||||
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||
if (traza === 'centro') return seleccionBase(m);
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.grados[indice];
|
||||
if (!c) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
/** The axis title says what the rate reads. */
|
||||
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
if (!sel.categoria && sel.grupo === m.base) return 'Verdaderos positivos (valor predictivo positivo)';
|
||||
if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión';
|
||||
if (!sel.categoria) return 'Sin confirmación de alto grado';
|
||||
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
|
||||
}
|
||||
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
|
||||
export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[] {
|
||||
const cats = seleccionados(m, sel);
|
||||
return m.filas.map(fila => {
|
||||
if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null };
|
||||
const k = cats.reduce((s, c) => s + fila.celdas[c].n!, 0);
|
||||
const [bajo, alto] = wilson(k, fila.den);
|
||||
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
||||
});
|
||||
}
|
||||
export function estadoTasa(t: Tasa): string {
|
||||
return t.fila.den === 0 ? 'Sin mujeres con biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||||
}
|
||||
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
||||
export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
const visibles = valores.filter(t => t.bajo !== null && t.alto !== null);
|
||||
if (!visibles.length) return [0, 100];
|
||||
const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!));
|
||||
return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)];
|
||||
}
|
||||
|
||||
/** Rates on the left: one point and horizontal Wilson interval per cytology, one trace always. */
|
||||
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
}], layout: {
|
||||
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { l: 130, r: 96, t: 16, b: 64 },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true },
|
||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
|
||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||
font: { size: 12, color: p.text },
|
||||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Donut on the right: groups inside, grades outside; selection dims, values stay. */
|
||||
export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), activos = new Set(seleccionados(m, sel)), total = m.conBiopsia;
|
||||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<h2>Datos y definiciones · {{ domainNames[dominio] }}</h2>
|
||||
<h2>Datos y definiciones de {{ domainNames[dominio] }}</h2>
|
||||
<section aria-labelledby="domain-info-title">
|
||||
<h3 id="domain-info-title">Información del dominio</h3>
|
||||
<p>Dominio: {{ domainNames[dominio] }}.</p>
|
||||
@if (dominio === 'cacu') { <p>Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo espécimen fue insatisfactorio.</p> }
|
||||
@if (!loading && !error && periodTypes.length) {
|
||||
<p>Periodicidad disponible:
|
||||
@for (tipo of periodTypes; track tipo; let last = $last) { {{ periodNames[tipo] }}{{ last ? '.' : ', ' }} }
|
||||
@@ -29,10 +29,6 @@
|
||||
@if (item.tipos_periodo.length) {
|
||||
<ul>@for (tipo of item.tipos_periodo; track tipo) { <li>{{ periodNames[tipo] }}</li> }</ul>
|
||||
} @else { <p>Pendiente de información.</p> }
|
||||
<h4>Cómo interpretar este indicador</h4>
|
||||
@if (interpretation(item).length) {
|
||||
<ul>@for (line of interpretation(item); track $index) { <li>{{ line }}</li> }</ul>
|
||||
}
|
||||
@if (opened.has(dominio + ':' + item.id)) {
|
||||
<app-indicador-metadata [dominio]="dominio" [indicador]="item.id" />
|
||||
} @else {
|
||||
@@ -43,14 +39,3 @@
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="definitions-methodology-title">
|
||||
<h3 id="definitions-methodology-title">Interpretación y metodología</h3>
|
||||
<p>Ten en cuenta estas limitaciones al consultar las gráficas.</p>
|
||||
<ul>
|
||||
<li>Un valor nulo significa que no hay un valor disponible; un cero es un valor observado. Los datos suprimidos tampoco representan un cero.</li>
|
||||
<li>{{ periodInterpretation }}</li>
|
||||
<li>Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.</li>
|
||||
<li>Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por denominadores pequeños.</li>
|
||||
</ul>
|
||||
<p>Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. Las notas de cada gráfica incluyen detalles adicionales para interpretar los datos mostrados.</p>
|
||||
</section>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Component, Input, output } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { Dominio, Indicador, TipoPeriodo } from './indicadores.models';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { IndicadorMetadata } from './indicador-metadata';
|
||||
|
||||
@Component({
|
||||
@@ -19,20 +19,9 @@ export class IndicadoresDefinitions {
|
||||
@Input() loading = false;
|
||||
@Input() error = '';
|
||||
readonly retry = output<void>();
|
||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
|
||||
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; }
|
||||
interpretation(item: Indicador) {
|
||||
if (!item.contrato) return [];
|
||||
const lines = contractInterpretation(item.contrato, this.dominio);
|
||||
// Catalog metadata does not describe the traces. Keep the shared C2 guidance
|
||||
// independent of bars/sectors; the actual figure retains its full explanation.
|
||||
return lines.filter(line =>
|
||||
!line.includes('Los valores nulos o suprimidos') &&
|
||||
!line.includes('Los puntos suprimidos') &&
|
||||
!line.includes('No hay una explicación específica disponible'),
|
||||
).slice(item.contrato === 'C2' ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ describe('navegación multiperiodo en el panel común', () => {
|
||||
expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false);
|
||||
for (let i = 0; i < periods.length; i++) {
|
||||
expect(panel().activeDonutPeriod).toBe(periods[i]);
|
||||
expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} / 3`);
|
||||
expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} de 3`);
|
||||
expect(card().chartFigure?.data).toHaveLength(1);
|
||||
expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true);
|
||||
if (i < 2) { buttons()[1].click(); fixture.detectChanges(); }
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
function eu7Datos() {
|
||||
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
|
||||
}
|
||||
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));
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(m.escenarios.map(s => `${s.den}`));
|
||||
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
|
||||
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
|
||||
.toEqual(['5.0', '24.3', '21.7', '7.8']);
|
||||
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
// Same traces in every selection (animation identity); unselected ones are zero-width.
|
||||
expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
|
||||
const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
|
||||
expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
|
||||
expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
|
||||
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
|
||||
.toEqual(m.escenarios.map(s => `<b>${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} %</b> (${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.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
|
||||
expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
|
||||
expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
|
||||
t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
|
||||
expect(JSON.stringify(f)).not.toContain('123456');
|
||||
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
||||
});
|
||||
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, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
||||
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
|
||||
});
|
||||
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
||||
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();
|
||||
});
|
||||
it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
|
||||
const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
|
||||
const ids = m.categorias.map(c => c.id);
|
||||
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
|
||||
const f = barras(m, selection, 'claro');
|
||||
expect(f.data.map(t => t['uid'])).toEqual(ids);
|
||||
expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
|
||||
f.data.forEach((t, i) => {
|
||||
if (t['hoverinfo'] === 'skip') {
|
||||
expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
|
||||
} else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
|
||||
});
|
||||
dona(m, selection, 'claro');
|
||||
}
|
||||
expect(m).toEqual(snapshot); expect(data).toEqual(original);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
||||
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>${shareText(v, total)}` : ''));
|
||||
};
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
||||
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||
text: [`<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));
|
||||
// Every category keeps its trace (same uid and count) so a selection animates;
|
||||
// an unselected category is a zero-width bar without text or hover, never data.
|
||||
return { data: m.categorias.map(c => {
|
||||
const visible = visibles.includes(c.id);
|
||||
const x = m.escenarios.map(s => {
|
||||
const value = porcentaje(s, c.id);
|
||||
return value === null ? null : visible ? value : 0;
|
||||
});
|
||||
return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
|
||||
marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
|
||||
text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
|
||||
customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
|
||||
...(visible ? { hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }
|
||||
: { hoverinfo: 'skip' }) };
|
||||
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
||||
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, 112],
|
||||
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
|
||||
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
|
||||
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
|
||||
: sel.grupo || sel.categoria ? `<b>${percentNumber(sumas[i]!)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
|
||||
: miles(s.den) })),
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
|
||||
// Presentation policy only. Each indicator owns a stable selection and revision;
|
||||
// no global Apply can invalidate its figure or numeric snapshot. Omitting periodos
|
||||
// delegates to the existing backend contract for all reported semesters.
|
||||
const cacuSelections = new Map<string, GlobalApplied>(
|
||||
['cacu_eu13', 'ind1'].map(id => [id, Object.freeze({
|
||||
tipo: 'semestre' as const, selection: Object.freeze({ mode: 'todos' as const }), revision: 0,
|
||||
})]),
|
||||
);
|
||||
|
||||
export function independentFigurePeriods(domain: Dominio, id: string) {
|
||||
return domain === 'cacu' && cacuSelections.has(id);
|
||||
}
|
||||
|
||||
export function figureApplied(domain: Dominio, id: string, general: GlobalApplied): GlobalApplied {
|
||||
return domain === 'cacu' ? cacuSelections.get(id) ?? general : general;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { percentNumber, percentText, roundPercent, sharePercent, shareText } from './indicadores-format';
|
||||
|
||||
describe('regla de redondeo de porcentajes', () => {
|
||||
it('una décima, medio hacia arriba, calculada con enteros', () => {
|
||||
expect(sharePercent(2, 303)).toBe(0.7);
|
||||
expect(sharePercent(1, 8)).toBe(12.5);
|
||||
expect(sharePercent(1, 3)).toBe(33.3);
|
||||
expect(sharePercent(2, 3)).toBe(66.7);
|
||||
expect(shareText(0, 9)).toBe('0.0 %');
|
||||
expect(shareText(5, 5)).toBe('100.0 %');
|
||||
});
|
||||
it('entre 0 y 0.1, la primera cifra significativa', () => {
|
||||
expect(shareText(1, 2000)).toBe('0.05 %');
|
||||
expect(shareText(1, 1600)).toBe('0.06 %');
|
||||
expect(percentText(0.0432)).toBe('0.04 %');
|
||||
});
|
||||
it('un porcentaje publicado redondea igual, sin sorpresas de coma flotante', () => {
|
||||
expect(roundPercent(0.6600660066)).toBe(0.7);
|
||||
expect(roundPercent(12.25)).toBe(12.3);
|
||||
expect(roundPercent(1.005 * 10)).toBe(10.1);
|
||||
expect(percentNumber(100)).toBe('100.0');
|
||||
expect(percentText(null)).toBe('No disponible');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
// One rounding rule for every percentage shown: one decimal, half up; between 0 and 0.1
|
||||
// the first significant digit (0.04 %, not 0.0 %). Integer counts round exactly, without
|
||||
// binary floating-point surprises (1.005 → 1.0 with toFixed).
|
||||
|
||||
/** The percentage of `k` in `n`, rounded by the rule, computed from integers. */
|
||||
export function sharePercent(k: number, n: number): number {
|
||||
if (k > 0 && 1000 * k < n) return Number((100 * k / n).toPrecision(1));
|
||||
return Math.floor((2000 * k + n) / (2 * n)) / 10;
|
||||
}
|
||||
|
||||
/** A published percentage (0 to 100), rounded by the rule. */
|
||||
export function roundPercent(value: number): number {
|
||||
if (value > 0 && value < 0.1) return Number(value.toPrecision(1));
|
||||
// Snap to 9 decimals first so 12.25 published as 12.2499999999 still rounds up.
|
||||
return Math.floor(Math.round(value * 1e9) / 1e8 + 0.5) / 10;
|
||||
}
|
||||
|
||||
/** Text of a rounded percentage: «12.3», «0.04», «100.0». */
|
||||
export function percentNumber(value: number): string {
|
||||
const rounded = roundPercent(value);
|
||||
return rounded > 0 && rounded < 0.1 ? String(rounded) : rounded.toFixed(1);
|
||||
}
|
||||
|
||||
/** «12.3 %» from a published percentage, or the fallback when there is none. */
|
||||
export function percentText(value: number | null | undefined, fallback = 'No disponible'): string {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
|
||||
}
|
||||
|
||||
/** «12.3 %» from a count over its denominator. */
|
||||
export function shareText(k: number, n: number): string {
|
||||
const value = sharePercent(k, n);
|
||||
return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
|
||||
}
|
||||
@@ -114,7 +114,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
|
||||
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('granularidad mes');
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de tiempo mes');
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
r.flush({ data: [], layout: {} });
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
|
||||
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { pending } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@@ -22,7 +22,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
const definitions = KPI_BY_DOMAIN[domain];
|
||||
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
|
||||
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
|
||||
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }];
|
||||
// Two figures, so every domain keeps an ordinary card whose representation can change.
|
||||
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f', 'g'] }];
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
@@ -33,7 +34,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
const inventory = http.match(r => r.url.endsWith('/periodos'));
|
||||
expect(inventory).toHaveLength(4); // The anchor search shares the catalog inventory request.
|
||||
expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request.
|
||||
inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
|
||||
fixture.detectChanges();
|
||||
});
|
||||
@@ -41,15 +42,26 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
function data(index: number, period: string, value = 7) {
|
||||
const d = definitions[index];
|
||||
return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: [period], categorias: { A: {} }, filas: [{
|
||||
periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
|
||||
periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
|
||||
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
|
||||
}
|
||||
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); }
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
function flushPanels(period: string, expected = 2) {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
function flushPanels(period: string, expected = definitions.length - 1) {
|
||||
const requests = originalRequests();
|
||||
expect(requests).toHaveLength(expected);
|
||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
|
||||
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
|
||||
@@ -101,24 +113,32 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[1]] });
|
||||
expect(page.filters!.editors.semestre!.draft).toEqual(page.filters!.applied.selection);
|
||||
expect(pending(page.filters!)).toBe(false); expect(editor().selectedPeriods).toEqual([periods[1]]);
|
||||
expect(panels()).toHaveLength(3);
|
||||
expect(panels()).toHaveLength(definitions.length);
|
||||
expect(panels().every(p => p.applied === page.filters!.applied && !p.initialPresentation && p.temporalReference === periods[1])).toBe(true);
|
||||
expect(panels()[0].result().value).toBe(7); http.expectNone(() => true);
|
||||
});
|
||||
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 and the CaCu paired times own coordinated views. This temporal fixture publishes
|
||||
// only placeholder f/g figures, so EU7 stops as incompatible without GET; the paired times
|
||||
// ask /datos for the same shared period, including the partner hidden from the catalog.
|
||||
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length);
|
||||
const tiempos = http.match(r => r.url.endsWith('/datos'));
|
||||
// P0-C.1 cached the same lab payload; the paired figure reuses it.
|
||||
expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(false);
|
||||
for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); }
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
|
||||
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
|
||||
const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(2);
|
||||
const requests = originalRequests(); expect(requests).toHaveLength(definitions.length - 1);
|
||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
|
||||
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => {
|
||||
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
|
||||
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
|
||||
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
|
||||
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
|
||||
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
|
||||
@@ -126,13 +146,14 @@ 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.tiempos)!;
|
||||
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
|
||||
expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready');
|
||||
});
|
||||
it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => {
|
||||
choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
|
||||
choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
|
||||
page.changeDominio(otherDomain); http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges();
|
||||
page.changeDominio('tea'); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
@@ -145,7 +166,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
});
|
||||
it('Aplicar Todos durante búsqueda cancela y respeta la decisión manual', () => {
|
||||
const old = request(periods[0]); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false);
|
||||
page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], 3);
|
||||
page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], definitions.length);
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true);
|
||||
});
|
||||
it('error HTTP queda visible, sin datos mezclados, con reintento funcional', () => {
|
||||
@@ -172,7 +193,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
page.retryCatalog(); http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(page.initialPeriodState()).toBe('manual'); http.expectNone(() => true);
|
||||
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
|
||||
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
|
||||
expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('un ancla retirada del catálogo requiere selección manual y no consulta datos retirados', () => {
|
||||
@@ -182,11 +203,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
expect(page.kpiIndicator(definitions[0].id)).toBeUndefined();
|
||||
expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => {
|
||||
originalRequests().forEach(r => {
|
||||
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
||||
expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0]));
|
||||
}); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true);
|
||||
expect(panels()).toHaveLength(definitions.length - 1); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('inicializa y restaura los tres dominios con periodos propios sin repetir datos resueltos', () => {
|
||||
choose();
|
||||
@@ -202,11 +223,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] }));
|
||||
const payload = (index: number) => {
|
||||
const value = data(index, period); value.id = definitions[index].id;
|
||||
value.filas[0].grupo = index === 1 && target !== 'tea' ? 'total' : 'TOTAL'; return value;
|
||||
const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato;
|
||||
value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value;
|
||||
};
|
||||
http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges();
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => {
|
||||
originalRequests().forEach(r => {
|
||||
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index));
|
||||
}); fixture.detectChanges();
|
||||
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] });
|
||||
|
||||
@@ -74,7 +74,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
|
||||
const run = start(); http.expectOne(`/${domain}/indicadores/${anchor.id}/periodos`).flush('', { status: 404, statusText: 'Missing' });
|
||||
expect(run.failed()).toBe(true); expect(run.completed()).toBe(false); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['semestre', 'mes'] as const)('busca únicamente la granularidad activa %s, sin mezclar tipos ni usar un mes más reciente', tipo => {
|
||||
it.each(['semestre', 'mes'] as const)('busca únicamente el intervalo de tiempo activo %s, sin mezclar tipos ni usar un mes más reciente', tipo => {
|
||||
const run = start(tipo); inventory(['2026-12', '2025-10', '2026-S1', '2025-S2']);
|
||||
const expected = tipo === 'mes' ? '2026-12' : '2026-S1'; request(expected).flush(data(expected));
|
||||
expect(run.selected()).toEqual({ periodo: expected, tipo }); http.expectNone(() => true);
|
||||
|
||||
@@ -140,6 +140,6 @@ describe('KPI de CaMa con respuestas reales de WebApi', () => {
|
||||
});
|
||||
it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => {
|
||||
expect(result(2).state).toBe('Disponible');
|
||||
expect(result(2).info).toContain('El horizonte de 180 días es provisional.');
|
||||
expect(result(2).info).toMatch(/^[\d.,]+ mastografías; Q1 a Q3: [\d.]+ a [\d.]+ días\.$/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Component, input } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter, ActivatedRoute } from '@angular/router';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { PARES_TIEMPOS } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
|
||||
// Synthetic contract examples only; no value in these tests is a deployed clinical result.
|
||||
const payload = (period = '2025-S1', extra: Record<string, unknown> = {}): IndicadorDatos => ({
|
||||
id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period],
|
||||
filas: [{ periodo: period, grupo: 'TOTAL', estrato: null, n: 20, q1: 7, mediana: 12, q3: 20, unidad: 'dias', suprimido: 0, ...extra }],
|
||||
});
|
||||
|
||||
describe('P0-C.1: contrato de toma a resultado', () => {
|
||||
const read = (data: IndicadorDatos) => kpiResult(data, CACU_RESULTADO_KPI, 'cacu', applied);
|
||||
it('usa el ID del laboratorio del par, nunca la mediana de diagnóstico', () => {
|
||||
expect(CACU_RESULTADO_KPI.id).toBe(PARES_TIEMPOS.find(p => p.dominio === 'cacu')!.reporte);
|
||||
expect(read(payload())).toMatchObject({ state: 'Disponible', value: 12 });
|
||||
expect(CACU_RESULTADO_KPI.unit).toBe('días (mediana)');
|
||||
const diagnosis = { ...payload('2025-S1', { mediana: 52, q3: 90 }), id: KPI_BY_DOMAIN.cacu[1].id };
|
||||
expect(read(diagnosis).state).toBe('Error de contrato');
|
||||
expect(kpiResult(diagnosis, KPI_BY_DOMAIN.cacu[1], 'cacu', applied).value).toBe(52);
|
||||
});
|
||||
it.each([{ mediana: null }, { n: 0 }, { n: null }, { q1: null }, { unidad: 'meses' }, { q1: 15 }])('no inventa valor ante %j', extra => {
|
||||
expect(read(payload('2025-S1', extra))).toEqual({ state: 'Sin valor disponible' });
|
||||
});
|
||||
it('cero publicado es válido, supresión nunca expone cuantiles ni conteo', () => {
|
||||
expect(read(payload('2025-S1', { mediana: 0, q1: 0 })).value).toBe(0);
|
||||
expect(read(payload('2025-S1', { suprimido: 1 }))).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
expect(read(payload('2025-S1', { suprimido: null })).value).toBeUndefined();
|
||||
});
|
||||
it('distingue vacío, periodo equivocado y selección no consolidable sin mezclar grupos o tipos', () => {
|
||||
expect(read({ ...payload(), filas: [], periodos: [] }).state).toBe('Sin filas utilizables');
|
||||
expect(read(payload('2025-S2')).state).toBe('Selección no consolidable');
|
||||
expect(read(payload('2025-01')).state).toBe('Error de contrato');
|
||||
expect(read({ ...payload(), filas: [...payload().filas, ...payload().filas] }).state).toBe('Selección no consolidable');
|
||||
expect(read(payload('2025-S1', { estrato: 'grupo_edad' })).state).toBe('Selección no consolidable');
|
||||
expect(kpiResult(payload(), CACU_RESULTADO_KPI, 'cacu', { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable');
|
||||
});
|
||||
});
|
||||
|
||||
describe('P0-C.1: transporte y periodo aplicado', () => {
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorKpiPanel>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorKpiPanel);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('definition', CACU_RESULTADO_KPI);
|
||||
f.componentRef.setInput('applied', applied); f.detectChanges();
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
const request = () => http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
|
||||
it('reutiliza la consulta idéntica en vuelo y completada de la gráfica mediante snapshots', () => {
|
||||
let received: IndicadorDatos | undefined;
|
||||
const snapshots = TestBed.inject(IndicadoresSnapshots);
|
||||
snapshots.datos('cacu', CACU_RESULTADO_KPI.id, 'semestre', ['2025-S1']).subscribe(data => received = data);
|
||||
const r = request(); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(payload());
|
||||
expect(received?.filas[0]['mediana']).toBe(12); expect(f.componentInstance.result().value).toBe(12);
|
||||
f.componentRef.setInput('applied', { ...applied, revision: 2 }); f.detectChanges();
|
||||
expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['empty', '404', 'suppressed', 'error'] as const)('%s no dispara búsqueda de otro periodo', scenario => {
|
||||
const r = request();
|
||||
if (scenario === '404' || scenario === 'error') r.flush('private', { status: scenario === '404' ? 404 : 503, statusText: 'Unavailable' });
|
||||
else r.flush(scenario === 'empty' ? { ...payload(), filas: [], periodos: [] } : payload('2025-S1', { suprimido: 1 }));
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.result().state).toBe({ empty: 'Sin filas utilizables', '404': 'Sin datos del periodo', suppressed: 'Dato oculto por tamaño', error: 'Error de consulta' }[scenario]);
|
||||
expect(f.componentInstance.result().value).toBeUndefined(); expect(f.componentInstance.temporalReference).toBe('2025-S1');
|
||||
expect(f.nativeElement.textContent).not.toContain('private'); http.expectNone(() => true);
|
||||
});
|
||||
it('la gráfica pareada comparte la petición en vuelo y conserva ambas series originales', () => {
|
||||
const chart = TestBed.createComponent(IndicadorTiemposPareados);
|
||||
try {
|
||||
chart.componentRef.setInput('dominio', 'cacu'); chart.componentRef.setInput('tema', 'claro');
|
||||
chart.componentRef.setInput('par', PARES_TIEMPOS.find(p => p.dominio === 'cacu')!);
|
||||
chart.componentRef.setInput('indicador', { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', tipos_periodo: ['semestre'], figuras: ['fig_c3r_caja'] });
|
||||
chart.componentRef.setInput('applied', applied); chart.detectChanges();
|
||||
const lab = request(); expect(lab.request.params.get('periodos')).toBe('2025-S1');
|
||||
lab.flush(payload());
|
||||
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
|
||||
chart.detectChanges();
|
||||
expect(chart.componentInstance.figure!.data.map(series => series['name'])).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
|
||||
expect(chart.componentInstance.figure!.data.map(series => series['median'])).toEqual([[12], [52]]);
|
||||
expect(f.componentInstance.result().value).toBe(12); http.expectNone(() => true);
|
||||
} finally { chart.destroy(); }
|
||||
});
|
||||
it('Todos y varios periodos no consultan; un mes consulta únicamente ese mes', () => {
|
||||
const old = request();
|
||||
for (const selection of [{ mode: 'todos' as const }, { mode: 'explicit' as const, periodos: ['2025-S1', '2025-S2'] as [string, ...string[]] }]) {
|
||||
f.componentRef.setInput('applied', { ...applied, selection, revision: 2 }); f.detectChanges();
|
||||
expect(f.componentInstance.result().state).toBe('Selección no consolidable'); http.expectNone(() => true);
|
||||
}
|
||||
expect(old.cancelled).toBe(true);
|
||||
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 3 }); f.detectChanges();
|
||||
const r = request(); expect(r.request.params.get('periodos')).toBe('2025-02'); r.flush(payload('2025-02'));
|
||||
expect(f.componentInstance.result().value).toBe(12);
|
||||
});
|
||||
});
|
||||
|
||||
describe('P0-C.1: cinco tarjetas de oportunidad', () => {
|
||||
it('conserva los originales, agrega laboratorio y deja ambos tratamientos inertes', () => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]),
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }] });
|
||||
const f = TestBed.createComponent(IndicadoresPage), http = TestBed.inject(HttpTestingController);
|
||||
try {
|
||||
// The established lab partner is absent from this visible catalog, as in the paired figure.
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
|
||||
http.expectOne(r => r.url.includes('/cacu_eu7/datos')).flush({ id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 20, suprimido: 0 }] });
|
||||
f.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/cacu_eu_tiempo_reporte/datos')).flush(payload());
|
||||
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
|
||||
f.detectChanges();
|
||||
const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
|
||||
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
|
||||
for (const card of cards.slice(3)) {
|
||||
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,17 @@
|
||||
import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
||||
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 };
|
||||
// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI.
|
||||
const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0],
|
||||
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] };
|
||||
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
|
||||
const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
|
||||
}
|
||||
describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
|
||||
const c1Group = domain === 'tea' ? 'TOTAL' : 'total';
|
||||
const run = (index: number, rows: Record<string, unknown>[]) => kpiResult(data(domain, index, rows), KPI_BY_DOMAIN[domain][index], domain, applied);
|
||||
const run = (index: number, rows: Record<string, unknown>[]) => kpiResult(data(domain, index, rows), definitions[domain][index], domain, applied);
|
||||
it('C2 suma categorías disjuntas del único TOTAL incluyendo SIN_DATO y cero', () => {
|
||||
expect(run(0, [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'SIN_DATO', n: 0 }]).value).toBe(5);
|
||||
expect(run(0, [{ ...total, categoria: 'A', n: 0 }]).value).toBe(0);
|
||||
@@ -18,10 +21,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
|
||||
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
|
||||
expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
|
||||
});
|
||||
it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => {
|
||||
it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => {
|
||||
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
|
||||
expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días');
|
||||
if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional');
|
||||
expect(result.value).toBe(0);
|
||||
expect(result.info).toContain(domain === 'cacu' ? 'primer cuartil: 0 días; tercer cuartil: 7 días' : '0 a 7 días');
|
||||
expect(result.info).not.toContain('provisional');
|
||||
});
|
||||
it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => {
|
||||
expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; }
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; }
|
||||
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
|
||||
export const CACU_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
};
|
||||
// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
@@ -14,7 +19,6 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
],
|
||||
cacu: [
|
||||
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: 'cacu_eu13', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
],
|
||||
cama: [
|
||||
@@ -32,8 +36,8 @@ const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => strin
|
||||
};
|
||||
const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = {
|
||||
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`,
|
||||
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`,
|
||||
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
|
||||
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
};
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; }
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
@@ -43,6 +47,7 @@ const unscoped = { state: 'Selección no consolidable', info: 'Elige un único p
|
||||
// C2 definitions count each patient once per period, in disjoint categories of TOTAL.
|
||||
// C1/C3r publish a single total row. Never combine totals, strata, or periods.
|
||||
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
|
||||
if (definition.singleAppliedPeriod && (applied.selection.mode !== 'explicit' || applied.selection.periodos.length !== 1)) return unscoped;
|
||||
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
|
||||
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
|
||||
}
|
||||
@@ -69,12 +74,12 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
if (!rows.every(row => count(row['n']))) return empty;
|
||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
if (!count(value)) return empty;
|
||||
return { state: 'Disponible', value, info: 'Conteo de pacientes únicos en el periodo.' };
|
||||
return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
|
||||
return { state: 'Disponible', value: row['valor'].toFixed(1), info: C1_INFO[domain](row['numerador'], row['denominador']) };
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) };
|
||||
}
|
||||
if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('D.2 memoria global por dominio', () => {
|
||||
it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => {
|
||||
expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false);
|
||||
});
|
||||
it('adapter no transforma ni recorta y requiere primera granularidad para Todos', () => {
|
||||
it('adapter no transforma ni recorta y requiere el primer intervalo de tiempo para Todos', () => {
|
||||
const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 };
|
||||
const snapshot = JSON.stringify(applied);
|
||||
expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true);
|
||||
|
||||
@@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason:
|
||||
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
|
||||
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
|
||||
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
|
||||
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite la granularidad ' + applied.tipo + ' del filtro general.' };
|
||||
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de tiempo ' + applied.tipo + ' del filtro general.' };
|
||||
const mode = applied.selection.mode;
|
||||
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
|
||||
? 'Todos con reporte requiere semestre como primera granularidad publicada. Para meses elige periodos explícitos.'
|
||||
: 'Los periodos del filtro general no son válidos para esta granularidad.' };
|
||||
? 'Todos con reporte requiere semestre como primer intervalo de tiempo publicado. Para meses elige periodos explícitos.'
|
||||
: 'Los periodos del filtro general no son válidos para este intervalo de tiempo.' };
|
||||
return { compatible: true };
|
||||
}
|
||||
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
import { Dominio, IndicadorMetadatos } from './indicadores.models';
|
||||
|
||||
// Existing WebApp explanations, shared by figures and the definitions section.
|
||||
// These are editorial guidance, not additional metadata supplied by WebApi.
|
||||
// Editorial fallback for a figure whose metadata publishes no `como_leer`
|
||||
// (metadata not loaded yet, failed, or an older kit). Not WebApi metadata.
|
||||
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
C1: [
|
||||
'El punto representa la proporción observada.',
|
||||
'Cuando la figura publica intervalos Wilson al 95 %, la línea vertical representa ese intervalo. No se infieren intervalos cuando faltan.',
|
||||
'Los intervalos amplios pueden deberse a denominadores pequeños.',
|
||||
'Los intervalos amplios pueden deberse a un tamaño de muestra pequeño.',
|
||||
'Un porcentaje observado del 100 % no implica certeza poblacional.',
|
||||
],
|
||||
C3r: [
|
||||
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
|
||||
'Los límites de dibujo no representan necesariamente extremos observados.',
|
||||
'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
|
||||
'Pueden mostrarse etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
|
||||
],
|
||||
};
|
||||
export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.';
|
||||
|
||||
export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined {
|
||||
const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId);
|
||||
if (!detail) return undefined;
|
||||
const instructions = detail.como_leer ?? [];
|
||||
return instructions.some(line => line.trim().length > 0) ? instructions : undefined;
|
||||
// "Cómo leer" of a figure: the kit's `como_leer` when it publishes one, otherwise
|
||||
// the generic guidance of the figure's contract.
|
||||
export function figureInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string,
|
||||
contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
|
||||
const instructions = metadata?.figuras_detalle?.find(item => item.figura === figureId)?.como_leer ?? [];
|
||||
return instructions.some(line => line.trim().length > 0) ? instructions : contractInterpretation(contract, domain, pie);
|
||||
}
|
||||
|
||||
export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
|
||||
function contractInterpretation(contract: string | undefined, domain: Dominio, pie: boolean): readonly string[] {
|
||||
if (contract === 'C2') return [
|
||||
pie
|
||||
? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.'
|
||||
@@ -41,5 +42,5 @@ export function contractInterpretation(contract: string | undefined, domain: Dom
|
||||
];
|
||||
return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
|
||||
? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.']
|
||||
: ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.'];
|
||||
: ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de la figura; no se infiere su significado estadístico.'];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { Indicador } from './indicadores.models';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
|
||||
import fixtureData from './fixtures/cacu_seguimiento.json';
|
||||
|
||||
const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C1', figuras: ['f-' + id], tipos_periodo: ['semestre'] });
|
||||
|
||||
describe('UX-10 navegación lateral del catálogo gráfico', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({
|
||||
imports: [IndicadoresPage],
|
||||
providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider],
|
||||
});
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
page.closeGraphicNavigation(false, false);
|
||||
fixture.detectChanges();
|
||||
http.match(request => request.url.endsWith('/seguimiento')).forEach(request => request.flush(fixtureData));
|
||||
http.match(request => request.url.endsWith('/metadatos')).forEach(request => request.flush({}));
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
async function load(items: Indicador[], domain: 'tea' | 'cacu' | 'cama' = 'tea') {
|
||||
if (domain !== page.dominio) {
|
||||
http.expectOne('/' + page.dominio + '/indicadores').flush([]);
|
||||
fixture.detectChanges();
|
||||
page.changeDominio(domain);
|
||||
}
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
function trigger() { return fixture.nativeElement.querySelector('.graphic-navigation-trigger') as HTMLButtonElement | null; }
|
||||
function optionButtons() { return Array.from(document.querySelectorAll<HTMLButtonElement>('#indicator-navigation-panel .panel-list button')); }
|
||||
async function openPanel() {
|
||||
const button = trigger()!;
|
||||
button.focus();
|
||||
button.click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
return button;
|
||||
}
|
||||
function expectNoFigureRequests() { http.expectNone(request => request.url.includes('/figuras/') || request.url.endsWith('/datos')); }
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('aparece solo en Resumen para el dominio %s', async domain => {
|
||||
await load([item('chart', 'Indicador gráfico')], domain);
|
||||
expect(trigger()).not.toBeNull();
|
||||
page.changeSection('seguimiento'); fixture.detectChanges();
|
||||
expect(trigger()).toBeNull();
|
||||
page.changeSection('datos'); fixture.detectChanges();
|
||||
expect(trigger()).toBeNull();
|
||||
page.changeSection('resumen'); fixture.detectChanges();
|
||||
page.fichaPacienteAbierta.set(true); fixture.detectChanges();
|
||||
expect(trigger()).toBeNull();
|
||||
page.fichaPacienteAbierta.set(false); fixture.detectChanges();
|
||||
expect(trigger()).not.toBeNull();
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('toma únicamente títulos y orden del catálogo visible, sin agregar KPI ni nombres alternos', async () => {
|
||||
const items = [item('a', 'Tasa visible exacta'), item('b', 'Distribución por edad')];
|
||||
await load(items, 'cacu');
|
||||
expect(page.showGraphicNavigation).toBe(true);
|
||||
await openPanel();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Tasa visible exacta', 'Distribución por edad']);
|
||||
expect(optionButtons().map(button => button.getAttribute('aria-label'))).toEqual(['Tasa visible exacta', 'Distribución por edad']);
|
||||
expect(optionButtons().some(button => button.textContent?.includes('Oportunidad') || button.textContent?.includes('destacado'))).toBe(false);
|
||||
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-panel').length).toBe(0);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('presenta un popover compacto anclado al botón, sin backdrop ni bloqueo del scroll', async () => {
|
||||
await load([item('a', 'Uno'), item('b', 'Título largo del indicador')]);
|
||||
const button = trigger()!;
|
||||
vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(new DOMRect(8, 180, 48, 48));
|
||||
const bodyOverflow = document.body.style.overflow;
|
||||
await openPanel();
|
||||
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
|
||||
expect(page.navigationPositions[0]).toEqual({ originX: 'start', overlayX: 'start', originY: 'center', overlayY: 'center' });
|
||||
expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
|
||||
expect(document.querySelector('.cdk-overlay-backdrop')).toBeNull();
|
||||
expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
|
||||
expect(bodyOverflow).toBe(document.body.style.overflow);
|
||||
expect(page.navigationScrollStrategy.constructor.name).toBe('RepositionScrollStrategy');
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('usa scroll interno en una lista extensa y se adapta al ancho disponible', async () => {
|
||||
await load(Array.from({ length: 30 }, (_, index) => item('indicator-' + index, 'Indicador clínico ' + index)));
|
||||
await openPanel();
|
||||
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
|
||||
const list = panel.querySelector<HTMLElement>('.panel-list')!;
|
||||
expect(optionButtons()).toHaveLength(30);
|
||||
expect(getComputedStyle(panel).maxHeight).toBe('min(58dvh, 32rem)');
|
||||
expect(getComputedStyle(list).overflowY).toBe('auto');
|
||||
expect(getComputedStyle(panel.parentElement!).maxWidth).toBe('calc(100vw - 1rem)');
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('reubica el popover en viewports estrechos y conserva límites verticales', async () => {
|
||||
await load([item('one', 'Indicador')]);
|
||||
const previousWidth = window.innerWidth;
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 320 });
|
||||
try {
|
||||
await openPanel();
|
||||
const panel = document.querySelector<HTMLElement>('.panel-shell')!;
|
||||
const host = panel.parentElement!;
|
||||
expect(getComputedStyle(host).maxWidth).toBe('calc(100vw - 1rem)');
|
||||
expect(page.navigationPositions).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ originX: 'end', overlayX: 'end' }),
|
||||
expect.objectContaining({ originY: 'bottom', overlayY: 'bottom' }),
|
||||
]));
|
||||
expect(panel.closest('.cdk-overlay-pane')).not.toBeNull();
|
||||
} finally {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, value: previousWidth });
|
||||
}
|
||||
});
|
||||
|
||||
it('sigue el orden priorizado por búsqueda y fijación mientras el panel está abierto', async () => {
|
||||
await load([item('one', 'Alfa'), item('two', 'Beta'), item('three', 'Gamma')]);
|
||||
page.togglePinned(page.catalog()[2]);
|
||||
fixture.detectChanges();
|
||||
await openPanel();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
|
||||
page.changeSearchQuery('beta');
|
||||
fixture.detectChanges();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Beta', 'Gamma', 'Alfa']);
|
||||
page.changeSearchQuery('sin coincidencias');
|
||||
fixture.detectChanges();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Gamma', 'Alfa', 'Beta']);
|
||||
page.searchQuery.set('');
|
||||
page.catalog.set([item('updated', 'Versión actualizada'), item('two', 'Beta')]);
|
||||
fixture.detectChanges();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Versión actualizada', 'Beta']);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('mantiene keys únicas para títulos duplicados y navega a la tarjeta elegida', async () => {
|
||||
const items = [item('duplicate-a', 'Resultado clínico'), item('duplicate-b', 'Resultado clínico')];
|
||||
await load(items, 'cama');
|
||||
const scroll = vi.fn();
|
||||
const focus = vi.spyOn(HTMLElement.prototype, 'focus');
|
||||
for (const card of fixture.nativeElement.querySelectorAll('app-indicador-catalog-card')) {
|
||||
card.scrollIntoView = scroll;
|
||||
}
|
||||
await openPanel();
|
||||
expect(optionButtons()).toHaveLength(2);
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['Resultado clínico', 'Resultado clínico']);
|
||||
optionButtons()[1].click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const targetId = identityElementId(indicatorIdentity('cama', 'duplicate-b'));
|
||||
expect(scroll).toHaveBeenCalledOnce();
|
||||
expect(scroll.mock.instances[0]).toBe(fixture.nativeElement.querySelector('#' + targetId));
|
||||
expect(focus).toHaveBeenCalled();
|
||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('#' + targetId + ' h2'));
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('abre con foco dentro, expone el estado expandido y cierra restaurando el foco con Escape', async () => {
|
||||
await load([item('one', 'Indicador')]);
|
||||
const button = await openPanel();
|
||||
expect(button.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(document.querySelector('nav[aria-label="Navegar a indicadores clínicos"]')).not.toBeNull();
|
||||
expect(document.activeElement).toBe(optionButtons()[0]);
|
||||
expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
|
||||
document.querySelector('.panel-shell')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(button.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(document.activeElement).toBe(button);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('cierra al pulsar fuera y mantiene el click externo disponible', async () => {
|
||||
const bodyOverflow = document.body.style.overflow;
|
||||
await load([item('one', 'Indicador')]);
|
||||
await openPanel();
|
||||
document.body.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
|
||||
document.body.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(page.navigationClosing()).toBe(true);
|
||||
expect(document.querySelector('app-indicadores-navegacion-panel')?.hasAttribute('inert')).toBe(true);
|
||||
expect(document.querySelector('.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing)')).not.toBeNull();
|
||||
expect(document.body.style.overflow).toBe(bodyOverflow);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('no conserva elementos al cambiar de dominio y elimina el encabezado y el botón X', async () => {
|
||||
await load([item('one', 'TEA gráfico')]);
|
||||
await openPanel();
|
||||
expect(document.querySelector('#indicator-navigation-title')).toBeNull();
|
||||
expect(document.querySelector('.panel-header')).toBeNull();
|
||||
expect(document.querySelector('.panel-shell mat-icon')).toBeNull();
|
||||
expect(document.querySelector('.panel-shell')?.querySelectorAll('button')).toHaveLength(1);
|
||||
page.changeDominio('cacu');
|
||||
http.expectOne('/cacu/indicadores').flush([item('new', 'CaCu clínico')]);
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(trigger()).not.toBeNull();
|
||||
await openPanel();
|
||||
expect(optionButtons().map(button => button.textContent?.trim())).toEqual(['CaCu clínico']);
|
||||
expect(optionButtons().some(button => button.textContent?.includes('TEA'))).toBe(false);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('respeta movimiento reducido, enfoca la tarjeta y no solicita sus figuras desde el panel', async () => {
|
||||
await load([item('lazy', 'Carga diferida')]);
|
||||
const card = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement;
|
||||
const scroll = vi.fn();
|
||||
card.scrollIntoView = scroll;
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
|
||||
await openPanel();
|
||||
optionButtons()[0].click();
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(scroll).toHaveBeenCalledWith({ behavior: 'instant', block: 'start' });
|
||||
expect(fixture.debugElement.query(By.css('app-indicador-catalog-card'))?.componentInstance?.visible).toBe(false);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
function pointer(target: Element, type: 'pointerenter' | 'pointerleave' | 'pointermove', pointerType = 'mouse', moved = true) {
|
||||
const event = new Event(type);
|
||||
Object.defineProperty(event, 'pointerType', { value: pointerType });
|
||||
target.dispatchEvent(event);
|
||||
// A real entry caused by mouse movement also dispatches pointermove. Layout-only entries don't.
|
||||
if (type === 'pointerenter' && moved) {
|
||||
const move = new Event('pointermove');
|
||||
Object.defineProperty(move, 'pointerType', { value: pointerType });
|
||||
target.dispatchEvent(move);
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function hoverDevice(enabled = true) {
|
||||
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: enabled && query === '(hover: hover) and (pointer: fine)' })));
|
||||
}
|
||||
|
||||
it('abre por hover sin mover el foco y conserva el origen CDK oculto y su caja', async () => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
hoverDevice();
|
||||
const button = trigger()!;
|
||||
const origin = fixture.debugElement.query(By.css('[cdkOverlayOrigin]')).nativeElement;
|
||||
const rect = new DOMRect(8, 180, 48, 48);
|
||||
vi.spyOn(button, 'getBoundingClientRect').mockReturnValue(rect);
|
||||
const initialFocus = document.activeElement;
|
||||
pointer(button, 'pointerenter');
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
expect(document.activeElement).toBe(initialFocus);
|
||||
expect(trigger()).toBe(origin);
|
||||
expect(getComputedStyle(button).opacity).toBe('0');
|
||||
expect(getComputedStyle(button).pointerEvents).toBe('none');
|
||||
expect(getComputedStyle(button).display).not.toBe('none');
|
||||
expect(button.getBoundingClientRect()).toBe(rect);
|
||||
expect(button.tabIndex).toBe(-1);
|
||||
expect(optionButtons()).toHaveLength(1);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('permite cruzar del disparador a cualquier opción y cancela el cierre al reingresar', async () => {
|
||||
await load([item('a', 'Uno'), item('b', 'Dos')]);
|
||||
hoverDevice(); vi.useFakeTimers();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
pointer(trigger()!, 'pointerleave');
|
||||
vi.advanceTimersByTime(200);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
const panel = document.querySelector('app-indicadores-navegacion-panel')!;
|
||||
pointer(panel, 'pointerenter');
|
||||
vi.advanceTimersByTime(300);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(panel, 'pointerleave');
|
||||
vi.advanceTimersByTime(200);
|
||||
pointer(panel, 'pointerenter');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(panel, 'pointerleave');
|
||||
vi.advanceTimersByTime(229);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
vi.advanceTimersByTime(1); fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(page.navigationAttached()).toBe(true);
|
||||
expect(document.querySelector('.panel-closing')).not.toBeNull();
|
||||
vi.advanceTimersByTime(180); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
expect(document.querySelector('.panel-shell')).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['touch', 'pen', 'mouse'])('sin hover real ignora %s y conserva la apertura por toque/clic', async pointerType => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
hoverDevice(false);
|
||||
pointer(trigger()!, 'pointerenter', pointerType);
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
trigger()!.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }));
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
page.toggleGraphicNavigation(new MouseEvent('click', { detail: 1 }));
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['Enter', ' '])('abre con %s, enfoca la primera opción y deja salir el foco con Tab', async key => {
|
||||
await load([item('a', 'Uno'), item('b', 'Dos')]);
|
||||
trigger()!.focus();
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
trigger()!.dispatchEvent(event);
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(document.activeElement).toBe(optionButtons()[0]);
|
||||
const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });
|
||||
optionButtons()[1].dispatchEvent(tab);
|
||||
expect(tab.defaultPrevented).toBe(false);
|
||||
expect(document.querySelector('.cdk-focus-trap-anchor')).toBeNull();
|
||||
const outside = fixture.nativeElement.querySelector('[role="tab"]') as HTMLButtonElement;
|
||||
outside.focus();
|
||||
expect(document.activeElement).toBe(outside);
|
||||
expectNoFigureRequests();
|
||||
});
|
||||
|
||||
it('no cierra al salir el puntero si una opción conserva el foco de teclado', async () => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
await openPanel();
|
||||
vi.useFakeTimers();
|
||||
pointer(document.querySelector('app-indicadores-navegacion-panel')!, 'pointerleave');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
});
|
||||
|
||||
it('cierra con Escape aun cuando hover no haya trasladado el foco al panel', async () => {
|
||||
await load([item('a', 'Indicador')]); hoverDevice();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
expect(document.activeElement).toBe(trigger());
|
||||
});
|
||||
|
||||
it('no espera animación al cerrar con movimiento reducido', async () => {
|
||||
await load([item('a', 'Indicador')]);
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));
|
||||
await openPanel();
|
||||
page.closeGraphicNavigation(); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
expect(document.querySelector('.panel-shell')).toBeNull();
|
||||
});
|
||||
|
||||
it('no reabre por entradas del puntero generadas al desmontar el overlay y admite un nuevo movimiento', async () => {
|
||||
await load([item('a', 'Indicador')]); hoverDevice(); vi.useFakeTimers();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
page.closeGraphicNavigation(); fixture.detectChanges();
|
||||
page.closeGraphicNavigation(); fixture.detectChanges();
|
||||
pointer(trigger()!, 'pointerenter', 'mouse', false);
|
||||
expect(page.navigationOpen()).toBe(false);
|
||||
vi.advanceTimersByTime(180); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
pointer(trigger()!, 'pointermove');
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
page.closeGraphicNavigation(false); fixture.detectChanges();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
vi.advanceTimersByTime(500); fixture.detectChanges();
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
expect(page.navigationClosing()).toBe(false);
|
||||
});
|
||||
|
||||
it('cancela el cierre pendiente al cambiar de sección o dominio y al destruir', async () => {
|
||||
await load([item('a', 'TEA')]); hoverDevice(); vi.useFakeTimers();
|
||||
pointer(trigger()!, 'pointerenter'); pointer(trigger()!, 'pointerleave');
|
||||
page.changeSection('datos'); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
page.changeSection('resumen'); fixture.detectChanges();
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(trigger()!, 'pointerleave');
|
||||
page.changeDominio('cama');
|
||||
http.expectOne('/cama/indicadores').flush([item('b', 'CaMa')]); fixture.detectChanges();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
pointer(trigger()!, 'pointerenter');
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(page.navigationOpen()).toBe(true);
|
||||
pointer(trigger()!, 'pointerleave');
|
||||
const clear = vi.spyOn(globalThis, 'clearTimeout');
|
||||
const close = vi.spyOn(page, 'closeGraphicNavigation');
|
||||
fixture.destroy();
|
||||
expect(page.navigationAttached()).toBe(false);
|
||||
expect(clear).toHaveBeenCalled();
|
||||
const callsAtDestroy = close.mock.calls.length;
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(close.mock.calls).toHaveLength(callsAtDestroy);
|
||||
});
|
||||
|
||||
it('mantiene botones estables, títulos completos multilínea y transforma solo la etiqueta visual', async () => {
|
||||
const title = 'Indicador clínico con un título extenso que puede ocupar varias líneas completas';
|
||||
await load([item('a', title), item('b', 'Otro indicador')]);
|
||||
await openPanel();
|
||||
const button = optionButtons()[0];
|
||||
expect(button.textContent?.trim()).toBe(title);
|
||||
expect(getComputedStyle(button).minHeight).toBe('44px');
|
||||
expect(getComputedStyle(button).whiteSpace).toBe('normal');
|
||||
expect(getComputedStyle(button).transform).not.toContain('scale');
|
||||
expect(button.querySelector('.option-label')).not.toBeNull();
|
||||
expect(getComputedStyle(document.querySelector('.panel-list')!).overflowX).toBe('hidden');
|
||||
const styles = Array.from(document.querySelectorAll('style')).map(style => style.textContent).join('\n');
|
||||
expect(styles).toContain('button:focus-visible');
|
||||
expect(styles).toContain('scale(1.02)');
|
||||
expect(styles).toContain('scale(0.99)');
|
||||
expect(styles).toContain('prefers-reduced-motion: reduce');
|
||||
expect(styles).toContain('@starting-style');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
<div class="panel-shell" id="indicator-navigation-panel" (keydown)="onKeydown($event)">
|
||||
<nav class="panel-list" aria-label="Navegar a indicadores clínicos">
|
||||
@if (items().length) {
|
||||
<ul>
|
||||
@for (item of items(); track item.key) {
|
||||
<li><button mat-button type="button" [attr.aria-label]="item.titulo" (click)="seleccionar(item.key)"><span class="option-label">{{ item.titulo }}</span></button></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
@@ -0,0 +1,20 @@
|
||||
:host { display: block; width: min(20rem, calc(100vw - 1rem)); max-width: calc(100vw - 1rem); min-width: 0; color: var(--issste-text); }
|
||||
.panel-shell { display: flex; flex-direction: column; width: 100%; max-height: min(58dvh, 32rem); min-height: 0; overflow: hidden; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: 0 8px 28px rgb(8 24 57 / 24%); opacity: 1; transform: scale(1); transform-origin: left center; transition: opacity 180ms ease, transform 180ms cubic-bezier(.2, .8, .2, 1); }
|
||||
@starting-style { .panel-shell { opacity: 0; transform: scale(.97); } }
|
||||
:host(.panel-closing) { pointer-events: none; }
|
||||
:host(.panel-closing) .panel-shell { opacity: 0; transform: scale(.97); }
|
||||
.panel-list { flex: 0 1 auto; min-height: 0; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; padding: .35rem .5rem; }
|
||||
ul { list-style: none; margin: 0; padding: 0; }
|
||||
li + li { margin-top: .1rem; }
|
||||
li button { display: flex; width: 100%; min-height: 44px; height: auto; justify-content: flex-start; padding: .15rem .2rem; text-align: start; white-space: normal; line-height: 1.35; color: inherit; }
|
||||
.option-label { display: block; width: 100%; min-width: 0; padding: .4rem; box-sizing: border-box; border-radius: .35rem; overflow-wrap: anywhere; transition: transform 180ms ease, background-color 180ms ease; }
|
||||
button:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.panel-list:has(button:focus-visible) button:not(:focus-visible) .option-label { transform: scale(.99); }
|
||||
button:focus-visible .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); }
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
.panel-list:has(button:hover) button:not(:hover):not(:focus-visible) .option-label { transform: scale(.99); }
|
||||
button:hover .option-label { transform: scale(1.02); background: color-mix(in srgb, var(--issste-accent) 14%, transparent); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.panel-shell, .option-label { transition: none; transform: none !important; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Component, ElementRef, Input, Signal, inject, output } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
|
||||
export interface IndicadorNavegacionItem {
|
||||
key: string;
|
||||
titulo: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-navegacion-panel',
|
||||
imports: [MatButtonModule],
|
||||
host: { '[class.panel-closing]': 'closing', '[attr.inert]': "closing ? '' : null" },
|
||||
templateUrl: './indicadores-navegacion-panel.html',
|
||||
styleUrl: './indicadores-navegacion-panel.scss',
|
||||
})
|
||||
export class IndicadoresNavegacionPanel {
|
||||
@Input({ required: true }) items!: Signal<readonly IndicadorNavegacionItem[]>;
|
||||
@Input() closing = false;
|
||||
readonly selected = output<string>();
|
||||
readonly closed = output<void>();
|
||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
focusFirstOption() { this.element.nativeElement.querySelector<HTMLButtonElement>('.panel-list button')?.focus({ preventScroll: true }); }
|
||||
containsFocus() { return this.element.nativeElement.contains(this.element.nativeElement.ownerDocument.activeElement); }
|
||||
|
||||
onKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.closed.emit();
|
||||
}
|
||||
|
||||
seleccionar(key: string) {
|
||||
if (this.items().some(item => item.key === key)) this.selected.emit(key);
|
||||
}
|
||||
}
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
export interface NumericRow { period: string; group: string; category: string; value: string; detail: string; state: string; }
|
||||
const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
function number(value: unknown, suffix = ''): string {
|
||||
if (value === null) return 'Sin valor (nulo)';
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${value}${suffix}` : 'No disponible';
|
||||
}
|
||||
function label(dictionary: unknown, key: unknown, fallback: string): string {
|
||||
const entry = record(dictionary) && typeof key === 'string' ? dictionary[key] : undefined;
|
||||
return typeof entry === 'string' ? entry : record(entry) && typeof entry['etiqueta'] === 'string' ? entry['etiqueta'] : fallback;
|
||||
}
|
||||
// Read published cells individually. No totals, reconstruction, statistical
|
||||
// computation or conversion of missing/suppressed values into zero.
|
||||
export function numericRows(data: IndicadorDatos): NumericRow[] {
|
||||
return data.filas.map(row => {
|
||||
const group = row['grupo'];
|
||||
const groupName = group === 'TOTAL' || group === 'total' ? 'Total'
|
||||
: label(data['grupos'], group, 'Grupo sin etiqueta publicada');
|
||||
const stratum = row['estrato'];
|
||||
const base = { period: typeof row['periodo'] === 'string' ? row['periodo'] : 'Periodo no disponible',
|
||||
group: stratum == null ? groupName : `${groupName} · ${label(data['valores_estrato'], stratum, 'Estrato sin etiqueta publicada')}`,
|
||||
category: label(data['categorias'], row['categoria'], row['categoria'] == null ? '—' : 'Categoría sin etiqueta publicada'),
|
||||
value: 'No disponible', detail: '', state: 'Disponible' };
|
||||
if (row['suprimido'] === 1 || row['suprimido'] === true) return { ...base, value: 'Dato suprimido', state: 'Dato suprimido' };
|
||||
if (row['suprimido'] !== 0 && row['suprimido'] !== false) return { ...base, state: 'Estado de supresión no disponible' };
|
||||
let primary: unknown;
|
||||
if (data.contrato === 'C1') {
|
||||
primary = row['valor'];
|
||||
return { ...base, value: number(primary, ' %'), state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible',
|
||||
detail: `Intervalo publicado: ${number(row['ic_bajo'])} a ${number(row['ic_alto'])} %. Numerador: ${number(row['numerador'])}; denominador: ${number(row['denominador'])}.` };
|
||||
}
|
||||
if (data.contrato === 'C2') {
|
||||
primary = row['n'];
|
||||
const category = record(data['categorias']) ? data['categorias'][String(row['categoria'])] : undefined;
|
||||
const parent = record(category) ? label(data['grupos_de_categoria'], category['grupo'], '') : '';
|
||||
const unit = typeof row['unidad'] === 'string' ? row['unidad'] : typeof data['unidad'] === 'string' ? data['unidad'] : '';
|
||||
return { ...base, category: [parent, base.category].filter(Boolean).join(' · '), value: number(primary),
|
||||
state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible',
|
||||
detail: [unit && `Unidad: ${unit}.`, Object.hasOwn(row, 'denominador') && `Denominador publicado: ${number(row['denominador'])}.`].filter(Boolean).join(' ') };
|
||||
}
|
||||
if (data.contrato === 'C3r') {
|
||||
primary = row['mediana'];
|
||||
const unit = row['unidad'] === 'dias' ? 'días' : typeof row['unidad'] === 'string' ? row['unidad'] : 'Unidad no disponible';
|
||||
return { ...base, value: `Mediana: ${number(primary)} · ${unit}`, state: typeof primary === 'number' && Number.isFinite(primary) ? 'Disponible' : 'Sin valor disponible',
|
||||
detail: `Q1: ${number(row['q1'])}; Q3: ${number(row['q3'])}; n: ${number(row['n'])}.` };
|
||||
}
|
||||
return { ...base, state: 'Resumen no disponible para este indicador' };
|
||||
});
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
|
||||
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { numericRows } from './indicadores-numeric-rows';
|
||||
import { dualFigures } from './indicadores-dual-figures';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const item: Indicador = { id: 'future_indicator', titulo: 'Distribución publicada', contrato: 'C2',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre'], version: '2.0' };
|
||||
// Representative MD-19 wire shapes: published C1 interval, C2 counts/category
|
||||
// metadata and C3r quartiles. Only test data; never served as dashboard indicators.
|
||||
function data(contract = 'C2'): IndicadorDatos {
|
||||
return { id: item.id, contrato: contract, tipo_periodo: 'semestre', periodos: ['2025-S2'], version: '2.0',
|
||||
categorias: { A: { etiqueta: 'Categoría publicada', grupo: 'g' } }, grupos_de_categoria: { g: 'Grupo de categorías' },
|
||||
filas: [{ periodo: '2025-S2', grupo: 'TOTAL', categoria: 'A', suprimido: 0, n: 0,
|
||||
valor: 0, numerador: 0, denominador: 20, ic_bajo: 0, ic_alto: 16.1, mediana: 4, q1: 2, q3: 7, unidad: 'dias' }] };
|
||||
}
|
||||
|
||||
describe('MD-19 lecturas y celdas numéricas', () => {
|
||||
it.each(['new_name', 'any_future_id'])('descubre doble representación de %s sin IDs de indicador', id => {
|
||||
expect(dualFigures({ ...item, id })).toEqual(['fig_c2_donas', 'fig_c2_barras']);
|
||||
expect(dualFigures({ ...item, id, contrato: 'C1' })).toEqual([]);
|
||||
expect(dualFigures({ ...item, id, figuras: ['fig_c2_donas'] })).toEqual([]);
|
||||
expect(dualFigures({ ...item, id, figuras: ['future_donut', 'future_bar'] })).toEqual([]);
|
||||
});
|
||||
it('C1 conserva cero, intervalo publicado y poblaciones sin recalcular Wilson', () => {
|
||||
const row = numericRows(data('C1'))[0];
|
||||
expect(row.value).toBe('0 %'); expect(row.state).toBe('Disponible');
|
||||
expect(row.detail).toBe('Intervalo publicado: 0 a 16.1 %. Numerador: 0; denominador: 20.');
|
||||
});
|
||||
it('C2 conserva categorías, grupos y conteos; no suma poblaciones superpuestas', () => {
|
||||
const sample = data(); sample['grupos'] = { other: 'Otra población' }; sample.filas.push({ ...sample.filas[0], grupo: 'other', n: 11 });
|
||||
const rows = numericRows(sample);
|
||||
expect(rows).toHaveLength(2); expect(rows.map(r => r.value)).toEqual(['0', '11']);
|
||||
expect(rows[0].category).toBe('Grupo de categorías · Categoría publicada');
|
||||
expect(rows[1].group).toBe('Otra población');
|
||||
});
|
||||
it('C3r sólo muestra mediana, Q1, Q3, n y unidad publicados', () => {
|
||||
const row = numericRows(data('C3r'))[0];
|
||||
expect(row.value).toBe('Mediana: 4 · días'); expect(row.detail).toBe('Q1: 2; Q3: 7; n: 0.');
|
||||
expect(JSON.stringify(row)).not.toMatch(/bigote|extremo|min|max/);
|
||||
});
|
||||
it.each(['C1', 'C2', 'C3r'])('%s nunca revela valores de una fila suprimida ni reconstruye totales', contract => {
|
||||
const sample = data(contract); sample.filas[0]['suprimido'] = 1;
|
||||
const row = numericRows(sample)[0]; expect(row.value).toBe('Dato suprimido'); expect(row.detail).toBe('');
|
||||
expect(row.state).toBe('Dato suprimido');
|
||||
});
|
||||
it('distingue null, ausencia, NaN, cero y supresión desconocida', () => {
|
||||
const sample = data();
|
||||
sample.filas = [null, undefined, NaN, 0].map(n => ({ periodo: '2025-S2', grupo: 'TOTAL', n, suprimido: 0 }));
|
||||
expect(numericRows(sample).map(r => r.value)).toEqual(['Sin valor (nulo)', 'No disponible', 'No disponible', '0']);
|
||||
delete sample.filas[0]['suprimido']; expect(numericRows(sample)[0].value).toBe('No disponible');
|
||||
expect(numericRows(sample)[0].state).toContain('supresión no disponible');
|
||||
});
|
||||
});
|
||||
|
||||
describe('snapshots compartidos y resumen accesible', () => {
|
||||
let http: HttpTestingController, snapshots: IndicadoresSnapshots;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
const request = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
it('deduplica datos simultáneos de KPI, panel y tabla, y reutiliza payload terminado', () => {
|
||||
const queries = TestBed.inject(IndicadoresKpiQueries);
|
||||
const values: IndicadorDatos[] = [];
|
||||
queries.datos('tea', item.id, applied.tipo, '2025-S2', item.version).subscribe(value => values.push(value));
|
||||
snapshots.read('tea', item, applied).subscribe();
|
||||
snapshots.datos('tea', item.id, applied.tipo, ['2025-S2'], item.version).subscribe(value => values.push(value));
|
||||
request().flush(data()); expect(values).toHaveLength(2); expect(values[0]).toBe(values[1]);
|
||||
snapshots.read('tea', item, { ...applied, revision: 2 }).subscribe(); http.expectNone(() => true);
|
||||
expect(snapshots.numeric().get(snapshotKey('tea', item, { ...applied, revision: 2 }))?.status).toBe('ready');
|
||||
});
|
||||
it('incluye dominio, versión, tipo, selección y revisión en identidad', () => {
|
||||
const keys = [snapshotKey('tea', item, applied), snapshotKey('cama', item, applied),
|
||||
snapshotKey('tea', { ...item, version: '3.0' }, applied), snapshotKey('tea', item, { ...applied, revision: 2 }),
|
||||
snapshotKey('tea', item, { ...applied, tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01'] } }),
|
||||
snapshotKey('tea', item, { ...applied, selection: { mode: 'todos' } })];
|
||||
expect(new Set(keys).size).toBe(keys.length);
|
||||
});
|
||||
it('registra la identidad de versión publicada aunque el catálogo no la exponga', () => {
|
||||
const unversioned = { ...item, version: undefined };
|
||||
snapshots.read('tea', unversioned, applied).subscribe(); request().flush(data());
|
||||
const alias = snapshots.numeric().get(snapshotKey('tea', unversioned, applied));
|
||||
expect(alias?.sourceKey).toBe(snapshotKey('tea', item, applied));
|
||||
expect(snapshots.numeric().get(alias!.sourceKey!)).toBe(alias);
|
||||
});
|
||||
it('reutiliza en la tabla los detalles de datos consultados por un KPI, sin activar figuras', () => {
|
||||
TestBed.inject(IndicadoresKpiQueries).datos('tea', item.id, 'semestre', '2025-S2', item.version).subscribe();
|
||||
request().flush(data());
|
||||
expect(snapshots.reading('tea', item, applied)?.data).toEqual(data()); http.expectNone(() => true);
|
||||
});
|
||||
it('cancelar una lectura compartida conserva al otro consumidor; cancelar todos aborta HTTP', () => {
|
||||
const a = snapshots.read('tea', item, applied).subscribe(), b = snapshots.read('tea', item, applied).subscribe();
|
||||
const pending = request(); a.unsubscribe(); expect(pending.cancelled).toBe(false);
|
||||
b.unsubscribe(); expect(pending.cancelled).toBe(true);
|
||||
snapshots.read('tea', item, applied).subscribe(); request().flush(data());
|
||||
});
|
||||
it.each([404, 503])('conserva error HTTP %s y permite reintento sin cachear el error', status => {
|
||||
snapshots.read('tea', item, applied).subscribe(); request().flush({}, { status, statusText: 'Failure' });
|
||||
expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error');
|
||||
snapshots.read('tea', item, applied).subscribe(); request().flush(data());
|
||||
expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready');
|
||||
});
|
||||
it.each(['period', 'contract', 'version', 'row'])('rechaza respuesta incompatible por %s', kind => {
|
||||
snapshots.read('tea', item, applied).subscribe(); const sample = data();
|
||||
if (kind === 'period') sample.periodos = ['2024-S1'];
|
||||
if (kind === 'contract') sample.contrato = 'C1';
|
||||
if (kind === 'version') sample['version'] = '1.0';
|
||||
if (kind === 'row') sample.filas[0]['periodo'] = '2024-S1';
|
||||
request().flush(sample); expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('error');
|
||||
});
|
||||
it('tabla reutiliza exactamente KPI, cambia periodo/dominio sin mostrar valores anteriores y respeta catálogo retirado', () => {
|
||||
const fixture = TestBed.createComponent(IndicadoresNumericSummary);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied);
|
||||
fixture.componentRef.setInput('kpis', [{ id: item.id, title: 'Destacado publicado', unit: '%', contrato: 'C1' }]);
|
||||
snapshots.publishKpi('tea', item, applied, { value: '42.0', unit: '%', state: 'Disponible', period: '2025-S2', info: 'Nota publicada' });
|
||||
fixture.detectChanges(); let element = fixture.nativeElement as HTMLElement;
|
||||
expect(element.querySelector('.kpi-reading')?.textContent?.replace(/\s+/g, ' ')).toContain('42.0 %');
|
||||
expect(element.querySelector('.kpi-reading')?.textContent).toContain('2025-S2');
|
||||
expect(element.querySelector('.kpi-reading')?.textContent).toContain('Nota publicada');
|
||||
expect(element.querySelector('caption')).toBeTruthy(); expect(element.querySelectorAll('thead th[scope="col"]')).toHaveLength(5);
|
||||
expect(element.querySelector('.table-scroll')?.getAttribute('tabindex')).toBe('0'); http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } });
|
||||
fixture.detectChanges(); expect(element.textContent).not.toContain('42.0'); expect(element.textContent).toContain('2026-S1');
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
expect(element.textContent).not.toContain('42.0');
|
||||
fixture.componentRef.setInput('catalog', []); fixture.detectChanges(); expect(element.querySelectorAll('tbody tr')).toHaveLength(0);
|
||||
fixture.destroy();
|
||||
});
|
||||
it('tabla distingue carga, error y vacío publicado sin volver a consultar', () => {
|
||||
const fixture = TestBed.createComponent(IndicadoresNumericSummary);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', [item]); fixture.componentRef.setInput('applied', applied);
|
||||
snapshots.read('tea', item, applied).subscribe(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando…');
|
||||
request().flush({}, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Error de consulta');
|
||||
snapshots.read('tea', item, applied).subscribe(); request().flush({ ...data(), filas: [] }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Sin filas publicadas'); http.expectNone(() => true); fixture.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
describe('card doble, jerarquía y carga numérica diferida', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorCatalogCard>>, http: HttpTestingController, snapshots: IndicadoresSnapshots;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); snapshots = TestBed.inject(IndicadoresSnapshots);
|
||||
fixture = TestBed.createComponent(IndicadorCatalogCard);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', item);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const panels = () => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(el => el.componentInstance as IndicadorFigurePanel);
|
||||
function activate() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||
const figure = (id: string) => http.expectOne(r => r.url.endsWith('/figuras/' + id));
|
||||
it('dos paneles sin selector redundante, diferidos hasta activación y con mismo periodo aplicado', () => {
|
||||
expect(panels()).toHaveLength(2); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); http.expectNone(() => true);
|
||||
activate();
|
||||
const pending = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
expect(pending.request.params.get('periodos')).toBe('2025-S2'); pending.flush({ ...c2Fixture(), id: item.id });
|
||||
expect(panels().every(p => p.result().source === 'datos')).toBe(true);
|
||||
expect(fixture.nativeElement.classList.contains('dual-card')).toBe(true);
|
||||
expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('drill-down y restauración de dona no alteran barras, JSON original ni generan consultas', () => {
|
||||
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges();
|
||||
const bars = structuredClone(panels()[1].result().figure);
|
||||
const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard);
|
||||
const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result();
|
||||
const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf<HTMLButtonElement>].find(button => button.textContent?.trim() === 'G2')!;
|
||||
parentButton.click(); fixture.detectChanges(); expect(cards[0].activeParent).toBe('G2');
|
||||
expect(panels()[1].result()).toBe(barState); expect(panels()[1].result().figure).toEqual(bars);
|
||||
(fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); http.expectNone(() => true);
|
||||
});
|
||||
it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => {
|
||||
snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true);
|
||||
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges();
|
||||
expect(snapshots.numeric().get(snapshotKey('tea', item, applied))?.status).toBe('ready');
|
||||
snapshots.expanded.set(false); fixture.detectChanges(); snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it('cambio de periodo cancela ambas figuras y números; fuera de vista difiere el siguiente aplicado', () => {
|
||||
snapshots.expanded.set(true); activate(); const old = [http.expectOne(r => r.url.endsWith('/datos'))];
|
||||
fixture.componentInstance.setVisible(false); fixture.detectChanges();
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges();
|
||||
expect(old.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().status === 'deferred')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...data(), periodos: ['2026-S1'], filas: [] });
|
||||
for (const id of ['fig_c2_donas', 'fig_c2_barras']) {
|
||||
const pending = figure(id); expect(pending.request.params.get('periodos')).toBe('2026-S1'); pending.flush({ data: [], layout: {} });
|
||||
}
|
||||
});
|
||||
it('conserva preferencias y opciones adicionales; desaparece representación retirada y hace fallback', () => {
|
||||
const memory = TestBed.inject(IndicadoresMemory); memory.rememberFigure('tea', item.id, 'fig_c2_barras');
|
||||
fixture.componentRef.setInput('indicador', { ...item, figuras: [...item.figuras, 'future_representation'] }); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.isDual).toBe(true); expect(memory.figure('tea', item.id)).toBe('fig_c2_barras');
|
||||
fixture.componentInstance.selectFigure('future_representation'); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.displayFigures).toEqual(['future_representation']);
|
||||
fixture.componentRef.setInput('indicador', { ...item, figuras: ['fig_c2_donas'] }); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas']); expect(fixture.nativeElement.querySelector('mat-select')).toBeTruthy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import { Component, inject, Input, OnDestroy } from '@angular/core';
|
||||
import { Dominio, Indicador } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { KpiDefinition } from './indicadores-kpi';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { numericRows } from './indicadores-numeric-rows';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-numeric-summary',
|
||||
template: `
|
||||
<details (toggle)="toggle($event)">
|
||||
<summary><h2>Resumen de indicadores</h2></summary>
|
||||
<p>Valores publicados para {{ period }}. Los detalles se cargan al consultar las gráficas correspondientes. Cada fila conserva su periodo y población; no se suman grupos ni periodos.</p>
|
||||
<div class="table-scroll" role="region" aria-label="Resultados numéricos de indicadores" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados de indicadores destacados y gráficas consultadas</caption>
|
||||
<thead><tr><th scope="col">Indicador</th><th scope="col">Periodo</th><th scope="col">Grupo / categoría</th><th scope="col">Resultado</th><th scope="col">Estado y notas</th></tr></thead>
|
||||
<tbody>
|
||||
@for (definition of kpis; track definition.id) {
|
||||
@let item = find(definition.id);
|
||||
@if (item) {
|
||||
@let kpi = snapshots.kpis().get(key(item));
|
||||
<tr class="kpi-reading"><th scope="row">{{ definition.title }} <span class="kind">Destacado</span></th>
|
||||
<td>{{ kpi?.period ?? period }}</td><td>—</td>
|
||||
<td>{{ kpi?.value ?? 'No disponible' }} @if (kpi?.value !== undefined) { {{ kpi?.unit }} }</td>
|
||||
<td>{{ kpi?.state ?? 'Pendiente de lectura' }} {{ kpi?.info }} {{ kpi?.notes?.join(' ') }}</td></tr>
|
||||
}
|
||||
}
|
||||
@for (item of catalog; track item.id) {
|
||||
@let reading = snapshots.reading(dominio, item, applied);
|
||||
@let compatible = compatibility(item);
|
||||
@if (compatible.compatible && reading?.status === 'ready' && reading?.data; as data) {
|
||||
@for (row of rows(data); track $index) {
|
||||
<tr><th scope="row">{{ item.titulo }}</th><td>{{ row.period }}</td><td>{{ row.group }} · {{ row.category }}</td>
|
||||
<td>{{ row.value }} <span class="detail">{{ row.detail }}</span></td><td>{{ row.state }} {{ data.notas?.join(' ') }}</td></tr>
|
||||
} @empty {
|
||||
<tr><th scope="row">{{ item.titulo }}</th><td>{{ period }}</td><td>—</td><td>Sin filas publicadas</td><td>{{ data.notas?.join(' ') }}</td></tr>
|
||||
}
|
||||
} @else {
|
||||
<tr><th scope="row">{{ item.titulo }}</th><td>{{ period }}</td><td>—</td><td>No disponible</td>
|
||||
<td>{{ !compatible.compatible ? compatible.reason : reading?.status === 'loading' ? 'Cargando…' : reading?.status === 'error' ? 'Error de consulta: ' + reading?.message : 'Pendiente: consulta la gráfica para cargar sus números.' }}
|
||||
@if (reading?.status === 'error') { <button type="button" (click)="snapshots.retries.update(increment)" [attr.aria-label]="'Reintentar números de ' + item.titulo">Reintentar</button> }</td></tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; margin-top: var(--issste-space-6); }
|
||||
details { border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); padding: 1rem; }
|
||||
summary { cursor: pointer; min-height: 44px; align-content: center; }
|
||||
h2 { display: inline; font-family: var(--issste-font-heading); font-size: 1.5rem; }
|
||||
p, td, th { overflow-wrap: anywhere; }
|
||||
p, .kind, .detail { color: var(--issste-text-secondary); }
|
||||
.kind, .detail { display: block; font-weight: normal; }
|
||||
.table-scroll { overflow-x: auto; max-height: 32rem; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: .9rem; }
|
||||
caption { text-align: left; padding: .5rem; }
|
||||
th, td { padding: .65rem; border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; min-width: 6rem; }
|
||||
thead { background: var(--issste-surface); position: sticky; top: 0; }
|
||||
button { min-height: 44px; font: inherit; color: var(--issste-text); background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -2px; }
|
||||
@media (max-width: 550px) { details { padding: .5rem; } th, td { padding: .5rem; } }
|
||||
`,
|
||||
})
|
||||
export class IndicadoresNumericSummary implements OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) catalog: readonly Indicador[] = [];
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() kpis: readonly KpiDefinition[] = [];
|
||||
readonly snapshots = inject(IndicadoresSnapshots);
|
||||
readonly rows = numericRows;
|
||||
readonly increment = (value: number) => value + 1;
|
||||
get period() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
key(item: Indicador) { return snapshotKey(this.dominio, item, this.applied); }
|
||||
find(id: string) { return this.catalog.find(item => item.id === id); }
|
||||
compatibility(item: Indicador) { return filterCompatibility(this.applied, item.tipos_periodo); }
|
||||
toggle(event: Event) { this.snapshots.expanded.set((event.target as HTMLDetailsElement).open); }
|
||||
ngOnDestroy() { this.snapshots.expanded.set(false); }
|
||||
}
|
||||
@@ -1,28 +1,50 @@
|
||||
<section class="dashboard" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
<span class="domain">Dominio {{ domainLabels[dominio] }} · Investigación</span>
|
||||
<h1 id="dashboard-title">Dashboard de indicadores</h1>
|
||||
<p>Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.</p>
|
||||
@if (fichaPacienteAbierta()) {
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
<p>Consulta individual de seguimiento de cáncer cervicouterino</p>
|
||||
} @else {
|
||||
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
|
||||
<h1 id="dashboard-title">Indicadores</h1>
|
||||
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
|
||||
}
|
||||
</header>
|
||||
<nav aria-label="Dominios de indicadores">
|
||||
@for (domain of dominios; track domain) {
|
||||
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainLabels[domain] }}</a>
|
||||
}
|
||||
</nav>
|
||||
|
||||
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
|
||||
@for (section of sections; track section.id) {
|
||||
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
|
||||
[attr.aria-selected]="activeSection() === section.id" [tabIndex]="activeSection() === section.id ? 0 : -1"
|
||||
(click)="changeSection(section.id)">{{ section.label }}</button>
|
||||
}
|
||||
</div>
|
||||
@if (!fichaPacienteAbierta()) {
|
||||
<div class="section-tabs" [class.dark-theme]="tema === 'oscuro'" role="tablist" [attr.aria-label]="'Secciones de ' + domainLabels[dominio]" (keydown)="sectionKeydown($event)">
|
||||
@for (section of sections; track section.id) {
|
||||
<button type="button" role="tab" [id]="'tab-' + section.id" [attr.aria-controls]="'panel-' + section.id"
|
||||
[attr.aria-selected]="activeSection() === section.id" [tabIndex]="activeSection() === section.id ? 0 : -1"
|
||||
(click)="changeSection(section.id)">{{ section.label }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (showGraphicNavigation) {
|
||||
<button #navigationTrigger cdkOverlayOrigin #navigationOrigin="cdkOverlayOrigin" class="graphic-navigation-trigger" mat-mini-fab type="button"
|
||||
[class.graphic-navigation-trigger-expanded]="navigationOpen()" [tabIndex]="navigationOpen() ? -1 : 0"
|
||||
[attr.aria-label]="navigationOpen() ? 'Cerrar navegación por indicadores' : 'Abrir navegación por indicadores'"
|
||||
aria-controls="indicator-navigation-panel" [attr.aria-expanded]="navigationOpen()" (click)="toggleGraphicNavigation($event)"
|
||||
(keydown)="navigationTriggerKeydown($event)" (pointerenter)="navigationPointerEnter($event)" (pointerleave)="navigationPointerLeave($event)"
|
||||
(pointermove)="navigationPointerMove($event)">
|
||||
<mat-icon aria-hidden="true">format_list_bulleted</mat-icon>
|
||||
</button>
|
||||
<ng-template cdkConnectedOverlay [cdkConnectedOverlayOrigin]="navigationOrigin"
|
||||
[cdkConnectedOverlayOpen]="navigationAttached()" [cdkConnectedOverlayPositions]="navigationPositions"
|
||||
[cdkConnectedOverlayScrollStrategy]="navigationScrollStrategy" [cdkConnectedOverlayViewportMargin]="8"
|
||||
[cdkConnectedOverlayFlexibleDimensions]="true" [cdkConnectedOverlayPush]="true"
|
||||
cdkConnectedOverlayPanelClass="indicator-navigation-overlay"
|
||||
[cdkConnectedOverlayHasBackdrop]="false" (overlayOutsideClick)="closeGraphicNavigationFromOutside($event)"
|
||||
(overlayKeydown)="navigationOverlayKeydown($event)">
|
||||
<app-indicadores-navegacion-panel [items]="navigationItems" [closing]="navigationClosing()"
|
||||
(pointerenter)="navigationPointerEnter($event)" (pointerleave)="navigationPointerLeave($event)" (focusout)="navigationFocusOut()"
|
||||
(closed)="closeGraphicNavigation()" (selected)="selectGraphicNavigation($event)" />
|
||||
</ng-template>
|
||||
}
|
||||
|
||||
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
|
||||
@if (!catalogLoading() && filters; as state) {
|
||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
||||
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
|
||||
<p class="section-description">La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.</p>
|
||||
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
||||
(retryAvailability)="retryAvailability()"
|
||||
(edited)="editFilters()" (apply)="applyFilters()" />
|
||||
@@ -43,22 +65,26 @@
|
||||
} @else if (initialPeriodState() === 'manual') {
|
||||
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
|
||||
}
|
||||
@let kpis = availableKpis;
|
||||
@let kpis = opportunityKpis;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores destacados</h2>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length">
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||
@for (definition of kpis; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||
<div class="catalog-heading">
|
||||
<h2 id="graphic-section-title" class="section-title">Indicadores gráficos</h2>
|
||||
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
||||
@if (!catalogLoading() && !catalogError() && catalog().length) {
|
||||
<p class="catalog-count" role="status">{{ catalog().length }} indicadores publicados</p>
|
||||
}
|
||||
@@ -96,19 +122,17 @@
|
||||
}
|
||||
<div class="catalog-grid">
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="filters!.applied"
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
@if (!initialPeriodBlocked && filters && !catalogLoading() && !catalogError() && catalog().length) {
|
||||
<app-indicadores-numeric-summary [dominio]="dominio" [catalog]="catalog()" [applied]="filters.applied" [kpis]="availableKpis" />
|
||||
}
|
||||
</div>
|
||||
|
||||
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-seguimiento" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'" />
|
||||
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
|
||||
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
|
||||
</section>
|
||||
|
||||
<section id="panel-datos" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-datos" tabindex="0" [hidden]="activeSection() !== 'datos'">
|
||||
|
||||
@@ -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,38 +24,20 @@ 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; }
|
||||
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
// Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids.
|
||||
.kpi-section[data-domain='cacu'] .kpi-grid {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
|
||||
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
|
||||
background: var(--issste-surface); padding: var(--issste-space-2) var(--issste-space-2) 0;
|
||||
@@ -73,3 +55,8 @@ nav a[aria-current='page'] {
|
||||
.section-panel { padding-block: var(--issste-space-6); }
|
||||
.section-panel[hidden] { display: none; }
|
||||
@media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } }
|
||||
.graphic-navigation-trigger { transition: opacity 180ms ease; }
|
||||
.graphic-navigation-trigger-expanded { opacity: 0; pointer-events: none; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.graphic-navigation-trigger { transition: none; }
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
@@ -51,6 +52,22 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
.toEqual([]);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
|
||||
load();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
|
||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
|
||||
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de cáncer cervicouterino');
|
||||
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
|
||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
|
||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
|
||||
expect(page.activeSection()).toBe('resumen');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => {
|
||||
fixture.detectChanges();
|
||||
expect(page.catalogLoading()).toBe(true);
|
||||
@@ -74,9 +91,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true);
|
||||
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
|
||||
const summary = fixture.nativeElement.querySelector('app-indicadores-numeric-summary') as HTMLElement;
|
||||
expect(sections[1].compareDocumentPosition(summary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(summary.textContent).toContain('Resumen de indicadores');
|
||||
// Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página.
|
||||
expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados');
|
||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
|
||||
toggle(0); toggle(1); flushAll();
|
||||
@@ -112,22 +128,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';
|
||||
@@ -10,27 +10,30 @@ import { MatInputModule } from '@angular/material/input';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { ConnectedPosition, Overlay, OverlayModule } from '@angular/cdk/overlay';
|
||||
import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { indicatorIdentity } from './indicadores-identities';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
|
||||
import { IndicadoresDefinitions } from './indicadores-definitions';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
|
||||
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
|
||||
|
||||
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, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -41,8 +44,14 @@ export class IndicadoresPage {
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
setFichaPacienteAbierta(open: boolean) {
|
||||
this.fichaPacienteAbierta.set(open);
|
||||
if (open) this.closeGraphicNavigation(false, false);
|
||||
}
|
||||
changeSection(section: DashboardSection) {
|
||||
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
|
||||
if (section !== 'resumen') this.closeGraphicNavigation(false, false);
|
||||
this.activeSection.set(section);
|
||||
// Retain views, filters and Plotly hosts; only visible regions authorize loading.
|
||||
if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false);
|
||||
@@ -63,6 +72,26 @@ export class IndicadoresPage {
|
||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput');
|
||||
private readonly overlay = inject(Overlay);
|
||||
readonly navigationScrollStrategy = this.overlay.scrollStrategies.reposition();
|
||||
readonly navigationPositions: ConnectedPosition[] = [
|
||||
{ originX: 'start', originY: 'center', overlayX: 'start', overlayY: 'center' },
|
||||
{ originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'top' },
|
||||
{ originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' },
|
||||
{ originX: 'end', originY: 'center', overlayX: 'end', overlayY: 'center' },
|
||||
];
|
||||
readonly navigationOpen = signal(false);
|
||||
readonly navigationClosing = signal(false);
|
||||
readonly navigationAttached = computed(() => this.navigationOpen() || this.navigationClosing());
|
||||
readonly navigationKeyboard = signal(false);
|
||||
private readonly navigationPanel = viewChild(IndicadoresNavegacionPanel);
|
||||
private navigationHoverTimer?: ReturnType<typeof setTimeout>;
|
||||
private navigationAnimationTimer?: ReturnType<typeof setTimeout>;
|
||||
private navigationPointerInside = false;
|
||||
// Removing the overlay can generate pointerenter on the button under a stationary cursor.
|
||||
private navigationHoverDismissed = false;
|
||||
readonly navigationItems = computed<readonly IndicadorNavegacionItem[]>(() =>
|
||||
this.searchResults().items.map(item => ({ key: indicatorIdentity(this.dominio, item.id), titulo: item.titulo })));
|
||||
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
|
||||
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
|
||||
private renderedCards: readonly IndicadorCatalogCard[] = [];
|
||||
@@ -239,16 +268,43 @@ export class IndicadoresPage {
|
||||
private readonly route = inject(ActivatedRoute, { optional: true });
|
||||
readonly dominios = DOMINIOS;
|
||||
dominio: Dominio = 'tea';
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' };
|
||||
// At the start of the header line.
|
||||
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino' };
|
||||
readonly kpisByDomain = KPI_BY_DOMAIN;
|
||||
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); }
|
||||
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
||||
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
||||
kpiIndicator(id: string) {
|
||||
const published = this.catalog().find(item => item.id === id);
|
||||
if (published) return published;
|
||||
// The lab partner is deliberately hidden from some catalogs, as in the paired figure.
|
||||
// Reuse its established periodicity, without assigning the diagnosis version to lab data.
|
||||
if (this.dominio === 'cacu' && id === CACU_RESULTADO_KPI.id) {
|
||||
const diagnosis = this.catalog().find(item => item.id === 'cacu_dias_toma_diagnostico');
|
||||
if (diagnosis) return { id, titulo: CACU_RESULTADO_KPI.title, contrato: diagnosis.contrato,
|
||||
figuras: [], tipos_periodo: diagnosis.tipos_periodo };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
get opportunityKpis() {
|
||||
const definitions = this.availableKpis;
|
||||
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
|
||||
// Keep the established KPI definitions and initial-period anchor intact.
|
||||
const diagnosis = definitions.findIndex(item => item.id === 'cacu_dias_toma_diagnostico');
|
||||
return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI,
|
||||
...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)];
|
||||
}
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly searchQuery = signal('');
|
||||
readonly searchVisible = computed(() => this.catalog().length >= 5);
|
||||
readonly searchResults = computed(() => {
|
||||
const items = this.catalog();
|
||||
const catalog = this.catalog();
|
||||
// Stable presentation priority; search matches and pins still take precedence.
|
||||
const items = this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
||||
: catalog;
|
||||
const query = this.normalizeSearch(this.searchQuery());
|
||||
const prioritize = (group: Indicador[]) => [
|
||||
...group.filter(item => this.isPinned(item)),
|
||||
@@ -294,8 +350,117 @@ export class IndicadoresPage {
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
||||
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
|
||||
get showGraphicNavigation() {
|
||||
return this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading()
|
||||
&& !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0;
|
||||
}
|
||||
toggleGraphicNavigation(event?: MouseEvent) {
|
||||
if (!this.showGraphicNavigation) return;
|
||||
if (this.navigationOpen()) this.closeGraphicNavigation(false);
|
||||
else this.openGraphicNavigation(event?.detail === 0);
|
||||
}
|
||||
private openGraphicNavigation(keyboard = false) {
|
||||
if (!this.showGraphicNavigation) return;
|
||||
this.clearNavigationTimers();
|
||||
this.navigationHoverDismissed = false;
|
||||
this.navigationKeyboard.set(keyboard);
|
||||
this.navigationClosing.set(false);
|
||||
this.navigationOpen.set(true);
|
||||
if (keyboard) afterNextRender(() => {
|
||||
if (this.navigationOpen() && this.navigationKeyboard()) this.navigationPanel()?.focusFirstOption();
|
||||
}, { injector: this.injector });
|
||||
}
|
||||
navigationTriggerKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
this.openGraphicNavigation(true);
|
||||
}
|
||||
navigationPointerEnter(event: PointerEvent) {
|
||||
if (this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
|
||||
this.navigationPointerInside = true;
|
||||
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
||||
this.navigationHoverTimer = undefined;
|
||||
if (!this.navigationOpen()) this.openGraphicNavigation();
|
||||
}
|
||||
navigationPointerMove(event: PointerEvent) {
|
||||
if (!this.navigationHoverDismissed || !this.navigationCanHover(event)) return;
|
||||
this.navigationHoverDismissed = false;
|
||||
this.navigationPointerEnter(event);
|
||||
}
|
||||
private navigationCanHover(event: PointerEvent) {
|
||||
return event.pointerType === 'mouse' && this.document.defaultView?.matchMedia?.('(hover: hover) and (pointer: fine)').matches;
|
||||
}
|
||||
navigationPointerLeave(event: PointerEvent) {
|
||||
if (!this.navigationCanHover(event)) return;
|
||||
this.navigationPointerInside = false;
|
||||
this.scheduleNavigationClose();
|
||||
}
|
||||
navigationFocusOut() { this.scheduleNavigationClose(); }
|
||||
private scheduleNavigationClose() {
|
||||
if (!this.navigationOpen()) return;
|
||||
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
||||
this.navigationHoverTimer = setTimeout(() => {
|
||||
this.navigationHoverTimer = undefined;
|
||||
if (!this.navigationPointerInside && !this.navigationPanel()?.containsFocus()) this.closeGraphicNavigation(false);
|
||||
}, 230);
|
||||
}
|
||||
navigationOverlayKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
this.closeGraphicNavigation();
|
||||
}
|
||||
private clearNavigationTimers() {
|
||||
if (this.navigationHoverTimer !== undefined) clearTimeout(this.navigationHoverTimer);
|
||||
if (this.navigationAnimationTimer !== undefined) clearTimeout(this.navigationAnimationTimer);
|
||||
this.navigationHoverTimer = this.navigationAnimationTimer = undefined;
|
||||
}
|
||||
closeGraphicNavigation(restoreFocus = true, animate = true) {
|
||||
const wasOpen = this.navigationOpen();
|
||||
this.clearNavigationTimers();
|
||||
this.navigationHoverDismissed ||= wasOpen;
|
||||
this.navigationPointerInside = false;
|
||||
this.navigationKeyboard.set(false);
|
||||
this.navigationOpen.set(false);
|
||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
this.navigationClosing.set(animate && wasOpen && !reducedMotion);
|
||||
if (this.navigationClosing()) this.navigationAnimationTimer = setTimeout(() => {
|
||||
this.navigationAnimationTimer = undefined;
|
||||
this.navigationClosing.set(false);
|
||||
}, 180);
|
||||
if (wasOpen && restoreFocus && this.showGraphicNavigation) {
|
||||
this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger')?.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
closeGraphicNavigationFromOutside(event: MouseEvent) {
|
||||
const target = event.target;
|
||||
const trigger = this.element.nativeElement.querySelector<HTMLButtonElement>('.graphic-navigation-trigger');
|
||||
if (target instanceof Node && trigger?.contains(target)) return;
|
||||
this.closeGraphicNavigation(false);
|
||||
}
|
||||
selectGraphicNavigation(key: string) {
|
||||
if (!this.navigationItems().some(item => item.key === key)) {
|
||||
this.closeGraphicNavigation(false);
|
||||
return;
|
||||
}
|
||||
this.closeGraphicNavigation(false, false);
|
||||
afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
|
||||
}
|
||||
private scrollToIndicator(key: string) {
|
||||
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()
|
||||
|| !this.navigationItems().some(item => item.key === key)) return;
|
||||
const target = this.document.getElementById(identityElementId(key));
|
||||
const grid = this.element.nativeElement.querySelector('.catalog-grid');
|
||||
if (!target || !grid?.contains(target)) return;
|
||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
|
||||
target.querySelector('h2')?.focus({ preventScroll: true });
|
||||
}
|
||||
constructor() {
|
||||
afterEveryRender(() => this.syncVisibility());
|
||||
afterEveryRender(() => {
|
||||
this.syncVisibility();
|
||||
if (!this.showGraphicNavigation && (this.navigationAttached() || this.navigationHoverTimer !== undefined)) this.closeGraphicNavigation(false, false);
|
||||
});
|
||||
const browser = this.document.defaultView;
|
||||
if (typeof IntersectionObserver !== 'undefined') {
|
||||
browser?.addEventListener('scroll', this.viewportChanged, { passive: true });
|
||||
@@ -304,6 +469,7 @@ export class IndicadoresPage {
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.filtersEdited();
|
||||
this.visibilityDestroyed = true;
|
||||
this.closeGraphicNavigation(false, false);
|
||||
this.clearVisibility();
|
||||
this.sizeObserver?.disconnect();
|
||||
this.sizeTargets.clear();
|
||||
@@ -318,6 +484,7 @@ export class IndicadoresPage {
|
||||
return this.periodService.dominio(this.dominio, this.catalog());
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state));
|
||||
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
|
||||
this.closeGraphicNavigation(false, false);
|
||||
this.cancelInitialPeriod.next();
|
||||
this.initialPeriodState.set('ready');
|
||||
this.clearVisibility();
|
||||
@@ -339,6 +506,7 @@ export class IndicadoresPage {
|
||||
}
|
||||
changeDominio(dominio: Dominio) {
|
||||
if (!isDominio(dominio) || dominio === this.dominio) return;
|
||||
this.closeGraphicNavigation(false, false);
|
||||
this.activeSection.set('resumen');
|
||||
this.searchQuery.set('');
|
||||
this.filtersEdited();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
@@ -29,19 +29,30 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i])));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); }
|
||||
// Regression assertions below target the original KPI contracts. The added lab
|
||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||
function originalRequests() {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) {
|
||||
const period = r.request.params.get('periodos')!;
|
||||
r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] });
|
||||
}
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index];
|
||||
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{
|
||||
periodo: period, grupo: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
|
||||
periodo: period, grupo: d.contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, categoria: 'A',
|
||||
n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0,
|
||||
}] };
|
||||
}
|
||||
function flushDatos(domain: Dominio, suppressed = false) {
|
||||
const resolved = [];
|
||||
for (;;) {
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
const requests = originalRequests();
|
||||
if (!requests.length) return resolved;
|
||||
resolved.push(...requests);
|
||||
requests.forEach(r => {
|
||||
@@ -56,16 +67,16 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos'));
|
||||
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
|
||||
const requests = flushDatos(domain);
|
||||
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S1']);
|
||||
expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S1', '2026-S1']);
|
||||
expect(panels().map(p => p.result().value)).toEqual([4, '0.0', 0]);
|
||||
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]);
|
||||
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
|
||||
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => {
|
||||
load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2']));
|
||||
const initial = http.match(r => r.url.endsWith('/datos'));
|
||||
const initial = originalRequests();
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
expect(initial.every(r => r.cancelled)).toBe(true);
|
||||
const requests = flushDatos('cacu', true);
|
||||
@@ -89,7 +100,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador');
|
||||
expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const single = flushDatos('cacu'); expect(single).toHaveLength(3);
|
||||
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
|
||||
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
@@ -106,7 +117,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
fixture.detectChanges(); flushDatos('cacu');
|
||||
expect(fixture.componentInstance.initialPeriodState()).toBe('error');
|
||||
expect(panels()).toHaveLength(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de CaCu');
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de cáncer cervicouterino');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
const control = editor(); control.changeMode('manual'); control.select(['2025-S2']);
|
||||
expect(control.canApply).toBe(false);
|
||||
|
||||
@@ -42,8 +42,8 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea · j · g');
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, i, f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea, j, g');
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(hosts[0]);
|
||||
|
||||
@@ -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);
|
||||
@@ -139,8 +140,7 @@ describe('Datos y definiciones reutiliza metadatos sin servicios', () => {
|
||||
expect(root.textContent).not.toMatch(/WebApp|WebApi|C1|C2|C3r|Origen de la información/);
|
||||
expect(root.textContent).toContain('La información metodológica ampliada no está disponible');
|
||||
expect(root.querySelectorAll('details[open]')).toHaveLength(0);
|
||||
expect(root.textContent).toContain('Un valor nulo significa que no hay un valor disponible');
|
||||
expect(root.textContent).toContain('Los datos suprimidos tampoco representan un cero');
|
||||
expect(root.textContent).not.toContain('Interpretación y metodología');
|
||||
fixture.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -54,7 +54,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
|
||||
marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
|
||||
hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: 'Distribución estratificada · ' + period }, barmode: 'group', autosize: true,
|
||||
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
|
||||
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
|
||||
font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
|
||||
xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { figuraTiempos, modeloTiempos, PARES_TIEMPOS, parTiempos, TiemposIncompatibles } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const par = PARES_TIEMPOS.find(p => p.dominio === 'cacu')!;
|
||||
const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C3r', version: '1', figuras: ['fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] });
|
||||
const diagnostico = item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico');
|
||||
const reporte = item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado');
|
||||
const row = (periodo: string, n: number | null, q1: number | null, mediana: number | null, q3: number | null, suprimido = 0) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
||||
function datos(id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos {
|
||||
return { id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' };
|
||||
}
|
||||
const lab = () => datos(reporte.id, [row('2025-S1', 120, 7, 12, 20), row('2025-S2', 98, 6, 10, 18)]);
|
||||
const dx = () => datos(diagnostico.id, [row('2025-S1', 3, null, null, null, 1), row('2025-S2', 40, 30, 52, 90)]);
|
||||
|
||||
describe('Tiempos pareados: modelo y figura', () => {
|
||||
it('una caja por indicador y periodo; suprimidos y nulos nunca se dibujan como cero', () => {
|
||||
const m = modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre');
|
||||
expect(m.periodos).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(m.cajas.diagnostico['2025-S1']).toEqual({ estado: 'Suprimido' });
|
||||
expect(m.cajas.reporte['2025-S2']).toEqual({ estado: 'Publicado', n: 98, q1: 6, mediana: 10, q3: 18 });
|
||||
const f = figuraTiempos(m, par, 'claro');
|
||||
expect(f.layout['boxmode']).toBe('group');
|
||||
expect(f.data.map(t => t['name'])).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
|
||||
expect(f.data.map(t => t['type'])).toEqual(['box', 'box']);
|
||||
expect(f.data[0]['marker']).not.toEqual(f.data[1]['marker']);
|
||||
expect(f.data[0]['x']).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(f.data[1]['x']).toEqual(['2025-S2']);
|
||||
expect(f.data[1]).toMatchObject({ q1: [30], median: [52], q3: [90], lowerfence: [30], upperfence: [90] });
|
||||
expect(f.data[1]['customdata']).toEqual([['40', '30', '52', '90']]);
|
||||
expect(f.data[1]['hovertemplate']).toContain('n = %{customdata[0]} citologías');
|
||||
expect(f.data[1]['hovertemplate']).toContain('Mediana: %{customdata[2]} días');
|
||||
expect(JSON.stringify(f.data)).not.toContain('null');
|
||||
expect(figuraTiempos(m, par, 'oscuro').layout['paper_bgcolor']).toBe('#081839');
|
||||
});
|
||||
it('cuartiles incompletos o desordenados quedan no disponibles', () => {
|
||||
const d = datos(diagnostico.id, [row('2025-S1', 4, 5, 3, 9), row('2025-S2', 0, 0, 0, 0)]);
|
||||
const m = modeloTiempos(par, { reporte: lab(), diagnostico: d }, 'semestre');
|
||||
expect(m.cajas.diagnostico['2025-S1'].estado).toBe('No disponible');
|
||||
expect(m.cajas.diagnostico['2025-S2'].estado).toBe('No disponible');
|
||||
});
|
||||
it('rechaza datos de otro indicador, contrato, periodo o con dos totales por periodo', () => {
|
||||
expect(() => modeloTiempos(par, { reporte: dx(), diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
||||
expect(() => modeloTiempos(par, { reporte: { ...lab(), contrato: 'C1' }, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
||||
expect(() => modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre', ['2025-S2'])).toThrow(TiemposIncompatibles);
|
||||
const twice = datos(reporte.id, [row('2025-S1', 1, 1, 1, 1), row('2025-S1', 2, 2, 2, 2)]);
|
||||
expect(() => modeloTiempos(par, { reporte: twice, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
||||
});
|
||||
it('el par de CaMa existe pero solo CaCu está conectado', () => {
|
||||
expect(parTiempos('cacu', 'cacu_dias_toma_diagnostico')).toBe(par);
|
||||
expect(parTiempos('cacu', 'cacu_eu_tiempo_reporte')).toBeUndefined();
|
||||
expect(PARES_TIEMPOS.some(p => p.dominio === 'cama' && p.diagnostico === 'cama_dias_toma_diagnostico')).toBe(true);
|
||||
expect(parTiempos('cama', 'cama_dias_toma_diagnostico')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tiempos pareados: componente', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, revision: 1 };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorTiemposPareados>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorTiemposPareados, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorTiemposPareados);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('par', par);
|
||||
f.componentRef.setInput('indicador', diagnostico);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
function flush(a = lab(), b = dx()) {
|
||||
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
|
||||
const d = http.expectOne(req => req.url === '/cacu/indicadores/cacu_dias_toma_diagnostico/datos');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(d.request.params.get('periodos')).toBe(r.request.params.get('periodos'));
|
||||
r.flush(a); d.flush(b); f.detectChanges();
|
||||
}
|
||||
it('carga diferida; dos GET de los mismos periodos; una gráfica y tabla con supresión', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading'); flush();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub));
|
||||
expect(charts).toHaveLength(1);
|
||||
expect((charts[0].componentInstance as ChartStub).figure()).toBe(f.componentInstance.figure);
|
||||
const text = f.nativeElement.querySelector('table').textContent as string;
|
||||
expect(text).toContain('Suprimido'); expect(text).toContain('mediana 52');
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
||||
});
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
f.detectChanges();
|
||||
flush(datos(reporte.id, [row('2025-S1', 2, null, null, null, 1)]), datos(diagnostico.id, []));
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay cajas publicadas');
|
||||
});
|
||||
it('con filtro incompatible u otro indicador no hay GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...diagnostico, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('indicador', { ...diagnostico, contrato: 'C1' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('la pareja oculta del catálogo se pide por id; un 404 se anuncia como error, sin cajas', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos' && req.params.get('periodos') === '2025-S1,2025-S2').flush({}, { status: 404, statusText: 'Not Found' });
|
||||
http.match(req => req.url.includes('cacu_dias_toma_diagnostico'));
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('error HTTP se anuncia y el reintento vuelve a pedir', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url.includes('cacu_eu_tiempo_reporte')).flush({}, { status: 500, statusText: 'Error' });
|
||||
http.match(req => req.url.includes('cacu_dias_toma_diagnostico'));
|
||||
f.detectChanges(); expect(f.componentInstance.status()).toBe('error');
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('«Cómo leer» muestra el como_leer de las dos figuras y la advertencia de poblaciones distintas', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes');
|
||||
http.expectOne('/cacu/indicadores/cacu_eu_tiempo_reporte/metadatos').flush({ ficha: { nota: 'No va' },
|
||||
figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: null, como_leer: ['Caja del laboratorio.'] }] });
|
||||
f.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: 'Caja de diagnóstico.', como_leer: ['Lee el diagnóstico.'] }] });
|
||||
f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...help.querySelectorAll('.reading-guide h3')].map(h => h.textContent)).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Caja del laboratorio.', 'Lee el diagnóstico.']);
|
||||
expect(help.querySelector('.caveat')!.textContent).toContain('no es el tiempo del tramo intermedio');
|
||||
expect(help.textContent).not.toContain('No va'); expect(help.textContent).not.toContain('pendientes');
|
||||
});
|
||||
it('la tarjeta de CaCu sustituye el diagnóstico por la vista pareada; las demás quedan igual', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', diagnostico);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
const view = card.debugElement.query(By.directive(IndicadorTiemposPareados));
|
||||
expect(view).not.toBeNull();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, indicator] of [['cacu', reporte], ['cama', { ...diagnostico, id: 'cama_dias_toma_diagnostico' }]] as const) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', indicator); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorTiemposPareados))).toHaveLength(0);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(1);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Dominio, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
|
||||
// Two C3r indicators that share the sample date (toma) and differ in their end
|
||||
// event: the lab result and the diagnosis note. They are drawn side by side per
|
||||
// period so the slower stretch is visible. C3r publishes only Q1, median and Q3:
|
||||
// no individual observations, so boxes have no whiskers and no violin is possible.
|
||||
export interface ParTiempos {
|
||||
dominio: Dominio;
|
||||
reporte: string;
|
||||
diagnostico: string;
|
||||
estudios: string;
|
||||
etiquetas: { reporte: string; diagnostico: string };
|
||||
// Only connected pairs replace the diagnosis card in the catalog.
|
||||
conectado: boolean;
|
||||
}
|
||||
export const PARES_TIEMPOS: readonly ParTiempos[] = [
|
||||
{ dominio: 'cacu', reporte: 'cacu_eu_tiempo_reporte', diagnostico: 'cacu_dias_toma_diagnostico', estudios: 'citologías',
|
||||
etiquetas: { reporte: 'Días de toma a resultado (laboratorio)', diagnostico: 'Días de toma a diagnóstico' }, conectado: true },
|
||||
{ dominio: 'cama', reporte: 'cama_eu38a', diagnostico: 'cama_dias_toma_diagnostico', estudios: 'mastografías',
|
||||
etiquetas: { reporte: 'Días de toma a resultado', diagnostico: 'Días de toma a diagnóstico' }, conectado: false },
|
||||
];
|
||||
export function parTiempos(dominio: Dominio, id: string): ParTiempos | undefined {
|
||||
return PARES_TIEMPOS.find(par => par.conectado && par.dominio === dominio && par.diagnostico === id);
|
||||
}
|
||||
export const FIGURA_C3R = 'fig_c3r_caja';
|
||||
|
||||
export type Clave = 'reporte' | 'diagnostico';
|
||||
export const CLAVES: readonly Clave[] = ['reporte', 'diagnostico'];
|
||||
export interface Caja {
|
||||
estado: 'Publicado' | 'Suprimido' | 'No disponible';
|
||||
n?: number; q1?: number; mediana?: number; q3?: number;
|
||||
}
|
||||
export interface ModeloTiempos { periodos: string[]; cajas: Record<Clave, Record<string, Caja>>; notas: string[]; }
|
||||
export class TiemposIncompatibles extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
|
||||
|
||||
function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
if (!fila) return { estado: 'No disponible' };
|
||||
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
|
||||
const { n, q1, mediana, q3 } = fila;
|
||||
// Null quantiles are not zeros: without a complete published box nothing is drawn.
|
||||
if (fila['suprimido'] !== 0 || !conteo(n) || n === 0 || !finito(q1) || !finito(mediana) || !finito(q3)
|
||||
|| q1 < 0 || q1 > mediana || mediana > q3) return { estado: 'No disponible' };
|
||||
return { estado: 'Publicado', n, q1, mediana, q3 };
|
||||
}
|
||||
|
||||
/** Two immutable C3r /datos payloads -> boxes per period, without mixing groups or strata. */
|
||||
export function modeloTiempos(par: ParTiempos, datos: Record<Clave, IndicadorDatos>, tipo: TipoPeriodo,
|
||||
solicitados?: readonly string[]): ModeloTiempos {
|
||||
const cajas = { reporte: {}, diagnostico: {} } as Record<Clave, Record<string, Caja>>;
|
||||
for (const clave of CLAVES) {
|
||||
const d = datos[clave];
|
||||
if (d.id !== par[clave] || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length
|
||||
|| (solicitados && d.periodos.some(p => !solicitados.includes(p)))) {
|
||||
fail('Los datos de tiempos no corresponden al indicador o al periodo aplicado.');
|
||||
}
|
||||
for (const fila of d.filas) {
|
||||
if (!registro(fila) || typeof fila['periodo'] !== 'string' || !d.periodos.includes(fila['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
|
||||
if (fila['grupo'] !== 'TOTAL' || fila['estrato'] != null) continue;
|
||||
if (fila['unidad'] !== undefined && fila['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
|
||||
const periodo = fila['periodo'] as string;
|
||||
if (cajas[clave][periodo]) fail('Más de una fila total por periodo.');
|
||||
cajas[clave][periodo] = caja(fila);
|
||||
}
|
||||
for (const periodo of d.periodos) cajas[clave][periodo] ??= { estado: 'No disponible' };
|
||||
}
|
||||
const periodos = solicitados ? [...solicitados]
|
||||
: [...new Set([...datos.reporte.periodos, ...datos.diagnostico.periodos])].sort();
|
||||
for (const clave of CLAVES) for (const periodo of periodos) cajas[clave][periodo] ??= { estado: 'No disponible' };
|
||||
return { periodos, cajas, notas: [...new Set([...(datos.reporte.notas ?? []), ...(datos.diagnostico.notas ?? [])])] };
|
||||
}
|
||||
|
||||
export function hayCajas(m: ModeloTiempos): boolean {
|
||||
return CLAVES.some(clave => m.periodos.some(p => m.cajas[clave][p].estado === 'Publicado'));
|
||||
}
|
||||
|
||||
const COLORES: Record<Clave, string> = { reporte: C2_PALETTE.series[0], diagnostico: C2_PALETTE.series[2] };
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
const dias = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
|
||||
|
||||
/** Grouped boxes from published quartiles; whiskers equal the box (fences are unknown). */
|
||||
export function figuraTiempos(m: ModeloTiempos, par: ParTiempos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const data = CLAVES.map(clave => {
|
||||
const periodos = m.periodos.filter(periodo => m.cajas[clave][periodo].estado === 'Publicado');
|
||||
const cajas = periodos.map(periodo => m.cajas[clave][periodo]);
|
||||
return {
|
||||
type: 'box', name: par.etiquetas[clave], legendgroup: clave, x: periodos,
|
||||
q1: cajas.map(c => c.q1), median: cajas.map(c => c.mediana), q3: cajas.map(c => c.q3),
|
||||
lowerfence: cajas.map(c => c.q1), upperfence: cajas.map(c => c.q3),
|
||||
marker: { color: COLORES[clave] }, line: { color: COLORES[clave], width: 2 }, fillcolor: rgba(COLORES[clave], .35),
|
||||
customdata: cajas.map(c => [c.n!.toLocaleString('es-MX'), dias(c.q1!), dias(c.mediana!), dias(c.q3!)]),
|
||||
hoveron: 'boxes',
|
||||
hovertemplate: `${par.etiquetas[clave]}<br>%{x}<br>n = %{customdata[0]} ${par.estudios}`
|
||||
+ '<br>Q1: %{customdata[1]} días<br>Mediana: %{customdata[2]} días<br>Q3: %{customdata[3]} días<extra></extra>',
|
||||
};
|
||||
});
|
||||
return { data, layout: {
|
||||
boxmode: 'group', autosize: true, height: 440, showlegend: true,
|
||||
legend: { orientation: 'h', x: 0, y: 1.02, xanchor: 'left', yanchor: 'bottom' },
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 48, l: 64, r: 16, b: 56 },
|
||||
xaxis: { type: 'category', categoryorder: 'array', categoryarray: m.periodos, title: { text: 'Periodo' } },
|
||||
yaxis: { title: { text: 'días' }, rangemode: 'tozero', gridcolor: p.grid, zeroline: false },
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
export function cajaTexto(c: Caja): string {
|
||||
return c.estado !== 'Publicado' ? c.estado
|
||||
: `n = ${c.n!.toLocaleString('es-MX')}, Q1 ${dias(c.q1!)}, mediana ${dias(c.mediana!)}, Q3 ${dias(c.q3!)} días`;
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
<h2>Seguimiento · {{ domainLabel }}</h2>
|
||||
@if (pacienteDetalle.estado().tipo !== 'cerrado') {
|
||||
<app-paciente-detalle [estado]="pacienteDetalle.estado()" [categorias]="categories"
|
||||
[registrosTemporales]="pacienteDetalle.registrosTemporales()"
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
@if (dominio !== 'cacu') {
|
||||
<p>El seguimiento aún no está disponible.</p>
|
||||
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
|
||||
@@ -17,6 +23,9 @@
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||
</select></label>
|
||||
<label>Ordenar por prioridad <select name="prioridad" disabled>
|
||||
<option>No disponible</option>
|
||||
</select></label>
|
||||
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@@ -29,12 +38,12 @@
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th>Identificador seudónimo</th><th>Grupo de edad</th><th>Estatus de seguimiento</th><th>Última citología</th><th>Último resultado de VPH</th><th>Estudio más reciente</th><th>Días de toma a diagnóstico</th><th>Prioridad</th></tr></thead>
|
||||
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr>
|
||||
<td>{{ item.id_seudonimo }}</td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="item.id_seudonimo">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirPaciente(item, $event)">{{ item.id_seudonimo }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
@@ -44,8 +53,9 @@
|
||||
</div>
|
||||
<nav aria-label="Paginación de seguimiento">
|
||||
<button type="button" [disabled]="response.paginacion.page <= 1" (click)="navigate(response.paginacion.page - 1)">Anterior</button>
|
||||
<span>Página {{ response.paginacion.page }} de {{ response.paginacion.total_pages }} · {{ response.paginacion.total_items }} registros</span>
|
||||
<span>Página {{ response.paginacion.page }} de {{ response.paginacion.total_pages }}, {{ response.paginacion.total_items }} registros</span>
|
||||
<button type="button" [disabled]="response.paginacion.page >= response.paginacion.total_pages" (click)="navigate(response.paginacion.page + 1)">Siguiente</button>
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -16,3 +16,8 @@ th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px
|
||||
th { background: var(--issste-background); font-weight: 600; }
|
||||
small { display: block; margin-top: .35rem; }
|
||||
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
|
||||
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
import { ChangeDetectorRef, Component, DestroyRef, inject, Input, OnChanges } from '@angular/core';
|
||||
import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Injector, Input, OnChanges, output } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { latestStudy, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
imports: [FormsModule],
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent],
|
||||
providers: [PacienteDetalleState],
|
||||
templateUrl: './indicadores-tracking.html',
|
||||
styleUrl: './indicadores-tracking.scss',
|
||||
})
|
||||
@@ -22,6 +26,10 @@ export class IndicadoresTracking implements OnChanges {
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly injector = inject(Injector);
|
||||
readonly pacienteDetalle = inject(PacienteDetalleState);
|
||||
readonly fichaPacienteAbierta = output<boolean>();
|
||||
private controlPaciente?: HTMLElement;
|
||||
private readonly requests = new Subject<SeguimientoQuery | null>();
|
||||
private initialized = false;
|
||||
private previousDomain?: Dominio;
|
||||
@@ -61,6 +69,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
}
|
||||
ngOnChanges() {
|
||||
if (this.previousDomain !== this.dominio) {
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined;
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
}
|
||||
@@ -77,5 +87,31 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
|
||||
this.load({ ...this.applied, page });
|
||||
}
|
||||
cytologyLabel(code: string | null) { return code === null ? 'No disponible' : this.categories[code]?.etiqueta ?? code; }
|
||||
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
|
||||
if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return;
|
||||
evento.stopPropagation();
|
||||
if (evento.type === 'click' && evento.currentTarget instanceof HTMLButtonElement) {
|
||||
if (evento.currentTarget.classList.contains('patient-link')) evento.preventDefault();
|
||||
this.controlPaciente = evento.currentTarget;
|
||||
} else if (evento.type === 'click' && evento.currentTarget instanceof HTMLTableRowElement
|
||||
&& evento.target instanceof HTMLElement && !evento.target.closest('button, a, input, select, textarea')) this.controlPaciente = evento.currentTarget;
|
||||
else if (evento.type === 'click' && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||
else if (evento.type !== 'click') return;
|
||||
this.pacienteDetalle.abrir(paciente, this.data.corte);
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
const control = this.controlPaciente;
|
||||
afterNextRender(() => {
|
||||
if (control?.isConnected) control.focus({ preventScroll: true });
|
||||
}, { injector: this.injector });
|
||||
}
|
||||
// The shown cytology is the patient's latest in the window. Without a Bethesda result it is either
|
||||
// unsatisfactory (`cacu.calidad_insatisfactoria` in the kit) or not yet reported at the cut-off.
|
||||
cytologyLabel(c: { bethesda: string | null; calidad: string | null }) {
|
||||
if (c.bethesda !== null) return this.categories[c.bethesda]?.etiqueta ?? c.bethesda;
|
||||
return c.calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface Indicador {
|
||||
tipos_periodo: TipoPeriodo[];
|
||||
filtros?: IndicadorFiltro[];
|
||||
}
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento';
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado';
|
||||
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
||||
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
||||
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
||||
|
||||
@@ -48,6 +48,13 @@ describe('IndicadoresService HTTP', () => {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it('ignora parametros: ni los valida ni bloquea los metadatos aunque vengan mal formados', () => {
|
||||
let value: unknown;
|
||||
service.metadatos('cacu', 'p').subscribe(v => value = v);
|
||||
http.expectOne('/cacu/indicadores/p/metadatos').flush({ descripcion: 'Descripción', parametros: 'incorrecto' });
|
||||
expect(value).toMatchObject({ descripcion: 'Descripción' });
|
||||
});
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => {
|
||||
service.catalogo(dominio).subscribe(items => {
|
||||
expect(items).toEqual(syntheticCatalogs[dominio]);
|
||||
@@ -135,7 +142,7 @@ describe('UX-04 validación defensiva HTTP', () => {
|
||||
|
||||
describe('contrato datos exclusivo de KPI', () => {
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
|
||||
it('envía sólo periodos explícitos sin granularidad ni tema y conserva filas y notas', () => {
|
||||
it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => {
|
||||
const http = TestBed.inject(HttpTestingController); let result: unknown;
|
||||
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
|
||||
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
||||
|
||||
@@ -66,7 +66,7 @@ export class IndicadoresService {
|
||||
}
|
||||
let params = new HttpParams();
|
||||
if (scope.estrato) {
|
||||
if (!['grupo_edad', 'estatus_seguimiento'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
params = params.set('estrato', scope.estrato);
|
||||
}
|
||||
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<div role="group" [attr.aria-labelledby]="id + '-titulo'" (focusout)="salir($event)">
|
||||
<p class="etiqueta" [id]="id + '-titulo'">{{ etiqueta }}</p>
|
||||
<div class="partes">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Día</mat-label>
|
||||
<input matInput type="text" inputmode="numeric" autocomplete="off" required
|
||||
data-fecha="dia" [formControl]="partes.controls.dia" [matAutocomplete]="dias"
|
||||
[errorStateMatcher]="estadoError" [aria-describedby]="mostrarError ? id + '-error' : ''">
|
||||
<mat-autocomplete #dias="matAutocomplete">
|
||||
@for (dia of diasSugeridos; track dia) { <mat-option [value]="dia">{{ dia }}</mat-option> }
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Mes</mat-label>
|
||||
<input matInput type="text" autocomplete="off" required
|
||||
data-fecha="mes" [formControl]="partes.controls.mes" [matAutocomplete]="meses"
|
||||
[errorStateMatcher]="estadoError" [aria-describedby]="mostrarError ? id + '-error' : ''">
|
||||
<mat-autocomplete #meses="matAutocomplete">
|
||||
@for (mes of mesesSugeridos; track mes) { <mat-option [value]="mes">{{ mes }}</mat-option> }
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Año</mat-label>
|
||||
<input matInput type="text" inputmode="numeric" autocomplete="off" required
|
||||
data-fecha="anio" [formControl]="partes.controls.anio" [matAutocomplete]="anios"
|
||||
[errorStateMatcher]="estadoError" [aria-describedby]="mostrarError ? id + '-error' : ''">
|
||||
<mat-autocomplete #anios="matAutocomplete">
|
||||
@for (anio of aniosSugeridos; track anio) { <mat-option [value]="anio">{{ anio }}</mat-option> }
|
||||
</mat-autocomplete>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
@if (mostrarError) { <p class="error" [id]="id + '-error'" aria-live="polite">{{ mensajeError }}</p> }
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.etiqueta { margin: 0 0 .5rem; font-size: .875rem; font-weight: 500; }
|
||||
.partes { display: grid; grid-template-columns: minmax(0, .8fr) minmax(0, 1.6fr) minmax(0, 1fr); gap: .5rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
.error { margin: .25rem 0 0; color: var(--mat-sys-error, #ba1a1a); font-size: .75rem; }
|
||||
@media (max-width: 400px) {
|
||||
.partes { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
|
||||
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
|
||||
import { MatInputHarness } from '@angular/material/input/testing';
|
||||
import { FechaCompuesta } from './fecha-compuesta';
|
||||
|
||||
@Component({
|
||||
imports: [ReactiveFormsModule, FechaCompuesta],
|
||||
template: '<app-fecha-compuesta [formControl]="fecha" etiqueta="Fecha del estudio" /><button>Después</button>',
|
||||
})
|
||||
class FormularioFecha {
|
||||
readonly fecha = new FormControl('', { nonNullable: true, validators: [Validators.required] });
|
||||
}
|
||||
|
||||
describe('Fecha compuesta reutilizable', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<FormularioFecha>>;
|
||||
let fecha: FormControl<string>;
|
||||
let control: FechaCompuesta;
|
||||
let root: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(FormularioFecha);
|
||||
fecha = fixture.componentInstance.fecha;
|
||||
root = fixture.nativeElement;
|
||||
fixture.detectChanges();
|
||||
control = fixture.debugElement.query(By.directive(FechaCompuesta)).componentInstance;
|
||||
});
|
||||
|
||||
async function escribir(parte: string, valor: string) {
|
||||
const input = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
||||
MatInputHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
||||
await input.setValue(valor);
|
||||
}
|
||||
async function capturar(dia: string, mes: string, anio: string) {
|
||||
await escribir('dia', dia); await escribir('mes', mes); await escribir('anio', anio);
|
||||
}
|
||||
function entrada(parte: string) { return root.querySelector<HTMLInputElement>(`[data-fecha="${parte}"]`)!; }
|
||||
function tecla(input: HTMLInputElement, key: string, keyCode: number) {
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
it('empieza vacío e inválido sin errores prematuros, con etiquetas y orden día-mes-año', () => {
|
||||
expect(fecha.invalid).toBe(true);
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
expect(root.querySelector('[role="group"]')?.getAttribute('aria-labelledby')).toBe(control.id + '-titulo');
|
||||
expect(root.querySelector('#' + control.id + '-titulo')?.textContent).toContain('Fecha del estudio');
|
||||
expect(Array.from(root.querySelectorAll('input')).map(input => input.dataset['fecha'])).toEqual(['dia', 'mes', 'anio']);
|
||||
for (const parte of ['dia', 'mes', 'anio']) {
|
||||
const input = entrada(parte);
|
||||
expect(input.required).toBe(true);
|
||||
expect(input.tabIndex).toBe(0);
|
||||
expect(root.querySelector(`label[for="${input.id}"]`)?.textContent).toMatch(/Día|Mes|Año/);
|
||||
}
|
||||
});
|
||||
|
||||
it('captura manualmente sin seleccionar sugerencias y conserva ISO sin conversión horaria', async () => {
|
||||
await capturar('26', 'octubre', '2026');
|
||||
expect(fecha.valid).toBe(true);
|
||||
expect(fecha.value).toBe('2026-10-26');
|
||||
await capturar('1', '01', '0001');
|
||||
expect(fecha.value).toBe('0001-01-01');
|
||||
await capturar('31', '12', '9999');
|
||||
expect(fecha.value).toBe('9999-12-31');
|
||||
});
|
||||
|
||||
it('ofrece doce meses y filtra nombres y números sin aceptar fragmentos ambiguos', async () => {
|
||||
const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
||||
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
||||
await mes.focus();
|
||||
expect(await mes.getOptions()).toHaveLength(12);
|
||||
await mes.enterText('ma');
|
||||
expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Marzo', 'Mayo']);
|
||||
await escribir('dia', '15'); await escribir('anio', '2026');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
await mes.clear(); await mes.enterText('10');
|
||||
expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Octubre']);
|
||||
expect(fecha.value).toBe('2026-10-15');
|
||||
for (const valor of ['13', '0', 'mes desconocido', 'mar']) {
|
||||
await mes.clear(); await mes.enterText(valor);
|
||||
expect(fecha.value, valor).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('selecciona los tres componentes mediante autocompletado', async () => {
|
||||
const loader = TestbedHarnessEnvironment.loader(fixture);
|
||||
for (const [parte, valor] of [['anio', '2024'], ['mes', 'Febrero'], ['dia', '29']]) {
|
||||
const input = await loader.getHarness(MatAutocompleteHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
||||
if (parte === 'anio') await input.enterText(valor); else await input.focus();
|
||||
await input.selectOption({ text: valor });
|
||||
}
|
||||
expect(fecha.value).toBe('2024-02-29');
|
||||
expect(fecha.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('navega las sugerencias con flechas y Enter y cierra con Escape manteniendo el foco', async () => {
|
||||
const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
||||
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
||||
await mes.enterText('ma');
|
||||
tecla(entrada('mes'), 'ArrowDown', 40);
|
||||
tecla(entrada('mes'), 'ArrowDown', 40);
|
||||
tecla(entrada('mes'), 'ArrowUp', 38);
|
||||
expect(entrada('mes').getAttribute('aria-activedescendant')).toBeTruthy();
|
||||
tecla(entrada('mes'), 'Enter', 13);
|
||||
await fixture.whenStable();
|
||||
expect(await mes.getValue()).toBe('Marzo');
|
||||
expect(await mes.isOpen()).toBe(false);
|
||||
await mes.clear(); await mes.enterText('ab');
|
||||
tecla(entrada('mes'), 'Escape', 27);
|
||||
await fixture.whenStable();
|
||||
expect(await mes.isOpen()).toBe(false);
|
||||
expect(await mes.isFocused()).toBe(true);
|
||||
expect(await mes.getValue()).toBe('ab');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['31', 'Abril', '2026'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2026'],
|
||||
['29', 'Febrero', '1900'], ['0', 'Enero', '2026'], ['32', 'Enero', '2026'],
|
||||
['1.5', 'Enero', '2026'], ['1', 'Enero', '0'], ['1', 'Enero', '10000'],
|
||||
['1', 'Enero', '-1'], ['1', 'Enero', '20e2'],
|
||||
])('rechaza fecha imposible o entrada inválida %s / %s / %s', async (dia, mes, anio) => {
|
||||
await capturar(dia, mes, anio);
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['2000', '2024'])('admite 29 de febrero en el año bisiesto %s', async anio => {
|
||||
await capturar('29', 'Febrero', anio);
|
||||
expect(fecha.value).toBe(`${anio}-02-29`);
|
||||
expect(fecha.valid).toBe(true);
|
||||
});
|
||||
|
||||
it('invalida el día al cambiar mes o año sin corregirlo silenciosamente ni conservar el ISO anterior', async () => {
|
||||
await capturar('31', 'Marzo', '2024');
|
||||
expect(fecha.value).toBe('2024-03-31');
|
||||
await escribir('mes', 'Abril');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(entrada('dia').value).toBe('31');
|
||||
expect(control.diasSugeridos).toHaveLength(30);
|
||||
await capturar('29', 'Febrero', '2024');
|
||||
expect(control.diasSugeridos).toHaveLength(29);
|
||||
await escribir('anio', '2025');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
expect(entrada('dia').value).toBe('29');
|
||||
expect(control.diasSugeridos).toHaveLength(28);
|
||||
await escribir('anio', '2024');
|
||||
expect(fecha.value).toBe('2024-02-29');
|
||||
});
|
||||
|
||||
it.each(['dia', 'mes', 'anio'])('vaciar %s invalida inmediatamente una fecha previamente válida', async parte => {
|
||||
await capturar('26', 'Octubre', '2026');
|
||||
await escribir(parte, '');
|
||||
expect(fecha.value).toBe('');
|
||||
expect(fecha.invalid).toBe(true);
|
||||
});
|
||||
|
||||
it('muestra un único error asociado al salir del grupo o al solicitar validación', async () => {
|
||||
const dia = entrada('dia');
|
||||
dia.focus();
|
||||
entrada('mes').focus();
|
||||
fixture.detectChanges();
|
||||
expect(fecha.touched).toBe(false);
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
root.querySelector('button')!.focus();
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fecha.touched).toBe(true);
|
||||
expect(root.querySelectorAll('.error')).toHaveLength(1);
|
||||
for (const input of root.querySelectorAll('input')) {
|
||||
expect(input.getAttribute('aria-describedby')).toContain(control.id + '-error');
|
||||
expect(input.getAttribute('aria-required')).toBe('true');
|
||||
}
|
||||
fecha.reset(''); fixture.detectChanges();
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
fecha.markAllAsTouched(); fixture.detectChanges();
|
||||
expect(root.querySelector('.error')?.textContent).toContain('completa día, mes y año');
|
||||
await capturar('31', 'Abril', '2026');
|
||||
expect(root.querySelector('.error')?.textContent).toContain('ese día no existe');
|
||||
expect(dia.getAttribute('aria-invalid')).toBe('true');
|
||||
await escribir('dia', '30');
|
||||
expect(root.querySelector('.error')).toBeNull();
|
||||
});
|
||||
|
||||
it('acepta valores externos sin emitir cambios adicionales y no normaliza fechas inválidas', async () => {
|
||||
const cambios = vi.fn();
|
||||
fecha.valueChanges.subscribe(cambios);
|
||||
fecha.setValue('2024-02-29'); fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(cambios).toHaveBeenCalledExactlyOnceWith('2024-02-29');
|
||||
expect(entrada('dia').value).toBe('29');
|
||||
expect(entrada('mes').value).toBe('Febrero');
|
||||
expect(entrada('anio').value).toBe('2024');
|
||||
expect(fecha.valid).toBe(true);
|
||||
for (const valor of ['2026-02-30', '2026-13-01', 'ayer', '2026-1-1', '2026-10-26T00:00:00Z']) {
|
||||
fecha.setValue(valor); fixture.detectChanges();
|
||||
expect(fecha.value).toBe(valor);
|
||||
expect(fecha.invalid).toBe(true);
|
||||
}
|
||||
fecha.reset(''); fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(Array.from(root.querySelectorAll('input')).every(input => input.value === '')).toBe(true);
|
||||
});
|
||||
|
||||
it('propaga disabled y permite años históricos y futuros sin listas enormes', async () => {
|
||||
fecha.disable(); fixture.detectChanges();
|
||||
expect(Array.from(root.querySelectorAll('input')).every(input => input.disabled)).toBe(true);
|
||||
fecha.enable(); fixture.detectChanges();
|
||||
for (const anio of ['0001', '1500', '2100', '9999']) {
|
||||
await capturar('1', 'Enero', anio);
|
||||
expect(fecha.value).toBe(`${anio}-01-01`);
|
||||
expect(fecha.valid).toBe(true);
|
||||
expect(control.aniosSugeridos.length).toBeLessThanOrEqual(7);
|
||||
expect(control.aniosSugeridos).toContain(anio);
|
||||
expect(control.aniosSugeridos.every(opcion => Number(opcion) >= 1 && Number(opcion) <= 9999)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { AfterViewInit, ChangeDetectorRef, Component, DestroyRef, ElementRef, Injector, Input, OnInit, forwardRef, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, NgControl, ReactiveFormsModule, ValidationErrors, Validator } from '@angular/forms';
|
||||
import { MatAutocompleteModule } from '@angular/material/autocomplete';
|
||||
import { ErrorStateMatcher } from '@angular/material/core';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { esFechaReal } from './paciente-registro.validation';
|
||||
|
||||
const MESES = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
|
||||
'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
|
||||
let siguienteId = 0;
|
||||
|
||||
/** Tres entradas editables; el formulario recibe exclusivamente ISO de calendario o vacío. */
|
||||
@Component({
|
||||
selector: 'app-fecha-compuesta',
|
||||
imports: [ReactiveFormsModule, MatAutocompleteModule, MatFormFieldModule, MatInputModule],
|
||||
templateUrl: './fecha-compuesta.html',
|
||||
styleUrl: './fecha-compuesta.scss',
|
||||
providers: [
|
||||
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => FechaCompuesta), multi: true },
|
||||
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => FechaCompuesta), multi: true },
|
||||
],
|
||||
})
|
||||
export class FechaCompuesta implements ControlValueAccessor, Validator, OnInit, AfterViewInit {
|
||||
@Input() etiqueta = 'Fecha';
|
||||
readonly id = `fecha-compuesta-${siguienteId++}`;
|
||||
readonly partes = new FormGroup({
|
||||
dia: new FormControl('', { nonNullable: true }),
|
||||
mes: new FormControl('', { nonNullable: true }),
|
||||
anio: new FormControl('', { nonNullable: true }),
|
||||
});
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private readonly cdr = inject(ChangeDetectorRef);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private ngControl: NgControl | null = null;
|
||||
private visitado = false;
|
||||
private entradaExternaInvalida = false;
|
||||
private onChange: (valor: string) => void = () => {};
|
||||
private onTouched: () => void = () => {};
|
||||
readonly estadoError: ErrorStateMatcher = { isErrorState: () => this.mostrarError };
|
||||
|
||||
constructor() {
|
||||
this.partes.valueChanges.pipe(takeUntilDestroyed(this.destroy)).subscribe(() => {
|
||||
this.entradaExternaInvalida = false;
|
||||
// Emitir también al invalidarse: nunca conservar la última fecha válida.
|
||||
this.onChange(this.fechaIso);
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
// Resolver después de crear los providers CVA/Validator evita una dependencia circular.
|
||||
this.ngControl = this.injector.get(NgControl, null, { self: true });
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
// FormControlName ya está conectado al FormGroup al terminar de crear la vista.
|
||||
// markAllAsTouched/reset del formulario también deben refrescar el grupo con OnPush.
|
||||
this.ngControl?.control?.events.pipe(takeUntilDestroyed(this.destroy))
|
||||
.subscribe(() => this.cdr.markForCheck());
|
||||
}
|
||||
|
||||
private numero(valor: string, digitos: number): number | null {
|
||||
const texto = valor.trim();
|
||||
return new RegExp(`^\\d{1,${digitos}}$`).test(texto) ? Number(texto) : null;
|
||||
}
|
||||
|
||||
private get mesNumero(): number | null {
|
||||
const texto = this.partes.controls.mes.value.trim().toLocaleLowerCase('es');
|
||||
const numero = this.numero(texto, 2);
|
||||
if (numero !== null) return numero >= 1 && numero <= 12 ? numero : null;
|
||||
const indice = MESES.findIndex(mes => mes.toLocaleLowerCase('es') === texto);
|
||||
return indice >= 0 ? indice + 1 : null;
|
||||
}
|
||||
|
||||
get mesesSugeridos(): string[] {
|
||||
const texto = this.partes.controls.mes.value.trim().toLocaleLowerCase('es');
|
||||
const numero = this.numero(texto, 2);
|
||||
if (numero !== null) return numero >= 1 && numero <= 12 ? [MESES[numero - 1]] : [];
|
||||
return MESES.filter(mes => mes.toLocaleLowerCase('es').includes(texto));
|
||||
}
|
||||
|
||||
get diasSugeridos(): string[] {
|
||||
const mes = String(this.mesNumero ?? 1).padStart(2, '0');
|
||||
const numeroAnio = this.numero(this.partes.controls.anio.value, 4);
|
||||
// Sin año válido se ofrece el máximo de febrero; completar el año vuelve a validar.
|
||||
const anio = String(numeroAnio || 2000).padStart(4, '0');
|
||||
return Array.from({ length: 31 }, (_, i) => String(i + 1))
|
||||
.filter(dia => esFechaReal(`${anio}-${mes}-${dia.padStart(2, '0')}`));
|
||||
}
|
||||
|
||||
get aniosSugeridos(): string[] {
|
||||
const escrito = this.numero(this.partes.controls.anio.value, 4);
|
||||
const centro = escrito && escrito <= 9999 ? escrito : new Date().getFullYear();
|
||||
return Array.from({ length: 7 }, (_, i) => centro - 3 + i)
|
||||
.filter(anio => anio >= 1 && anio <= 9999).map(anio => String(anio).padStart(4, '0'));
|
||||
}
|
||||
|
||||
private get fechaIso(): string {
|
||||
const { dia, anio } = this.partes.getRawValue();
|
||||
const d = this.numero(dia, 2);
|
||||
const m = this.mesNumero;
|
||||
const a = this.numero(anio, 4);
|
||||
if (d === null || m === null || a === null) return '';
|
||||
const fecha = `${String(a).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
|
||||
return esFechaReal(fecha) ? fecha : '';
|
||||
}
|
||||
|
||||
get mensajeError(): string {
|
||||
if (this.entradaExternaInvalida) return 'Ingresa una fecha real de calendario.';
|
||||
const { dia, mes, anio } = this.partes.getRawValue();
|
||||
if (![dia, mes, anio].every(valor => valor.trim())) return 'Ingresa una fecha válida: completa día, mes y año.';
|
||||
if (this.mesNumero === null) return 'Escribe el nombre completo del mes o un número del 1 al 12.';
|
||||
const a = this.numero(anio, 4);
|
||||
if (a === null || a < 1) return 'Ingresa un año entre 0001 y 9999.';
|
||||
if (!this.fechaIso) return 'Ingresa una fecha real: ese día no existe en el mes y año indicados.';
|
||||
return '';
|
||||
}
|
||||
|
||||
get mostrarError(): boolean {
|
||||
return !this.partes.disabled && !!this.mensajeError && (this.ngControl?.touched ?? this.visitado);
|
||||
}
|
||||
|
||||
salir(event: FocusEvent) {
|
||||
if (!this.host.nativeElement.contains(event.relatedTarget as Node | null)) {
|
||||
this.visitado = true;
|
||||
this.onTouched();
|
||||
}
|
||||
}
|
||||
|
||||
writeValue(valor: unknown): void {
|
||||
const coincidencia = typeof valor === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(valor) : null;
|
||||
this.entradaExternaInvalida = !!valor && !esFechaReal(valor);
|
||||
this.visitado = false;
|
||||
this.partes.reset(coincidencia ? {
|
||||
dia: coincidencia[3], mes: MESES[Number(coincidencia[2]) - 1] ?? coincidencia[2], anio: coincidencia[1],
|
||||
} : { dia: '', mes: '', anio: '' }, { emitEvent: false });
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
registerOnChange(fn: (valor: string) => void): void { this.onChange = fn; }
|
||||
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
|
||||
setDisabledState(deshabilitado: boolean): void {
|
||||
if (deshabilitado) this.partes.disable({ emitEvent: false });
|
||||
else this.partes.enable({ emitEvent: false });
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
validate(control: AbstractControl): ValidationErrors | null {
|
||||
return esFechaReal(control.value) && this.fechaIso === control.value ? null : { fechaCompuesta: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { PacienteDetalle } from './paciente-detalle.models';
|
||||
|
||||
// Explicit demonstration identities only. Never derive a history from age, status or a hash.
|
||||
export const PACIENTES_DETALLE_SINTETICOS: readonly PacienteDetalle[] = [
|
||||
{
|
||||
id_seudonimo: 'P-4BC9B9E8F4',
|
||||
origen: 'sintetico',
|
||||
historial: [{ descripcion: 'Antecedente de tamizaje cervical (demostración)', fecha: '2025-06-12', notas: null }],
|
||||
procedimientos: [],
|
||||
pruebas: [{ nombre: 'Citología previa (demostración)', fecha: '2025-06-12', resultado: 'Negativa para lesión intraepitelial' }],
|
||||
},
|
||||
{
|
||||
id_seudonimo: 'P-2C9E494F5D',
|
||||
origen: 'sintetico',
|
||||
historial: null,
|
||||
procedimientos: [{ nombre: 'Colposcopia (demostración)', fecha: '2026-06-10', resultado: null }],
|
||||
pruebas: [{ nombre: 'Histopatología (demostración)', fecha: null, resultado: null }],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,85 @@
|
||||
@if (estado.tipo !== 'cerrado') {
|
||||
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
|
||||
<header>
|
||||
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.id_seudonimo }}</h2>
|
||||
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
|
||||
<dl class="summary">
|
||||
<div><dt>Identificador seudónimo</dt><dd>{{ estado.resumen.id_seudonimo }}</dd></div>
|
||||
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Prioridad</dt><dd>{{ estado.resumen.prioridad ?? 'No disponible' }}</dd></div>
|
||||
</dl>
|
||||
</header>
|
||||
@if (estado.tipo === 'cargando') { <p role="status">Cargando información…</p> }
|
||||
@if (estado.tipo === 'no-disponible') { <p class="availability" role="status">Información no disponible.</p> }
|
||||
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Seguimiento para intentar de nuevo.</p> }
|
||||
@if (registrosTemporales.length) { <p class="pending-changes" role="status">Cambios sin guardar</p> }
|
||||
<div class="detail-grid">
|
||||
<mat-card class="history-card" appearance="outlined" aria-labelledby="historial-title">
|
||||
<mat-card-header><h3 id="historial-title">Historial médico relevante</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<div class="history-actions">
|
||||
<button mat-stroked-button type="button" (click)="abrirRegistro('condicion')">Agregar condición</button>
|
||||
<button mat-stroked-button type="button" (click)="abrirRegistro('procedimiento')">Agregar procedimiento</button>
|
||||
</div>
|
||||
<div class="history-table-scroll" role="region" aria-label="Historial médico relevante" tabindex="0">
|
||||
<table class="history-table">
|
||||
<thead><tr><th scope="col">Registro</th><th scope="col">Fecha</th></tr></thead>
|
||||
<tbody>
|
||||
<tr class="section-row"><th scope="rowgroup" colspan="2">Condiciones</th></tr>
|
||||
@if (estado.tipo === 'disponible') {
|
||||
@if (estado.detalle.historial; as historial) {
|
||||
@for (item of historial; track $index) {
|
||||
<tr><td><strong>{{ item.descripcion }}</strong>@if (item.notas) { <span class="record-detail">{{ item.notas }}</span> }</td><td>{{ item.fecha ?? 'No disponible' }}</td></tr>
|
||||
}
|
||||
@if (!historial.length && !temporales('condicion').length) { <tr><td colspan="2" class="empty-row">Sin registros.</td></tr> }
|
||||
} @else if (!temporales('condicion').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
} @else if (!temporales('condicion').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
@for (item of temporales('condicion'); track item.id) {
|
||||
<tr data-registro-temporal="condicion"><td><strong>{{ etiquetaRegistro(item) }}</strong><span class="record-detail">Agregado en esta sesión</span></td><td>{{ item.fecha }}</td></tr>
|
||||
}
|
||||
<tr class="section-row"><th scope="rowgroup" colspan="2">Procedimientos</th></tr>
|
||||
@if (estado.tipo === 'disponible') {
|
||||
@if (estado.detalle.procedimientos; as procedimientos) {
|
||||
@for (item of procedimientos; track $index) {
|
||||
<tr><td><strong>{{ item.nombre }}</strong>@if (item.resultado) { <span class="record-detail">Resultado: {{ item.resultado }}</span> }</td><td>{{ item.fecha ?? 'No disponible' }}</td></tr>
|
||||
}
|
||||
@if (!procedimientos.length && !temporales('procedimiento').length) { <tr><td colspan="2" class="empty-row">Sin registros.</td></tr> }
|
||||
} @else if (!temporales('procedimiento').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
} @else if (!temporales('procedimiento').length) { <tr><td colspan="2" class="empty-row">Información no disponible.</td></tr> }
|
||||
@for (item of temporales('procedimiento'); track item.id) {
|
||||
<tr data-registro-temporal="procedimiento"><td><strong>{{ etiquetaRegistro(item) }}</strong><span class="record-detail">Agregado en esta sesión</span></td><td>{{ item.fecha }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="tests-card" appearance="outlined" aria-labelledby="pruebas-title">
|
||||
<mat-card-header><h3 id="pruebas-title">Pruebas y resultados</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<button mat-stroked-button type="button" (click)="abrirRegistro('resultado')">Agregar resultado</button>
|
||||
<h4>Últimos resultados</h4>
|
||||
<ul>
|
||||
<li><strong>Última citología</strong>@if (estado.resumen.citologia; as c) { <span>Fecha: {{ c.fecha }}</span><span>Resultado: {{ etiquetaCitologia(c.resultado, c.calidad) }}</span><span>Calidad: {{ c.calidad ?? 'No disponible' }}</span> } @else { <span>No disponible</span> }</li>
|
||||
<li><strong>Último resultado de VPH</strong>@if (estado.resumen.vph; as v) { <span>Fecha: {{ v.fecha }}</span><span>Resultado: {{ v.resultado }}</span><span>Genotipo 16/18: {{ v.genotipo16y18 === null ? 'No disponible' : v.genotipo16y18 ? 'Presente' : 'No detectado' }}</span> } @else { <span>No disponible</span> }</li>
|
||||
</ul>
|
||||
@if (estado.tipo === 'disponible') {
|
||||
<h4>Pruebas adicionales</h4>
|
||||
@if (estado.detalle.pruebas; as pruebas) {
|
||||
<ul>@for (item of pruebas; track $index) { <li><strong>{{ item.nombre }}</strong><span>Fecha: {{ item.fecha ?? 'No disponible' }}</span><span>Resultado: {{ item.resultado ?? 'No disponible' }}</span></li> } @empty { <li>Sin registros.</li> }</ul>
|
||||
} @else { <p>Información no disponible.</p> }
|
||||
}
|
||||
@if (estado.tipo === 'disponible' || temporales('resultado').length) {
|
||||
<h4>Resultados agregados</h4>
|
||||
<ul>@for (item of temporales('resultado'); track item.id) { <li data-registro-temporal="resultado"><strong>{{ etiquetaRegistro(item) }}</strong><span>Fecha: {{ item.fecha }}</span><span>Resultado: {{ etiquetaResultado(item) }}</span></li> } @empty { <li>Sin registros.</li> }</ul>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
|
||||
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content><app-paciente-riesgo-tabla /></mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
/** Snapshot of the received row, independent of the Seguimiento transport contract. */
|
||||
export interface PacienteResumen {
|
||||
id_seudonimo: string;
|
||||
grupoEdad: string | null;
|
||||
estatus: string | null;
|
||||
corte: string;
|
||||
origen: 'seguimiento-demostracion';
|
||||
citologia: { fecha: string; resultado: string | null; calidad: string | null } | null;
|
||||
vph: { fecha: string; resultado: string; genotipo16y18: boolean | null } | null;
|
||||
diasTomaDiagnostico: number | null;
|
||||
prioridad: string | null;
|
||||
}
|
||||
|
||||
export interface AntecedenteDetalle { descripcion: string; fecha: string | null; notas?: string | null; }
|
||||
export interface ProcedimientoDetalle { nombre: string; fecha: string | null; resultado?: string | null; }
|
||||
export interface PruebaDetalle { nombre: string; fecha: string | null; resultado: string | null; }
|
||||
|
||||
/** null = unavailable collection; [] = no entries supplied, never proof of clinical absence. */
|
||||
export interface PacienteDetalle {
|
||||
id_seudonimo: string;
|
||||
origen: 'sintetico';
|
||||
historial: AntecedenteDetalle[] | null;
|
||||
procedimientos: ProcedimientoDetalle[] | null;
|
||||
pruebas: PruebaDetalle[] | null;
|
||||
}
|
||||
|
||||
export interface PacienteDetalleProvider {
|
||||
obtener(idSeudonimo: string): Observable<PacienteDetalle | null>;
|
||||
}
|
||||
|
||||
export type PacienteDetalleEstado =
|
||||
| { tipo: 'cerrado' }
|
||||
| { tipo: 'cargando' | 'no-disponible' | 'error'; resumen: PacienteResumen }
|
||||
| { tipo: 'disponible'; resumen: PacienteResumen; detalle: PacienteDetalle };
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable, InjectionToken, inject } from '@angular/core';
|
||||
import { defer, of } from 'rxjs';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalleProvider } from './paciente-detalle.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PacienteDetalleMockProvider implements PacienteDetalleProvider {
|
||||
obtener(idSeudonimo: string) {
|
||||
return defer(() => {
|
||||
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo);
|
||||
// Each read owns its data; consumers cannot mutate another selection or the fixtures.
|
||||
return of(detalle ? structuredClone(detalle) : null);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const PACIENTE_DETALLE_PROVIDER = new InjectionToken<PacienteDetalleProvider>('PacienteDetalleProvider', {
|
||||
providedIn: 'root',
|
||||
factory: () => inject(PacienteDetalleMockProvider),
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
:host { display: block; min-width: 0; color: var(--issste-text); overflow-wrap: anywhere; }
|
||||
header { margin-block: 1.5rem; }
|
||||
h2 { margin-block: .5rem 1rem; font-size: 1.65rem; }
|
||||
h3 { margin-block: 0 1rem; font-size: 1.2rem; }
|
||||
h4 { font: inherit; font-weight: 600; }
|
||||
.back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; }
|
||||
.back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; }
|
||||
.availability { margin-block: .75rem; color: var(--issste-text-secondary); }
|
||||
.pending-changes { margin-block: .75rem; color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; }
|
||||
dt { color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
dd { margin: .4rem 0 0; font-weight: 600; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "history tests" "risks risks"; gap: 1rem; align-items: start; }
|
||||
mat-card { min-width: 0; background: var(--issste-surface); color: inherit; border-color: var(--issste-border); }
|
||||
.history-card { grid-area: history; }
|
||||
.tests-card { grid-area: tests; }
|
||||
.risks-card { grid-area: risks; }
|
||||
.history-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.history-table-scroll { width: 100%; min-width: 0; max-width: 100%; overflow-x: auto; margin-top: .75rem; border: 1px solid var(--issste-border); border-radius: .5rem; }
|
||||
.history-table-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.history-table { width: 100%; min-width: 26rem; border-collapse: separate; border-spacing: 0; text-align: start; }
|
||||
.history-table th, .history-table td { padding: .7rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); }
|
||||
.history-table thead th { color: var(--issste-text-secondary); font-size: .9rem; font-weight: 600; }
|
||||
.history-table thead th:last-child, .history-table td:last-child { width: 9rem; white-space: nowrap; }
|
||||
.history-table .section-row th { text-align: start; background: color-mix(in srgb, var(--issste-surface), var(--issste-border) 24%); font-weight: 600; }
|
||||
.history-table .empty-row { color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.record-detail { display: block; margin-top: .35rem; color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.risks-card mat-card-content { min-width: 0; }
|
||||
ul { list-style: none; padding: 0; }
|
||||
li { padding-block: .75rem; border-top: 1px solid var(--issste-border); }
|
||||
li span { display: block; margin-top: .4rem; }
|
||||
button { min-height: 44px; color: var(--issste-text); border-color: var(--issste-border); }
|
||||
@media (max-width: 48rem) {
|
||||
.detail-grid { grid-template-columns: minmax(0, 1fr); grid-template-areas: "history" "tests" "risks"; }
|
||||
.history-table { min-width: 22rem; }
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { Subject, of, throwError } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cacu_seguimiento.json';
|
||||
import { seguimientoResponse } from '../cacu-seguimiento.service';
|
||||
import { IndicadoresTracking } from '../indicadores-tracking';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.models';
|
||||
import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider';
|
||||
import { PacienteDetalleState } from './paciente-detalle.state';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
|
||||
const pacientes = seguimientoResponse(fixtureData).items;
|
||||
|
||||
describe('Proveedor de detalle sintético', () => {
|
||||
it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => {
|
||||
const provider = TestBed.inject(PacienteDetalleMockProvider);
|
||||
const id = pacientes[0].id_seudonimo;
|
||||
provider.obtener(id).subscribe(detalle => expect(detalle?.id_seudonimo).toBe(id));
|
||||
for (const desconocido of ['001', '1', id.toLowerCase(), ` ${id}`, 'sin-ficha', 'toString']) {
|
||||
provider.obtener(desconocido).subscribe(detalle => expect(detalle).toBeNull());
|
||||
}
|
||||
});
|
||||
|
||||
it('aísla lecturas y conserva nulos, colecciones vacías y propiedades ausentes', () => {
|
||||
const provider = TestBed.inject(PacienteDetalleMockProvider);
|
||||
provider.obtener(pacientes[0].id_seudonimo).subscribe(detalle => {
|
||||
expect(detalle?.procedimientos).toEqual([]);
|
||||
expect(detalle?.historial?.[0].notas).toBeNull();
|
||||
detalle!.historial![0].descripcion = 'mutación local';
|
||||
});
|
||||
provider.obtener(pacientes[0].id_seudonimo).subscribe(detalle => {
|
||||
expect(detalle?.historial?.[0].descripcion).not.toBe('mutación local');
|
||||
});
|
||||
provider.obtener(pacientes[1].id_seudonimo).subscribe(detalle => {
|
||||
expect(detalle?.historial).toBeNull();
|
||||
expect(detalle?.procedimientos?.[0].resultado).toBeNull();
|
||||
expect(Object.hasOwn(detalle!.procedimientos![0], 'notas')).toBe(false);
|
||||
expect(detalle?.pruebas?.[0].fecha).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Estado de selección del paciente', () => {
|
||||
function setup(provider: PacienteDetalleProvider) {
|
||||
TestBed.configureTestingModule({ providers: [PacienteDetalleState, { provide: PACIENTE_DETALLE_PROVIDER, useValue: provider }] });
|
||||
return TestBed.inject(PacienteDetalleState);
|
||||
}
|
||||
|
||||
it('entrega el seudónimo sin conversión y toma una instantánea independiente de la fila', () => {
|
||||
const obtener = vi.fn(() => of(null));
|
||||
const state = setup({ obtener });
|
||||
const paciente = { ...pacientes[0], id_seudonimo: '001', ultimo_vph: { ...pacientes[0].ultimo_vph! }, dias_toma_diagnostico: 0 };
|
||||
state.abrir(paciente, fixtureData.corte);
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('001');
|
||||
paciente.ultimo_vph.resultado = 'cambio posterior';
|
||||
const estado = state.estado();
|
||||
expect(estado.tipo).toBe('no-disponible');
|
||||
if (estado.tipo !== 'cerrado') {
|
||||
expect(estado.resumen.id_seudonimo).toBe('001');
|
||||
expect(estado.resumen.vph?.resultado).toBe('NEGATIVO');
|
||||
expect(estado.resumen.vph?.genotipo16y18).toBeNull();
|
||||
expect(estado.resumen.diasTomaDiagnostico).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('descarta respuestas tardías de otro paciente y al regresar a la lista', () => {
|
||||
const a = new Subject<PacienteDetalle | null>();
|
||||
const b = new Subject<PacienteDetalle | null>();
|
||||
const state = setup({ obtener: id => id === pacientes[0].id_seudonimo ? a : b });
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(state.estado().tipo).toBe('cargando');
|
||||
state.abrir(pacientes[1], fixtureData.corte);
|
||||
a.next(PACIENTES_DETALLE_SINTETICOS[0]);
|
||||
expect(state.estado().tipo).toBe('cargando');
|
||||
b.next(PACIENTES_DETALLE_SINTETICOS[1]);
|
||||
let estado = state.estado();
|
||||
expect(estado.tipo).toBe('disponible');
|
||||
if (estado.tipo === 'disponible') expect(estado.detalle.id_seudonimo).toBe(pacientes[1].id_seudonimo);
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
state.cerrar();
|
||||
a.next(PACIENTES_DETALLE_SINTETICOS[0]);
|
||||
expect(state.estado()).toEqual({ tipo: 'cerrado' });
|
||||
});
|
||||
|
||||
it('no presenta detalles devueltos para un seudónimo distinto', () => {
|
||||
const state = setup({ obtener: () => of(PACIENTES_DETALLE_SINTETICOS[1]) });
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(state.estado().tipo).toBe('error');
|
||||
expect(state.estado()).not.toHaveProperty('detalle');
|
||||
});
|
||||
|
||||
it('mantiene el resumen ante un error del proveedor, sin exponer datos internos', () => {
|
||||
const state = setup({ obtener: () => throwError(() => new Error('private')) });
|
||||
state.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(state.estado().tipo).toBe('error');
|
||||
expect(JSON.stringify(state.estado())).not.toContain('private');
|
||||
state.cerrar();
|
||||
expect(state.estado().tipo).toBe('cerrado');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>;
|
||||
let http: HttpTestingController;
|
||||
let root: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresTracking);
|
||||
root = fixture.nativeElement;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('domainLabel', 'CaCu');
|
||||
fixture.componentRef.setInput('active', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento').flush(fixtureData);
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: { NORMAL: { etiqueta: 'Normal' } } });
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
|
||||
function accion(index = 0) { return root.querySelectorAll<HTMLButtonElement>('tbody button.patient-link')[index]; }
|
||||
function abrir(index = 0) { accion(index).click(); fixture.detectChanges(); return root.querySelector<HTMLElement>('app-paciente-detalle')!; }
|
||||
function volver() { root.querySelector<HTMLButtonElement>('app-paciente-detalle button')!.click(); fixture.detectChanges(); }
|
||||
|
||||
it('abre por acción nativa accesible, enfoca la ficha y restaura el foco sin HTTP adicional', () => {
|
||||
const button = accion();
|
||||
expect(button.type).toBe('button');
|
||||
expect(button.getAttribute('aria-label')).toBe(`Ver ficha del paciente ${pacientes[0].id_seudonimo}`);
|
||||
const focus = vi.spyOn(button, 'focus');
|
||||
const detail = abrir();
|
||||
expect(detail.querySelector('h2')?.textContent).toContain(pacientes[0].id_seudonimo);
|
||||
expect(detail.querySelector('h2')).toBe(document.activeElement);
|
||||
expect(root.querySelector('form')!.closest('[hidden]')).not.toBeNull();
|
||||
expect(detail.textContent).not.toMatch(/Datos de demostración|información adicional sintética|solo existen en memoria|no representan un expediente clínico real/i);
|
||||
expect(Array.from(detail.querySelectorAll('h3')).map(h => h.textContent)).toEqual([
|
||||
'Historial médico relevante', 'Pruebas y resultados', 'Riesgos y recomendaciones',
|
||||
]);
|
||||
expect(detail.querySelectorAll('.history-card')).toHaveLength(1);
|
||||
expect(detail.querySelectorAll('.history-card table thead th')).toHaveLength(2);
|
||||
expect(Array.from(detail.querySelectorAll('.history-card table thead th'), th => th.textContent?.trim())).toEqual(['Registro', 'Fecha']);
|
||||
expect(Array.from(detail.querySelectorAll('.history-card .section-row th'), th => th.textContent?.trim())).toEqual(['Condiciones', 'Procedimientos']);
|
||||
expect(detail.querySelector('.history-card button')?.textContent).toContain('Agregar condición');
|
||||
expect(Array.from(detail.querySelectorAll('.history-card button'), button => button.textContent?.trim())).toEqual(['Agregar condición', 'Agregar procedimiento']);
|
||||
expect(detail.querySelector('.history-card')!.compareDocumentPosition(detail.querySelector('.tests-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(detail.querySelector('.tests-card')!.compareDocumentPosition(detail.querySelector('.risks-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(detail.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(detail.querySelectorAll('app-paciente-riesgo-tabla table')).toHaveLength(0);
|
||||
expect(detail.textContent).not.toContain('Valores ilustrativos');
|
||||
volver();
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
expect(root.querySelector('form')!.closest('[hidden]')).toBeNull();
|
||||
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('abre desde otras celdas y devuelve el foco a la fila; mantiene el seudónimo enfocable', () => {
|
||||
const row = root.querySelectorAll<HTMLTableRowElement>('tbody tr[data-paciente]')[1];
|
||||
const control = accion(1);
|
||||
expect(control.tabIndex).toBe(0);
|
||||
expect(control.getAttribute('aria-label')).toContain(pacientes[1].id_seudonimo);
|
||||
row.cells[1].click();
|
||||
fixture.detectChanges();
|
||||
const estado = fixture.componentInstance.pacienteDetalle.estado();
|
||||
expect(estado.tipo).toBe('disponible');
|
||||
if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo);
|
||||
volver();
|
||||
expect(row).toBe(document.activeElement);
|
||||
http.expectNone(() => true);
|
||||
expect(row.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it('conserva filtros aplicados, borrador, página, filas y desplazamiento de tabla al volver', () => {
|
||||
const component = fixture.componentInstance;
|
||||
component.draft = { corte: '2026-09-30', meses: 6, estatus: 'VIGILANCIA', page: 1, page_size: 10 };
|
||||
component.apply();
|
||||
const response = { ...fixtureData, ventana: { ...fixtureData.ventana, meses: 6 }, filtros: { estatus: 'VIGILANCIA' } };
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento').flush(response);
|
||||
component.navigate(2);
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...response, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
||||
fixture.detectChanges();
|
||||
component.draft.meses = 12;
|
||||
const table = root.querySelector<HTMLElement>('.tracking-table')!;
|
||||
table.scrollLeft = 200;
|
||||
const row = root.querySelector('tbody tr');
|
||||
abrir(); volver();
|
||||
expect(component.draft.meses).toBe(12);
|
||||
expect(component.draft.estatus).toBe('VIGILANCIA');
|
||||
expect(component.data?.paginacion.page).toBe(2);
|
||||
expect(root.querySelector('tbody tr')).toBe(row);
|
||||
expect(root.querySelector('.tracking-table')).toBe(table);
|
||||
expect(table.scrollLeft).toBe(200);
|
||||
http.expectNone(() => true);
|
||||
component.navigate(3);
|
||||
const request = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(request.request.params.get('meses')).toBe('6');
|
||||
expect(request.request.params.get('estatus')).toBe('VIGILANCIA');
|
||||
expect(request.request.params.get('page')).toBe('3');
|
||||
request.flush({ ...response, paginacion: { ...fixtureData.paginacion, page: 3 } });
|
||||
});
|
||||
|
||||
it('muestra ausencia de ficha sin asignar a otro paciente los antecedentes anteriores', () => {
|
||||
expect(abrir().textContent).toContain('Antecedente de tamizaje cervical');
|
||||
const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
|
||||
volver();
|
||||
const detail = abrir(2);
|
||||
expect(detail.textContent).toContain(pacientes[2].id_seudonimo);
|
||||
expect(detail.textContent).toContain('Información no disponible');
|
||||
expect((detail.textContent.match(/Información no disponible/g) ?? [])).toHaveLength(3);
|
||||
expect(detail.textContent).not.toContain('Antecedente de tamizaje cervical');
|
||||
expect(detail.textContent).not.toContain('Colposcopia (demostración)');
|
||||
expect(detail.textContent).toContain('Normal'); // Received study is still available.
|
||||
expect(detail.textContent).not.toContain('ficha sintética');
|
||||
expect(detail.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
|
||||
expect(detail.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
expect(detail.querySelectorAll('app-paciente-riesgo-tabla [aria-selected]')).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('organiza condiciones y procedimientos en una sola tabla y conserva los datos iniciales', () => {
|
||||
let detail = abrir();
|
||||
const historial = detail.querySelector('.history-card table')!;
|
||||
expect(historial.querySelectorAll('.section-row')).toHaveLength(2);
|
||||
expect(Array.from(historial.querySelectorAll('tbody tr'), row => row.textContent?.trim()).join(' ')).toContain('Antecedente de tamizaje cervical (demostración)');
|
||||
expect(Array.from(historial.querySelectorAll('tbody tr'), row => row.textContent?.trim()).join(' ')).toContain('2025-06-12');
|
||||
expect(historial.querySelectorAll('[data-registro-temporal]')).toHaveLength(0);
|
||||
volver();
|
||||
|
||||
detail = abrir(1);
|
||||
const rows = Array.from(detail.querySelectorAll('.history-card table tbody tr'));
|
||||
const procedure = rows.find(row => row.textContent?.includes('Colposcopia (demostración)'))!;
|
||||
expect(procedure.textContent).toContain('2026-06-10');
|
||||
expect(procedure.previousElementSibling?.querySelector('th')?.textContent).toBe('Procedimientos');
|
||||
expect(detail.querySelectorAll('.history-card')).toHaveLength(1);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => {
|
||||
const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
|
||||
const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
|
||||
try {
|
||||
const detail = abrir();
|
||||
const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!;
|
||||
expect(tarjeta.textContent).toContain('Información simulada');
|
||||
expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
|
||||
expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith();
|
||||
volver();
|
||||
const otra = abrir(1);
|
||||
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally { obtener.mockRestore(); }
|
||||
});
|
||||
|
||||
it('distingue fuentes, nulos, falsos, ceros y listas sin registros sin inferir condiciones', () => {
|
||||
let detail = abrir();
|
||||
expect(detail.textContent).toContain('Últimos resultados');
|
||||
expect(detail.textContent).toContain('Pruebas adicionales');
|
||||
expect(detail.textContent).toContain('Genotipo 16/18: No disponible');
|
||||
expect(detail.textContent).toContain('Sin registros');
|
||||
volver();
|
||||
detail = abrir(1);
|
||||
expect(detail.textContent).toContain('Información no disponible');
|
||||
expect(detail.textContent).toContain('Resultado: No disponible');
|
||||
expect(detail.textContent).not.toContain('Antecedente de tamizaje cervical');
|
||||
volver();
|
||||
detail = abrir(5);
|
||||
expect(detail.textContent).toContain('Genotipo 16/18: No detectado');
|
||||
expect(detail.textContent).toContain('Insatisfactoria');
|
||||
expect(detail.textContent).not.toMatch(/undefined|null/);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('conserva la selección al cambiar de pestaña y la limpia al cambiar de dominio', () => {
|
||||
abrir();
|
||||
fixture.componentRef.setInput('active', false); fixture.detectChanges();
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
expect(root.querySelector('app-paciente-detalle h2')?.textContent).toContain(pacientes[0].id_seudonimo);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.detectChanges();
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
||||
expect(root.querySelector('tbody button')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('no selecciona filas ajenas a la respuesta vigente', () => {
|
||||
fixture.componentInstance.abrirPaciente({ ...pacientes[0] }, { currentTarget: accion() } as unknown as Event);
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { Subject, catchError, defer, map, of, switchMap } from 'rxjs';
|
||||
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
|
||||
import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models';
|
||||
import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider';
|
||||
import { AltaRegistroTemporal } from './paciente-registro.models';
|
||||
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
|
||||
|
||||
/** Selección por instancia de Seguimiento; las altas temporales viven aparte en la sesión Angular. */
|
||||
@Injectable()
|
||||
export class PacienteDetalleState {
|
||||
private readonly provider = inject(PACIENTE_DETALLE_PROVIDER);
|
||||
private readonly sesion = inject(PacienteRegistrosSesion);
|
||||
private readonly seleccion = new Subject<PacienteResumen | null>();
|
||||
private readonly actual = signal<PacienteDetalleEstado>({ tipo: 'cerrado' });
|
||||
readonly estado = this.actual.asReadonly();
|
||||
readonly registrosTemporales = computed(() => {
|
||||
const estado = this.actual();
|
||||
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo);
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.seleccion.pipe(
|
||||
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe(
|
||||
map(detalle => {
|
||||
if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) {
|
||||
throw new Error('Detalle incompatible con la selección');
|
||||
}
|
||||
return detalle
|
||||
? { tipo: 'disponible', resumen, detalle } as const
|
||||
: { tipo: 'no-disponible', resumen } as const;
|
||||
}),
|
||||
catchError(() => of({ tipo: 'error', resumen } as const)),
|
||||
) : of({ tipo: 'cerrado' } as const)),
|
||||
takeUntilDestroyed(inject(DestroyRef)),
|
||||
).subscribe(estado => this.actual.set(estado));
|
||||
}
|
||||
|
||||
abrir(paciente: SeguimientoPaciente, corte: string) {
|
||||
const resumen: PacienteResumen = {
|
||||
id_seudonimo: paciente.id_seudonimo,
|
||||
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
|
||||
estatus: paciente.estatus.etiqueta,
|
||||
corte,
|
||||
origen: 'seguimiento-demostracion',
|
||||
citologia: paciente.ultima_citologia ? {
|
||||
fecha: paciente.ultima_citologia.fecha,
|
||||
resultado: paciente.ultima_citologia.bethesda,
|
||||
calidad: paciente.ultima_citologia.calidad,
|
||||
} : null,
|
||||
vph: paciente.ultimo_vph ? {
|
||||
fecha: paciente.ultimo_vph.fecha,
|
||||
resultado: paciente.ultimo_vph.resultado,
|
||||
genotipo16y18: paciente.ultimo_vph.genotipo_16_18,
|
||||
} : null,
|
||||
diasTomaDiagnostico: paciente.dias_toma_diagnostico,
|
||||
prioridad: paciente.prioridad?.etiqueta ?? null,
|
||||
};
|
||||
this.actual.set({ tipo: 'cargando', resumen });
|
||||
this.seleccion.next(resumen);
|
||||
}
|
||||
|
||||
cerrar() { this.seleccion.next(null); }
|
||||
|
||||
agregarRegistro(alta: AltaRegistroTemporal) {
|
||||
const estado = this.actual();
|
||||
if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false;
|
||||
return this.sesion.agregar(alta.id_seudonimo, alta.registro);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { AfterViewInit, Component, DestroyRef, ElementRef, inject, Input, OnDestroy, ViewChild, output } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { PacienteDetalleEstado } from './paciente-detalle.models';
|
||||
import { PacienteRegistroDialog } from './paciente-registro-dialog';
|
||||
import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
|
||||
import { etiquetaRegistro, etiquetaResultado } from './paciente-registros-sesion';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-detalle',
|
||||
imports: [MatButtonModule, MatCardModule, MatDialogModule, MatIconModule, PacienteRiesgoTabla],
|
||||
templateUrl: './paciente-detalle.html',
|
||||
styleUrl: './paciente-detalle.scss',
|
||||
})
|
||||
export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
|
||||
@Input({ required: true }) estado: PacienteDetalleEstado = { tipo: 'cerrado' };
|
||||
@Input() categorias: Record<string, { etiqueta: string }> = {};
|
||||
@Input() registrosTemporales: readonly RegistroTemporal[] = [];
|
||||
readonly volver = output<void>();
|
||||
readonly registroAgregado = output<AltaRegistroTemporal>();
|
||||
readonly etiquetaRegistro = etiquetaRegistro;
|
||||
readonly etiquetaResultado = etiquetaResultado;
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private dialogoActivo?: MatDialogRef<PacienteRegistroDialog, NuevoRegistroTemporal>;
|
||||
@ViewChild('titulo') private titulo?: ElementRef<HTMLElement>;
|
||||
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
|
||||
ngOnDestroy() { this.dialogoActivo?.close(); }
|
||||
|
||||
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
|
||||
|
||||
abrirRegistro(tipo: TipoRegistroTemporal) {
|
||||
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
|
||||
const id_seudonimo = this.estado.resumen.id_seudonimo;
|
||||
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; id_seudonimo: string }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
|
||||
data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
|
||||
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false,
|
||||
});
|
||||
this.dialogoActivo = ref;
|
||||
ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => {
|
||||
this.dialogoActivo = undefined;
|
||||
if (registro) this.registroAgregado.emit({ id_seudonimo, registro });
|
||||
});
|
||||
}
|
||||
etiquetaCitologia(resultado: string | null, calidad: string | null) {
|
||||
if (resultado !== null) return this.categorias[resultado]?.etiqueta ?? resultado;
|
||||
return calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<h2 mat-dialog-title>{{ titulo }}</h2>
|
||||
<form [formGroup]="form" (ngSubmit)="agregar()">
|
||||
<mat-dialog-content>
|
||||
<p>Paciente {{ data.id_seudonimo }}</p>
|
||||
<div class="fields">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>{{ etiquetaTipo }}</mat-label>
|
||||
<mat-select formControlName="seleccion" required>
|
||||
@for (opcion of tipos; track opcion.valor) {
|
||||
<mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
@if (form.controls.seleccion.hasError('required')) { <mat-error>Selecciona una opción.</mat-error> }
|
||||
@else { <mat-error>Selecciona una opción válida.</mat-error> }
|
||||
</mat-form-field>
|
||||
@if (data.tipo === 'resultado') {
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Resultado</mat-label>
|
||||
<mat-select formControlName="resultado" required>
|
||||
@for (opcion of resultados; track opcion.valor) {
|
||||
<mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>Selecciona primero el tipo de estudio.</mat-hint>
|
||||
@if (form.controls.resultado.hasError('required')) { <mat-error>Selecciona un resultado para este estudio.</mat-error> }
|
||||
@else { <mat-error>El resultado no corresponde al estudio seleccionado.</mat-error> }
|
||||
</mat-form-field>
|
||||
}
|
||||
<app-fecha-compuesta formControlName="fecha" [etiqueta]="etiquetaFecha" />
|
||||
</div>
|
||||
</mat-dialog-content>
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" [mat-dialog-close]="undefined">Cancelar</button>
|
||||
<button mat-flat-button type="submit" [disabled]="form.invalid">Agregar</button>
|
||||
</mat-dialog-actions>
|
||||
</form>
|
||||
@@ -0,0 +1,5 @@
|
||||
:host { display: block; color: var(--issste-text); }
|
||||
.fields { display: grid; gap: 1.25rem; margin-block: 1.5rem .75rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
button { min-height: 44px; }
|
||||
mat-dialog-actions { gap: .5rem; flex-wrap: wrap; }
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Component, DestroyRef, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { FechaCompuesta } from './fecha-compuesta';
|
||||
import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO, esOpcion, opciones } from './paciente-registro.catalogos';
|
||||
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
|
||||
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
|
||||
|
||||
export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; }
|
||||
|
||||
const opcionValida = (catalogo: Readonly<Record<string, string>>): ValidatorFn =>
|
||||
control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true };
|
||||
const fechaValida: ValidatorFn = control => !control.value || esFechaReal(control.value) ? null : { fecha: true };
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-registro-dialog',
|
||||
imports: [ReactiveFormsModule, MatDialogModule, MatButtonModule, MatFormFieldModule, MatSelectModule, FechaCompuesta],
|
||||
templateUrl: './paciente-registro-dialog.html',
|
||||
styleUrl: './paciente-registro-dialog.scss',
|
||||
})
|
||||
export class PacienteRegistroDialog {
|
||||
readonly data = inject<RegistroDialogData>(MAT_DIALOG_DATA);
|
||||
private readonly dialogRef = inject<MatDialogRef<PacienteRegistroDialog, NuevoRegistroTemporal>>(MatDialogRef);
|
||||
readonly titulo = this.data.tipo === 'condicion' ? 'Agregar condición'
|
||||
: this.data.tipo === 'procedimiento' ? 'Agregar procedimiento' : 'Agregar resultado';
|
||||
readonly etiquetaTipo = this.data.tipo === 'condicion' ? 'Tipo de condición'
|
||||
: this.data.tipo === 'procedimiento' ? 'Tipo de procedimiento' : 'Tipo de estudio';
|
||||
readonly etiquetaFecha = this.data.tipo === 'condicion' ? 'Fecha de inicio'
|
||||
: this.data.tipo === 'procedimiento' ? 'Fecha del procedimiento' : 'Fecha del estudio';
|
||||
private readonly catalogo = this.data.tipo === 'condicion' ? CONDICIONES_DEMO
|
||||
: this.data.tipo === 'procedimiento' ? PROCEDIMIENTOS_DEMO : ESTUDIOS_DEMO;
|
||||
readonly tipos = opciones(this.catalogo);
|
||||
resultados: ReturnType<typeof opciones> = [];
|
||||
readonly form = new FormGroup({
|
||||
seleccion: new FormControl('', { nonNullable: true, validators: [Validators.required, opcionValida(this.catalogo)] }),
|
||||
fecha: new FormControl('', { nonNullable: true, validators: [Validators.required, fechaValida] }),
|
||||
resultado: new FormControl({ value: '', disabled: true }, { nonNullable: true }),
|
||||
});
|
||||
private enviado = false;
|
||||
|
||||
constructor() {
|
||||
if (this.data.tipo === 'resultado') {
|
||||
this.form.controls.seleccion.valueChanges.pipe(takeUntilDestroyed(inject(DestroyRef))).subscribe(estudio => {
|
||||
const catalogo = esOpcion(ESTUDIOS_DEMO, estudio) ? RESULTADOS_DEMO[estudio] : null;
|
||||
this.resultados = catalogo ? opciones(catalogo) : [];
|
||||
const resultado = this.form.controls.resultado;
|
||||
resultado.reset('');
|
||||
resultado.setValidators([Validators.required, opcionValida(catalogo ?? {})]);
|
||||
if (catalogo) resultado.enable(); else resultado.disable();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
agregar() {
|
||||
this.form.markAllAsTouched();
|
||||
if (this.enviado || this.form.invalid) return;
|
||||
const { seleccion, fecha, resultado } = this.form.getRawValue();
|
||||
const registro = crearRegistroTemporal(this.data.tipo, seleccion, fecha, resultado);
|
||||
if (!registro) return;
|
||||
this.enviado = true;
|
||||
this.dialogRef.close(registro);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { EnvironmentInjector, createEnvironmentInjector } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
|
||||
import { MatSelectHarness } from '@angular/material/select/testing';
|
||||
import { MatInputHarness } from '@angular/material/input/testing';
|
||||
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cacu_seguimiento.json';
|
||||
import { seguimientoResponse } from '../cacu-seguimiento.service';
|
||||
import { IndicadoresTracking } from '../indicadores-tracking';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalleState } from './paciente-detalle.state';
|
||||
import { PacienteRegistroDialog } from './paciente-registro-dialog';
|
||||
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
|
||||
import { TipoRegistroTemporal } from './paciente-registro.models';
|
||||
|
||||
const pacientes = seguimientoResponse(fixtureData).items;
|
||||
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
|
||||
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
|
||||
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
|
||||
{ tipo: 'resultado', texto: 'Agregar resultado', opcion: 'VPH', resultado: 'VPH no detectado' },
|
||||
];
|
||||
|
||||
describe('Altas de demostración desde la ficha de Seguimiento', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>;
|
||||
let root: HTMLElement;
|
||||
let http: HttpTestingController;
|
||||
let dialog: MatDialog;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
dialog = TestBed.inject(MatDialog);
|
||||
montarTracking();
|
||||
});
|
||||
|
||||
function montarTracking() {
|
||||
fixture = TestBed.createComponent(IndicadoresTracking);
|
||||
root = fixture.nativeElement;
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('active', true);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cacu/seguimiento' && r.method === 'GET').flush(fixtureData);
|
||||
http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/metadatos' && r.method === 'GET').flush({});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
dialog.closeAll();
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
});
|
||||
|
||||
function abrir(index = 0) {
|
||||
root.querySelectorAll<HTMLButtonElement>('tbody button')[index].click();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function volver() {
|
||||
root.querySelector<HTMLButtonElement>('app-paciente-detalle > button')!.click();
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function boton(texto: string) {
|
||||
return Array.from(root.querySelectorAll<HTMLButtonElement>('app-paciente-detalle button')).find(b => b.textContent?.trim() === texto)!;
|
||||
}
|
||||
async function abrirDialogo(texto: string) {
|
||||
const origen = boton(texto);
|
||||
origen.focus(); origen.click();
|
||||
expect(dialog.openDialogs).toHaveLength(1);
|
||||
const ref = dialog.openDialogs[0];
|
||||
const abierto = firstValueFrom(ref.afterOpened());
|
||||
fixture.detectChanges();
|
||||
await abierto;
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-labelledby')).toBeTruthy();
|
||||
expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-describedby')).toBeNull();
|
||||
expect(document.querySelector('[role="dialog"]')?.contains(document.activeElement)).toBe(true);
|
||||
return { ref, origen };
|
||||
}
|
||||
async function confirmar() {
|
||||
const ref = dialog.openDialogs[0];
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.click();
|
||||
await cerrado;
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
}
|
||||
|
||||
async function capturarFecha(dia: string, mes: string, anio: string) {
|
||||
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
|
||||
for (const [parte, valor] of [['dia', dia], ['mes', mes], ['anio', anio]]) {
|
||||
const input = await loader.getHarness(MatInputHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
||||
await input.setValue(valor);
|
||||
}
|
||||
}
|
||||
|
||||
for (const accion of acciones) {
|
||||
it(`abre, valida y confirma «${accion.texto}» sin HTTP y restaura el foco`, async () => {
|
||||
const inicial = JSON.stringify(PACIENTES_DETALLE_SINTETICOS);
|
||||
const resumen = JSON.stringify(fixture.componentInstance.data);
|
||||
abrir();
|
||||
const { origen } = await abrirDialogo(accion.texto);
|
||||
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
|
||||
const tipo = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="seleccion"]' }));
|
||||
await tipo.clickOptions({ text: accion.opcion });
|
||||
if (accion.resultado) {
|
||||
const resultado = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="resultado"]' }));
|
||||
await resultado.clickOptions({ text: accion.resultado });
|
||||
}
|
||||
await capturarFecha('26', 'Octubre', '2026');
|
||||
expect(document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(false);
|
||||
await confirmar();
|
||||
const registro = root.querySelector(`[data-registro-temporal="${accion.tipo}"]`)!;
|
||||
expect(registro.textContent).toContain(accion.opcion);
|
||||
expect(registro.textContent).toContain('2026-10-26');
|
||||
expect(root.querySelectorAll(`[data-registro-temporal="${accion.tipo}"]`)).toHaveLength(1);
|
||||
if (accion.tipo !== 'resultado') {
|
||||
expect(registro.closest('.history-card table')).not.toBeNull();
|
||||
let encabezado = registro.previousElementSibling;
|
||||
while (encabezado && !encabezado.classList.contains('section-row')) encabezado = encabezado.previousElementSibling;
|
||||
expect(encabezado?.textContent?.trim()).toBe(accion.tipo === 'condicion' ? 'Condiciones' : 'Procedimientos');
|
||||
} else {
|
||||
expect(registro.closest('.tests-card')).not.toBeNull();
|
||||
}
|
||||
expect(root.textContent).toContain('Cambios sin guardar');
|
||||
expect(document.activeElement).toBe(origen);
|
||||
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
|
||||
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
|
||||
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
|
||||
expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo);
|
||||
expect(almacenado.origen).toBe('sesion-demostracion');
|
||||
expect(almacenado.fecha).toBe('2026-10-26');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it(`cancela «${accion.texto}» sin guardar el borrador`, async () => {
|
||||
abrir();
|
||||
const { ref, origen } = await abrirDialogo(accion.texto);
|
||||
(ref.componentInstance as PacienteRegistroDialog).form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia');
|
||||
await capturarFecha('26', 'Octubre', '2026');
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog button[type="button"]')!.click();
|
||||
expect(await cerrado).toBeUndefined();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
|
||||
expect(root.querySelector('[data-registro-temporal]')).toBeNull();
|
||||
expect(document.activeElement).toBe(origen);
|
||||
await abrirDialogo(accion.texto);
|
||||
expect((dialog.openDialogs[0].componentInstance as PacienteRegistroDialog).form.controls.seleccion.value).toBe('');
|
||||
expect(Array.from(document.querySelectorAll<HTMLInputElement>('app-fecha-compuesta input')).every(input => input.value === '')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it(`bloquea fechas incompletas e imposibles en «${accion.texto}» y admite corregirlas`, async () => {
|
||||
abrir();
|
||||
const { ref } = await abrirDialogo(accion.texto);
|
||||
const component = ref.componentInstance as PacienteRegistroDialog;
|
||||
component.form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia');
|
||||
if (accion.tipo === 'resultado') component.form.controls.resultado.setValue('negativo');
|
||||
for (const partes of [['29', 'Febrero', ''], ['31', 'Abril', '2024'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2025']]) {
|
||||
await capturarFecha(partes[0], partes[1], partes[2]);
|
||||
expect(component.form.controls.fecha.value).toBe('');
|
||||
expect(document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(true);
|
||||
component.agregar();
|
||||
expect(dialog.openDialogs).toHaveLength(1);
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
|
||||
}
|
||||
await capturarFecha('29', '2', '2024');
|
||||
expect(component.form.controls.fecha.value).toBe('2024-02-29');
|
||||
await confirmar();
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()[0].fecha).toBe('2024-02-29');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it(`Escape cierra las sugerencias de «${accion.texto}» antes de permitir cancelar el diálogo`, async () => {
|
||||
abrir();
|
||||
const { ref, origen } = await abrirDialogo(accion.texto);
|
||||
const mes = await TestbedHarnessEnvironment.documentRootLoader(fixture).getHarness(
|
||||
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
||||
await mes.enterText('ma');
|
||||
expect(await mes.isOpen()).toBe(true);
|
||||
const input = document.querySelector<HTMLInputElement>('[data-fecha="mes"]')!;
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(await mes.isOpen()).toBe(false);
|
||||
expect(dialog.openDialogs).toHaveLength(1);
|
||||
expect(document.activeElement).toBe(input);
|
||||
expect(input.value).toBe('ma');
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
// Con las sugerencias cerradas, Escape conserva la cancelación habitual del modal.
|
||||
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
|
||||
expect(await cerrado).toBeUndefined();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(document.activeElement).toBe(origen);
|
||||
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
}
|
||||
|
||||
it('permite Escape y cierra el diálogo si se abandona la ficha sin confirmar', async () => {
|
||||
abrir();
|
||||
const { ref } = await abrirDialogo('Agregar condición');
|
||||
const cerrado = firstValueFrom(ref.afterClosed());
|
||||
document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true }));
|
||||
expect(await cerrado).toBeUndefined();
|
||||
fixture.detectChanges();
|
||||
const otro = await abrirDialogo('Agregar resultado');
|
||||
const destruido = firstValueFrom(otro.ref.afterClosed());
|
||||
volver();
|
||||
expect(await destruido).toBeUndefined();
|
||||
expect(TestBed.inject(PacienteRegistrosSesion).paraPaciente(pacientes[0].id_seudonimo)).toEqual([]);
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => {
|
||||
abrir(2);
|
||||
const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
|
||||
expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
expect(riesgoNoDisponible).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('Información no disponible');
|
||||
for (const tipo of acciones) {
|
||||
const { ref } = await abrirDialogo(tipo.texto);
|
||||
const form = (ref.componentInstance as PacienteRegistroDialog).form;
|
||||
form.patchValue({ seleccion: tipo.tipo === 'condicion' ? 'lesion_cervical' : tipo.tipo === 'procedimiento' ? 'escision_cervical' : 'histologia', fecha: '2026-10-26' });
|
||||
if (tipo.tipo === 'resultado') form.controls.resultado.setValue('nic1');
|
||||
fixture.detectChanges();
|
||||
await confirmar();
|
||||
}
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
|
||||
expect(root.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
volver(); abrir(0);
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0);
|
||||
volver(); abrir(2);
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
|
||||
volver();
|
||||
fixture.destroy(); // La navegación puede desmontar Seguimiento; la aplicación sigue viva.
|
||||
montarTracking(); abrir(2);
|
||||
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('no sustituye la última citología o VPH ni modifica el resumen, prioridades o datos recibidos', async () => {
|
||||
const inicial = structuredClone(fixture.componentInstance.data);
|
||||
abrir();
|
||||
const resumen = structuredClone(fixture.componentInstance.pacienteDetalle.estado());
|
||||
const { ref } = await abrirDialogo('Agregar resultado');
|
||||
const form = (ref.componentInstance as PacienteRegistroDialog).form;
|
||||
form.patchValue({ seleccion: 'vph', fecha: '2026-10-26' });
|
||||
form.controls.resultado.setValue('positivo_16_18');
|
||||
fixture.detectChanges(); await confirmar();
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado()).toEqual(resumen);
|
||||
expect(fixture.componentInstance.data).toEqual(inicial);
|
||||
expect(root.textContent).toContain('Último resultado de VPH');
|
||||
expect(root.textContent).toContain('NEGATIVO');
|
||||
expect(root.textContent).toContain('VPH 16/18 detectado');
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vida de la selección y de la memoria de sesión', () => {
|
||||
it('sobrevive a nuevas instancias de selección y rechaza altas de una ficha anterior', () => {
|
||||
const parent = TestBed.inject(EnvironmentInjector);
|
||||
const crear = () => createEnvironmentInjector([PacienteDetalleState], parent);
|
||||
const primero = crear();
|
||||
const segundo = crear();
|
||||
try {
|
||||
const a = primero.get(PacienteDetalleState);
|
||||
const b = segundo.get(PacienteDetalleState);
|
||||
a.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
|
||||
a.cerrar();
|
||||
expect(a.registrosTemporales()).toEqual([]);
|
||||
primero.destroy();
|
||||
b.abrir(pacientes[0], fixtureData.corte);
|
||||
expect(b.registrosTemporales()).toHaveLength(1);
|
||||
b.abrir(pacientes[1], fixtureData.corte);
|
||||
expect(b.registrosTemporales()).toEqual([]);
|
||||
expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
|
||||
} finally {
|
||||
if (!primero.destroyed) primero.destroy();
|
||||
segundo.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Opciones exclusivamente sintéticas de demostración; no son una clasificación clínica validada. */
|
||||
export const CONDICIONES_DEMO = {
|
||||
embarazo: 'Embarazo',
|
||||
lesion_cervical: 'Lesión cervical',
|
||||
antecedente_cacu: 'Antecedente de cáncer cervicouterino',
|
||||
inmunosupresion: 'Inmunosupresión',
|
||||
} as const;
|
||||
|
||||
export const PROCEDIMIENTOS_DEMO = {
|
||||
colposcopia: 'Colposcopia',
|
||||
escision_cervical: 'Escisión cervical',
|
||||
ablacion_cervical: 'Ablación cervical',
|
||||
histerectomia: 'Histerectomía',
|
||||
} as const;
|
||||
|
||||
export const ESTUDIOS_DEMO = {
|
||||
vph: 'VPH',
|
||||
citologia: 'Citología cervical',
|
||||
histologia: 'Histología cervical',
|
||||
} as const;
|
||||
|
||||
export const RESULTADOS_DEMO = {
|
||||
vph: {
|
||||
negativo: 'VPH no detectado',
|
||||
positivo_16_18: 'VPH 16/18 detectado',
|
||||
positivo_otro: 'Otro VPH de alto riesgo detectado',
|
||||
},
|
||||
citologia: {
|
||||
negativa: 'Negativa para lesión intraepitelial',
|
||||
asc_us: 'ASC-US',
|
||||
lsil: 'Lesión intraepitelial de bajo grado (LSIL)',
|
||||
hsil: 'Lesión intraepitelial de alto grado (HSIL)',
|
||||
insatisfactoria: 'Muestra insatisfactoria',
|
||||
},
|
||||
histologia: {
|
||||
sin_lesion: 'Sin lesión en la muestra',
|
||||
nic1: 'NIC 1',
|
||||
nic2: 'NIC 2',
|
||||
nic3: 'NIC 3',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type TipoCondicionDemo = keyof typeof CONDICIONES_DEMO;
|
||||
export type TipoProcedimientoDemo = keyof typeof PROCEDIMIENTOS_DEMO;
|
||||
export type TipoEstudioDemo = keyof typeof ESTUDIOS_DEMO;
|
||||
|
||||
export function esOpcion<T extends object>(catalogo: T, valor: unknown): valor is Extract<keyof T, string> {
|
||||
return typeof valor === 'string' && Object.hasOwn(catalogo, valor);
|
||||
}
|
||||
|
||||
export function opciones(catalogo: Readonly<Record<string, string>>) {
|
||||
return Object.entries(catalogo).map(([valor, etiqueta]) => ({ valor, etiqueta }));
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user