Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c076e1e7a9 | |||
| 710790b98e | |||
| d16804d416 | |||
| 05a55a673e | |||
| e803c38acf | |||
| 6009aea83e | |||
| 502fc969f0 | |||
| 612a11fa6f | |||
| 8b7dd6ec19 | |||
| 59ce79d1a2 | |||
| e13e727de3 | |||
| 67cde017fa | |||
| 8c3e41527c | |||
| 3aba7fe329 | |||
| 739bf9613c | |||
| 987bce0d93 | |||
| eaaffa9ebe | |||
| 088d9d4550 | |||
| e5ff3427c7 | |||
| 0bf1f82366 | |||
| edd6e4b640 | |||
| 3674a43587 | |||
| 27bd4d4a65 | |||
| cbae29bc24 | |||
| 35b329e235 | |||
| 7f303d1160 | |||
| e2b307abf5 | |||
| 39974b8533 | |||
| 53edec8692 | |||
| a1ea31039e | |||
| ef631e2c0b | |||
| 27dc7a0166 | |||
| e6353f9f4c | |||
| 3bb9c2121d | |||
| 737c6f9f14 | |||
| 8e543cbcc6 | |||
| ea7aad5067 | |||
| 09b52e6b0a | |||
| 078db53ae4 | |||
| 957f4cd024 | |||
| 1ce8d98663 | |||
| 1771cb7ec6 | |||
| b74f188b15 | |||
| 5196f20e47 | |||
| 5d4cd6f654 | |||
| a05717f92d | |||
| 123232592f | |||
| 2cbb994667 |
@@ -30,6 +30,17 @@ describe('App', () => {
|
|||||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('an indicators page shows the platform title and a menu named after its domain', async () => {
|
||||||
|
// Fails if the header stops naming the domain or offers the current one among the others.
|
||||||
|
const page = await render('/indicadores/cama');
|
||||||
|
expect(page.querySelector('.platform-title')?.textContent).toContain('Plataforma de Indicadores');
|
||||||
|
expect(page.querySelector('.domain-selector')?.textContent).toContain('Cáncer de mama');
|
||||||
|
(page.querySelector('.domain-selector') as HTMLButtonElement).click();
|
||||||
|
const options = Array.from(document.querySelectorAll('.mat-mdc-menu-panel a')).map(a => a.textContent?.trim());
|
||||||
|
expect(options).toEqual(['TEA', 'CaCu']);
|
||||||
|
expect(page.querySelector('.site-header__crumb')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||||
const page = await render('/conectar');
|
const page = await render('/conectar');
|
||||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
|
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number;
|
||||||
|
// Filters a list announces in `filtros_disponibles`, by key.
|
||||||
|
filtros?: Record<string, string>; }
|
||||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||||
export interface SeguimientoPaciente {
|
export interface SeguimientoPaciente {
|
||||||
id_seudonimo: string;
|
id_seudonimo: string;
|
||||||
|
|||||||
@@ -16,11 +16,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
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(); }
|
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||||
it('prioridad deshabilitada con una sola opción y sin parámetros nuevos al consultar o paginar', () => {
|
it('sin selector de prioridad ni filtros de TEA, y sin parámetros nuevos al consultar o paginar', () => {
|
||||||
respond();
|
respond();
|
||||||
const select = fixture.nativeElement.querySelector('select[name="prioridad"]') as HTMLSelectElement;
|
expect(fixture.nativeElement.querySelector('select[name="prioridad"]')).toBeNull();
|
||||||
expect(select.disabled).toBe(true); expect(select.labels?.[0].textContent).toContain('Ordenar por prioridad');
|
expect(fixture.nativeElement.querySelector('select[name="mchat"]')).toBeNull();
|
||||||
expect(Array.from(select.options).map(o => o.text)).toEqual(['No disponible']);
|
|
||||||
const order = fixture.componentInstance.data!.items.map(i => i.id_seudonimo);
|
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);
|
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||||
fixture.componentInstance.apply();
|
fixture.componentInstance.apply();
|
||||||
@@ -92,14 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
|||||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||||
});
|
});
|
||||||
it('tea conserva su estado pendiente sin consultas de pacientes', () => {
|
|
||||||
const dominio = 'tea';
|
|
||||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
|
||||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
|
||||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
|
||||||
});
|
|
||||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||||
const service=TestBed.inject(CacuSeguimientoService);
|
const service=TestBed.inject(CacuSeguimientoService);
|
||||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing';
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { MatSelect } from '@angular/material/select';
|
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
@@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||||
}
|
}
|
||||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
|
||||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); }
|
||||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||||
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); }
|
||||||
@@ -38,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
|
||||||
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
|
||||||
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
// The card doesn't count its figures; the figures themselves show what is published.
|
||||||
|
expect(fixture.nativeElement.textContent).not.toContain('figuras publicadas');
|
||||||
// The internal panel heading is deliberately visually hidden and retains identity.
|
// The internal panel heading is deliberately visually hidden and retains identity.
|
||||||
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
|
||||||
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
|
||||||
@@ -47,13 +46,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
expect(fixture.componentInstance.indicador.contrato).toBe(contrato);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => {
|
it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => {
|
||||||
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']);
|
||||||
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges();
|
||||||
expect(select().options.map(option => [option.value, option.viewValue])).toEqual([
|
|
||||||
['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'],
|
|
||||||
['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'],
|
|
||||||
]);
|
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
open(); request('fig_c1_grupos').flush({ data: [], layout: {} });
|
||||||
for (const [id, label] of [
|
for (const [id, label] of [
|
||||||
@@ -62,7 +57,7 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
['fig_c2_donas', 'Donas'],
|
['fig_c2_donas', 'Donas'],
|
||||||
['fig_c9_futura', 'Representación 5'],
|
['fig_c9_futura', 'Representación 5'],
|
||||||
]) {
|
]) {
|
||||||
select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges();
|
fixture.componentInstance.selectFigure(id); fixture.detectChanges();
|
||||||
const pending = request(id);
|
const pending = request(id);
|
||||||
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id);
|
||||||
expect(pending.request.params.get('tema')).toBe('claro');
|
expect(pending.request.params.get('tema')).toBe('claro');
|
||||||
@@ -74,9 +69,9 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
}
|
}
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
it('no ofrece selector de representación y sólo consulta la figura mostrada', () => {
|
||||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull();
|
||||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
|
||||||
@@ -98,9 +93,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
|||||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||||
});
|
});
|
||||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
open(); const first = request('f'); expect(panels()).toHaveLength(1);
|
||||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
|
||||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan
|
|||||||
import { catchError, of, Subscription } from 'rxjs';
|
import { catchError, of, Subscription } from 'rxjs';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||||
@@ -19,7 +17,8 @@ import { IndicadoresService } from './indicadores.service';
|
|||||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
import { vistaConfirmacion } from './indicadores-confirmacion-citologia';
|
||||||
|
import { vistaEscenario } from './indicadores-eu7-escenario';
|
||||||
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||||
import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama';
|
import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama';
|
||||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||||
@@ -29,7 +28,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-catalog-card',
|
selector: 'app-indicador-catalog-card',
|
||||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||||
template: `
|
template: `
|
||||||
<mat-card>
|
<mat-card>
|
||||||
<header>
|
<header>
|
||||||
@@ -37,7 +36,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@if (!sobrio) {
|
@if (!sobrio && fijable) {
|
||||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
<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()">
|
(click)="pinChanged.emit()">
|
||||||
@@ -45,7 +44,6 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
</button>
|
</button>
|
||||||
}
|
}
|
||||||
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
|
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||||
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
|
||||||
@if (isEu7) {
|
@if (isEu7) {
|
||||||
<div #visibilityRegion class="eu7-region">
|
<div #visibilityRegion class="eu7-region">
|
||||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||||
@@ -67,16 +65,6 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||||
</div>
|
</div>
|
||||||
} @else if (selectedFigure) {
|
} @else if (selectedFigure) {
|
||||||
@if (!sobrio && (!pair.length || otherFigures.length)) {
|
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
|
||||||
<mat-label>Representación gráfica</mat-label>
|
|
||||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
|
||||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
|
||||||
@if (pair.length) { <mat-option [value]="pair[0]">Dona y barras</mat-option> }
|
|
||||||
@for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { <mat-option [value]="figure">{{ figureDisplayName(figure, indicador.figuras) }}</mat-option> }
|
|
||||||
</mat-select>
|
|
||||||
</mat-form-field>
|
|
||||||
}
|
|
||||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||||
<div class="representation-panel">
|
<div class="representation-panel">
|
||||||
@@ -123,8 +111,6 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||||
mat-form-field { width: 100%; margin-top: var(--issste-space-4); }
|
mat-form-field { width: 100%; margin-top: var(--issste-space-4); }
|
||||||
.catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4);
|
|
||||||
border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
|
||||||
@media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } }
|
@media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
@@ -148,8 +134,9 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
|||||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
||||||
get sobrio() { return this.dominio === 'cama'; }
|
get sobrio() { return this.dominio === 'cama'; }
|
||||||
get pair() { return dualFigures(this.indicador); }
|
get pair() { return dualFigures(this.indicador); }
|
||||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
get isEu7() { return !!vistaEscenario(this.dominio, this.indicador); }
|
||||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
// CaMa's histopathology has its own view (isHistopatologia); the confirmation view is CaCu's cytology.
|
||||||
|
get isConfirmacion() { return !this.isHistopatologia && !!vistaConfirmacion(this.dominio, this.indicador); }
|
||||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||||
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
||||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||||
@@ -181,6 +168,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() independentPeriods = false;
|
@Input() independentPeriods = false;
|
||||||
@Input() pinned = false;
|
@Input() pinned = false;
|
||||||
|
// Pinning reorders a long grid; with a few cards there is nothing to bring forward.
|
||||||
|
@Input() fijable = true;
|
||||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||||
readonly pinChanged = output<void>();
|
readonly pinChanged = output<void>();
|
||||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
<section class="confirmacion" [attr.aria-label]="'Confirmación histopatológica, ' + vista.textos.filas.toLowerCase()">
|
||||||
<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>
|
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||||
@if (helpOpen) {
|
@if (helpOpen) {
|
||||||
<div class="methodology">
|
<div class="methodology">
|
||||||
@@ -16,7 +15,7 @@
|
|||||||
}
|
}
|
||||||
@switch (status()) {
|
@switch (status()) {
|
||||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
@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 ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('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> }
|
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||||
}
|
}
|
||||||
@@ -30,9 +29,13 @@
|
|||||||
}
|
}
|
||||||
@if (model; as m) {
|
@if (model; as m) {
|
||||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
|
<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> }
|
@if (status() === 'empty') { <p role="status">{{ vista.textos.vacio }}</p> }
|
||||||
@else {
|
@else {
|
||||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
@if (!vista.botones) {
|
||||||
|
<p class="hint">Haz clic en un anillo de la dona para elegir un grupo o un resultado; el centro regresa un paso, hasta el total.</p>
|
||||||
|
}
|
||||||
|
<!-- Without visible buttons they stay for the keyboard, shown while one has the focus. -->
|
||||||
|
<div class="legend" [class.solo-teclado]="!vista.botones" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
|
<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">
|
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||||
@for (g of m.grupos; track g.id; let i = $index) {
|
@for (g of m.grupos; track g.id; let i = $index) {
|
||||||
@@ -46,9 +49,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="figures">
|
<div class="figures">
|
||||||
<section class="figure rates"><h3>Por resultado de la citología, {{ m.periodo }}</h3>
|
<section class="figure rates"><h3>{{ vista.textos.filas }}, {{ m.periodo }}</h3>
|
||||||
@if (ratesFigure) {
|
@if (ratesFigure) {
|
||||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación, tasas por citología, ' + m.periodo + ', ' + selectionLabel" />
|
<app-plotly-chart [figure]="ratesFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, tasas ' + vista.textos.filas.toLowerCase() + ', ' + m.periodo + ', ' + selectionLabel" />
|
||||||
}
|
}
|
||||||
<ul class="rate-states">
|
<ul class="rate-states">
|
||||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||||
@@ -56,16 +59,16 @@
|
|||||||
</section>
|
</section>
|
||||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||||
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
|
@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)" />
|
<app-plotly-chart [figure]="donutFigure" [animated]="!vista.botones" [showNotes]="false" [label]="'Confirmación, dona de grados de biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
|
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin ' + vista.textos.sujetos + ' con biopsia en el periodo.' }}</p> }
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||||
<details class="published-values"><summary>Valores publicados</summary>
|
<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">
|
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de contingencia, ' + indicador.titulo" tabindex="0">
|
||||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</caption>
|
<table><caption>Tabla de contingencia de {{ vista.textos.sujetos }}, {{ 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>
|
<thead><tr><th scope="col">{{ vista.textos.encabezado }}</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||||
<tbody>@for (fila of m.filas; track fila.id) {
|
<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>
|
<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>
|
}</tbody>
|
||||||
|
|||||||
@@ -7,8 +7,12 @@ p, h3, summary { overflow-wrap: anywhere; }
|
|||||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
.legend > button { justify-self: start; }
|
.legend > button { justify-self: start; }
|
||||||
|
.hint { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||||
|
.legend.solo-teclado:not(:focus-within) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||||
|
// The donut is the control: its slices and centre answer to the pointer.
|
||||||
|
.donut app-plotly-chart { cursor: pointer; }
|
||||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
border-radius: var(--issste-radius); color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
.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[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:disabled { opacity: .5; cursor: default; }
|
||||||
|
|||||||
@@ -5,15 +5,12 @@ import { MatButtonModule } from '@angular/material/button';
|
|||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas,
|
||||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
Celda, Tasa, tasas, vistaConfirmacion } 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({
|
@Component({
|
||||||
selector: 'app-indicador-confirmacion-citologia',
|
selector: 'app-indicador-confirmacion-citologia',
|
||||||
@@ -45,17 +42,20 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
private loaded = false;
|
private loaded = false;
|
||||||
private pages: ModeloConfirmacion[] = [];
|
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 selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||||
get reading() { return this.model && this.selection ? lectura(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 isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === (this.vista.botones ? this.model.base : undefined); }
|
||||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||||
readonly estadoTasa = estadoTasa;
|
// CaCu's words when the catalog doesn't name this indicator, so the messages still read.
|
||||||
|
get vista() { return vistaConfirmacion(this.dominio, this.indicador) ?? CONFIRMACION_CACU; }
|
||||||
|
estadoTasa(t: Tasa) { return estadoTasa(t, this.vista.textos.sujetos); }
|
||||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
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'); }
|
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||||
get readingGuide() {
|
get readingGuide() {
|
||||||
const details = this.metadata?.figuras_detalle ?? [];
|
const details = this.metadata?.figuras_detalle ?? [];
|
||||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||||
|
const figuras = [['fig_c2_donas', 'Dona de resultados de biopsia'], ['fig_c2_barras', 'Tasas ' + this.vista.textos.filas.toLowerCase()]] as const;
|
||||||
|
return figuras.flatMap(([figura, nombre]) => {
|
||||||
const detail = details.find(item => item.figura === figura);
|
const detail = details.find(item => item.figura === figura);
|
||||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||||
@@ -65,7 +65,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
|
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: this.vista.estrato })
|
||||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||||
if (key !== this.key) {
|
if (key !== this.key) {
|
||||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||||
@@ -84,7 +84,8 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
this.subscription?.unsubscribe();
|
this.subscription?.unsubscribe();
|
||||||
this.loaded = true; this.clear();
|
this.loaded = true; this.clear();
|
||||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||||
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
const vista = vistaConfirmacion(this.dominio, this.indicador);
|
||||||
|
if (!vista || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||||
this.status.set('incompatible'); return;
|
this.status.set('incompatible'); return;
|
||||||
}
|
}
|
||||||
@@ -92,12 +93,12 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||||
this.status.set('loading');
|
this.status.set('loading');
|
||||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
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({
|
{ estrato: vista.estrato }).pipe(timeout({ first: 40000 })).subscribe({
|
||||||
next: datos => {
|
next: datos => {
|
||||||
if (key !== this.key) return;
|
if (key !== this.key) return;
|
||||||
try {
|
try {
|
||||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
|
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods, vista);
|
||||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
|
this.pages = this.periods.map(p => modeloConfirmacion(datos, p, vista));
|
||||||
// The most recent period first, as the prototype; navigation goes back.
|
// The most recent period first, as the prototype; navigation goes back.
|
||||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||||
} catch (error) { this.failure(error); }
|
} catch (error) { this.failure(error); }
|
||||||
@@ -115,7 +116,8 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
}
|
}
|
||||||
private activatePeriod() {
|
private activatePeriod() {
|
||||||
this.model = this.pages[this.periodIndex];
|
this.model = this.pages[this.periodIndex];
|
||||||
this.selection = this.model ? seleccionBase(this.model) : undefined;
|
// With buttons the view opens on the base group; without, on the total, as CaCu's interactive donut.
|
||||||
|
this.selection = this.model ? (this.vista.botones ? seleccionBase(this.model) : {}) : undefined;
|
||||||
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
||||||
}
|
}
|
||||||
changePeriod(step: number) {
|
changePeriod(step: number) {
|
||||||
@@ -124,7 +126,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
}
|
}
|
||||||
select(trace: string, index = 0) {
|
select(trace: string, index = 0) {
|
||||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||||
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
this.selection = (this.vista.botones ? clicConfirmacion : clicDona)(this.model, this.selection, trace, index); this.draw();
|
||||||
}
|
}
|
||||||
plotClicked(event: unknown) {
|
plotClicked(event: unknown) {
|
||||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||||
@@ -132,7 +134,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
|||||||
}
|
}
|
||||||
private draw() {
|
private draw() {
|
||||||
if (!this.model || !this.selection) return;
|
if (!this.model || !this.selection) return;
|
||||||
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
|
this.donutFigure = (this.vista.botones ? donaConfirmacion : donaExpandible)(this.model, this.selection, this.tema);
|
||||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
<section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
|
||||||
<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>
|
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||||
@if (helpOpen) {
|
@if (helpOpen) {
|
||||||
<div class="methodology">
|
<div class="methodology">
|
||||||
@@ -16,24 +15,24 @@
|
|||||||
}
|
}
|
||||||
@switch (status()) {
|
@switch (status()) {
|
||||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
@case ('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> }
|
@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 (status() === 'ready' || status() === 'empty') {
|
||||||
@if (periods.length > 1) {
|
@if (periods.length > 1) {
|
||||||
<nav class="periods" aria-label="Periodos de dona y barras EU7">
|
<nav class="periods" [attr.aria-label]="'Periodos de dona y barras, ' + indicador.titulo">
|
||||||
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
|
<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>
|
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
@if (model; as m) {
|
@if (model; as m) {
|
||||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
|
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
|
||||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||||
@else {
|
@else {
|
||||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
<div class="legend" role="group" [attr.aria-label]="'Explorar grupos y categorías, ' + indicador.titulo">
|
||||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección">Volver</button>
|
||||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||||
@for (g of m.grupos; track g.id; let i = $index) {
|
@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>
|
<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>
|
||||||
@@ -48,27 +47,27 @@
|
|||||||
<div class="figures">
|
<div class="figures">
|
||||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
||||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
@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)" />
|
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="indicador.titulo + ', dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
|
} @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>
|
<p>{{ sinDatoNote }}</p>
|
||||||
</section>
|
</section>
|
||||||
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
|
<section class="figure"><h3>{{ selectionLabel }} por {{ etiquetaEstrato }}, {{ m.periodo }}</h3>
|
||||||
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
|
<p>Porcentaje del total válido de cada {{ etiquetaEstrato }}; excluye «{{ m.sinDatoEtiqueta }}».</p>
|
||||||
@if (m.escenarios.length && barsFigure) {
|
@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" />
|
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="indicador.titulo + ', barras por ' + etiquetaEstrato + ', ' + m.periodo + ', ' + selectionLabel" />
|
||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||||
<details class="published-values"><summary>Valores publicados</summary>
|
<details class="published-values"><summary>Valores publicados</summary>
|
||||||
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
|
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
||||||
<table><caption>Datos generales, {{ m.periodo }}</caption>
|
<table><caption>Datos generales, {{ m.periodo }}</caption>
|
||||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
|
<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>
|
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
|
||||||
</table>
|
</table>
|
||||||
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
|
<table><caption>Por {{ etiquetaEstrato }}, {{ m.periodo }}, porcentajes sin «{{ m.sinDatoEtiqueta }}»</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>
|
<thead><tr><th scope="col">{{ etiquetaEstrato.charAt(0).toUpperCase() + etiquetaEstrato.slice(1) }}</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
|
||||||
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
|
<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>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ p, h3, summary { overflow-wrap: anywhere; }
|
|||||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
.legend > button { justify-self: start; }
|
.legend > button { justify-self: start; }
|
||||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
border-radius: var(--issste-radius); color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
.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[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:disabled { opacity: .5; cursor: default; }
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
|||||||
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
|
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
|
||||||
expect(f.nativeElement.textContent).not.toContain('987654');
|
expect(f.nativeElement.textContent).not.toContain('987654');
|
||||||
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
|
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
|
||||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
|
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores, Distribución de resultados citológicos"]').tabIndex).toBe(0);
|
||||||
});
|
});
|
||||||
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
|
||||||
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
|
||||||
|
|||||||
@@ -4,16 +4,14 @@ import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
|||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
|
||||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { percentText } from './indicadores-format';
|
import { percentText } from './indicadores-format';
|
||||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
import { barras, Celda, clic, dona, esEu7, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
periodosCompatibles, Seleccion, seleccionEtiqueta, vistaEscenario } 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({
|
@Component({
|
||||||
selector: 'app-indicador-eu7-escenario',
|
selector: 'app-indicador-eu7-escenario',
|
||||||
@@ -44,13 +42,16 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
private key = '';
|
private key = '';
|
||||||
private loaded = false;
|
private loaded = false;
|
||||||
private pages: Modelo[] = [];
|
private pages: Modelo[] = [];
|
||||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
|
||||||
|
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
|
||||||
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
|
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
|
||||||
get sinDatoNote() {
|
get sinDatoNote() {
|
||||||
const m = this.model;
|
const m = this.model;
|
||||||
if (!m) return '';
|
if (!m) return '';
|
||||||
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
if (m.vacio) return 'No hay registros publicados en este periodo.';
|
||||||
const n = m.sinDato.n;
|
const n = m.sinDato.n;
|
||||||
|
if (this.vista && !esEu7(this.vista)) return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
||||||
|
: `Fuera de la dona: ${n} pacientes con «${m.sinDatoEtiqueta}»${m.total === null ? '' : ` de ${m.total + n}`}.`;
|
||||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
|
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.`
|
: 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.`;
|
: `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.`;
|
||||||
@@ -69,7 +70,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
|
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
|
||||||
get readingGuide() {
|
get readingGuide() {
|
||||||
const details = this.metadata?.figuras_detalle ?? [];
|
const details = this.metadata?.figuras_detalle ?? [];
|
||||||
return EU7_FIGURES.flatMap(([figura, nombre]) => {
|
const figuras = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por ' + this.etiquetaEstrato]] as const;
|
||||||
|
return figuras.flatMap(([figura, nombre]) => {
|
||||||
const detail = details.find(item => item.figura === figura);
|
const detail = details.find(item => item.figura === figura);
|
||||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||||
@@ -99,10 +101,11 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
const vista = this.vista;
|
||||||
|
if (!vista || this.indicador.contrato !== 'C2'
|
||||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
|| !stratifiedCapabilities(this.indicador).includes(vista.estrato) || !compatibility.compatible) {
|
||||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||||
this.status.set('incompatible'); return;
|
this.status.set('incompatible'); return;
|
||||||
}
|
}
|
||||||
const key = this.key;
|
const key = this.key;
|
||||||
@@ -110,13 +113,13 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
this.status.set('loading');
|
this.status.set('loading');
|
||||||
this.subscription = combineLatest([
|
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),
|
||||||
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
|
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: vista.estrato }),
|
||||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||||
next: ([general, escenarios]) => {
|
next: ([general, escenarios]) => {
|
||||||
if (key !== this.key) return;
|
if (key !== this.key) return;
|
||||||
try {
|
try {
|
||||||
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
|
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
|
||||||
this.pages = this.periods.map(p => modelo(general, escenarios, p));
|
this.pages = this.periods.map(p => modelo(general, escenarios, p, vista.estrato));
|
||||||
this.periodIndex = 0; this.activatePeriod();
|
this.periodIndex = 0; this.activatePeriod();
|
||||||
} catch (error) { this.failure(error); }
|
} catch (error) { this.failure(error); }
|
||||||
},
|
},
|
||||||
@@ -151,7 +154,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
|||||||
private draw() {
|
private draw() {
|
||||||
if (!this.model) return;
|
if (!this.model) return;
|
||||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
this.donutFigure = dona(this.model, this.selection, this.tema);
|
||||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
this.barsFigure = barras(this.model, this.selection, this.tema, `% de pacientes de cada ${this.etiquetaEstrato}`);
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
|
|||||||
@@ -83,7 +83,23 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
@if (state.status === 'ready' && state.highlight; as h) {
|
||||||
|
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||||
|
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||||
|
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||||
|
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||||
|
<div class="highlight-keys" role="group" [attr.aria-label]="row.group ? row.group.label + ' y sus categorías' : 'Categorías'">
|
||||||
|
@if (row.group; as g) {
|
||||||
|
<button type="button" class="highlight-group" [attr.aria-pressed]="highlightSelection.group === g.id" (click)="highlight('group', g.id)"><span class="legend-swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.label }}</button>
|
||||||
|
}
|
||||||
|
@for (c of row.items; track c.id) {
|
||||||
|
<button type="button" [attr.aria-pressed]="highlightSelection.item === c.id" [disabled]="!!highlightSelection.group && c.group !== highlightSelection.group"
|
||||||
|
[attr.aria-label]="c.short ? c.label : null" (click)="highlight('item', c.id)"><span class="legend-swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.short ?? c.label }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else if (state.status === 'ready' && state.donutLegend?.length) {
|
||||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||||
@for (entry of state.donutLegend; track entry.label) {
|
@for (entry of state.donutLegend; track entry.label) {
|
||||||
<span class="donut-static-legend__item" role="listitem">
|
<span class="donut-static-legend__item" role="listitem">
|
||||||
@@ -94,7 +110,7 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
<div class="plot-slot" [hidden]="state.status !== 'ready'">
|
||||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend || state.highlight ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ', ' + selected?.id + ', ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||||
|
|||||||
@@ -113,3 +113,16 @@
|
|||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||||
}
|
}
|
||||||
|
// Highlight buttons, as in CaCu's «Distribución de resultados citológicos».
|
||||||
|
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||||
|
.dark .highlight-legend { color: #eef1f7; }
|
||||||
|
.highlight-status { margin: 0; font-weight: 600; }
|
||||||
|
.highlight-back { justify-self: start; }
|
||||||
|
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
|
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||||
|
overflow-wrap: anywhere; color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); font: inherit; cursor: pointer; }
|
||||||
|
.highlight-legend button:disabled { opacity: .45; cursor: default; }
|
||||||
|
.highlight-legend button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||||
|
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||||
|
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||||
|
.highlight-legend .highlight-group { font-weight: 600; }
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
|||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||||
|
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||||
|
|
||||||
// The panel owns requests; the card receives the original and its presentation copy.
|
// The panel owns requests; the card receives the original and its presentation copy.
|
||||||
export interface FigureState {
|
export interface FigureState {
|
||||||
@@ -22,6 +23,10 @@ export interface FigureState {
|
|||||||
categoryLabels?: readonly CategoryLabel[];
|
categoryLabels?: readonly CategoryLabel[];
|
||||||
minimumPlotWidth?: number;
|
minimumPlotWidth?: number;
|
||||||
donutLegend?: readonly DonutLegendEntry[];
|
donutLegend?: readonly DonutLegendEntry[];
|
||||||
|
// The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is.
|
||||||
|
ownLayout?: boolean;
|
||||||
|
// Legend buttons that highlight one part of the figure (CaCu style).
|
||||||
|
highlight?: FigureHighlight;
|
||||||
plotWidth?: number;
|
plotWidth?: number;
|
||||||
plotHeight?: number;
|
plotHeight?: number;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -64,7 +69,7 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
}
|
}
|
||||||
@Input({ required: true }) set state(value: FigureState) {
|
@Input({ required: true }) set state(value: FigureState) {
|
||||||
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
if (value.status !== 'ready' || value.figure !== this.currentState?.figure
|
||||||
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; }
|
|| JSON.stringify(value.hierarchy) !== JSON.stringify(this.currentState?.hierarchy)) { this.activeParent = undefined; this.activeCategory = undefined; this.highlightSelection = {}; }
|
||||||
this.currentState = value;
|
this.currentState = value;
|
||||||
if (value.status === 'ready') {
|
if (value.status === 'ready') {
|
||||||
this.updateDonut();
|
this.updateDonut();
|
||||||
@@ -87,7 +92,8 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||||
this.chartFigure = source && hierarchy
|
this.chartFigure = source && hierarchy
|
||||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
: source && this.state.highlight ? highlightFigure(source, this.state.highlight, this.highlightSelection)
|
||||||
|
: source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source;
|
||||||
}
|
}
|
||||||
expandParent(parent: string) {
|
expandParent(parent: string) {
|
||||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||||
@@ -109,9 +115,28 @@ export class IndicadorFigureCard implements OnChanges {
|
|||||||
target?.focus();
|
target?.focus();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
highlightSelection: HighlightSelection = {};
|
||||||
|
readonly highlightRows = highlightRows;
|
||||||
|
get highlightStatus() { return this.state.highlight ? highlightLabel(this.state.highlight, this.highlightSelection) : ''; }
|
||||||
|
highlight(kind: 'group' | 'item', id: string) {
|
||||||
|
if (!this.state.highlight) return;
|
||||||
|
this.highlightSelection = toggleHighlight(this.state.highlight, this.highlightSelection, kind, id);
|
||||||
|
this.updateDonut();
|
||||||
|
}
|
||||||
|
highlightBack() {
|
||||||
|
const sel = this.highlightSelection;
|
||||||
|
this.highlightSelection = sel.item && sel.group ? { group: sel.group } : {};
|
||||||
|
this.updateDonut();
|
||||||
|
}
|
||||||
plotClicked(event: unknown) {
|
plotClicked(event: unknown) {
|
||||||
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
if (!event || typeof event !== 'object' || !('points' in event) || !Array.isArray(event.points)) return;
|
||||||
const point = event.points[0];
|
const point = event.points[0];
|
||||||
|
if (this.state.highlight) {
|
||||||
|
const hit = typeof point?.curveNumber === 'number' && typeof point.pointNumber === 'number'
|
||||||
|
? highlightAt(this.state.highlight, { trace: point.curveNumber, index: point.pointNumber }) : undefined;
|
||||||
|
if (hit) this.highlight(hit.kind, hit.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||||
});
|
});
|
||||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||||
load(); figure().flush({ data: [], layout: {} });
|
load(); figure().flush({ data: [], layout: {} });
|
||||||
const control = filters();
|
const control = filters();
|
||||||
control.changeMode('manual');
|
control.select([]);
|
||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
apply();
|
apply();
|
||||||
http.expectNone(req => req.url.includes('/figuras/'));
|
http.expectNone(req => req.url.includes('/figuras/'));
|
||||||
@@ -228,18 +228,13 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(state?.applied?.selection.mode).toBe('todos');
|
expect(state?.applied?.selection.mode).toBe('todos');
|
||||||
apply();
|
apply();
|
||||||
const manual = figure();
|
const manual = figure();
|
||||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
expect(manual.request.params.get('periodos')).toBe('2025-S2');
|
||||||
control.select([]);
|
control.select([]);
|
||||||
expect(manual.cancelled).toBe(false);
|
expect(manual.cancelled).toBe(false);
|
||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
apply();
|
apply();
|
||||||
http.expectNone(req => req.url.includes('/figuras/'));
|
http.expectNone(req => req.url.includes('/figuras/'));
|
||||||
control.changeMode('todos');
|
manual.flush({ data: [], layout: {} });
|
||||||
apply();
|
|
||||||
expect(manual.cancelled).toBe(true);
|
|
||||||
const all = figure();
|
|
||||||
expect(all.request.params.has('periodos')).toBe(false);
|
|
||||||
all.flush({ data: [], layout: {} });
|
|
||||||
});
|
});
|
||||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||||
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
});
|
});
|
||||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual');
|
const control = filters(); control.select([]);
|
||||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||||
@@ -308,9 +303,9 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||||
http.expectNone(r => r.url.includes('/figuras/'));
|
http.expectNone(r => r.url.includes('/figuras/'));
|
||||||
});
|
});
|
||||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
const control = filters(); control.select([]); control.year = '2025';
|
||||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||||
apply();
|
apply();
|
||||||
const req = figure();
|
const req = figure();
|
||||||
@@ -320,7 +315,6 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
expect(page.result().figure).toBeUndefined();
|
expect(page.result().figure).toBeUndefined();
|
||||||
expect(page.result().message).toContain('esta selección');
|
expect(page.result().message).toContain('esta selección');
|
||||||
expect(page.result().message).not.toContain('2025');
|
expect(page.result().message).not.toContain('2025');
|
||||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
|
||||||
expect(control.selectedPeriods).toEqual(periodos);
|
expect(control.selectedPeriods).toEqual(periodos);
|
||||||
control.select([]);
|
control.select([]);
|
||||||
page.requestFigure();
|
page.requestFigure();
|
||||||
@@ -333,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
});
|
});
|
||||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||||
load(); figure().flush({ data: [], layout: {} });
|
load(); figure().flush({ data: [], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||||
control.unit = 'S2'; control.add();
|
control.unit = 'S2'; control.add();
|
||||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||||
@@ -344,17 +338,17 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
page.requestFigure();
|
page.requestFigure();
|
||||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||||
retry.flush({ data: [], layout: {} });
|
retry.flush({ data: [], layout: {} });
|
||||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
});
|
});
|
||||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||||
load(); figure().flush({ data: [], layout: {} });
|
load(); figure().flush({ data: [], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
apply(); const old = figure();
|
apply(); const old = figure();
|
||||||
control.unit = 'S2'; control.add();
|
control.unit = 'S2'; control.add();
|
||||||
expect(old.cancelled).toBe(false);
|
expect(old.cancelled).toBe(false);
|
||||||
apply(); const current = figure();
|
apply(); const current = figure();
|
||||||
expect(old.cancelled).toBe(true);
|
expect(old.cancelled).toBe(true);
|
||||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
expect(current.request.params.get('periodos')).toBe('2025-S2');
|
||||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||||
@@ -362,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
|
|||||||
|
|
||||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
|||||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2';
|
||||||
|
import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut';
|
||||||
|
import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||||
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
import { c2GeneralSelection } from './indicadores-c2-general-selection';
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
@@ -46,10 +48,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||||
@for (d of capabilities; track d) {
|
@for (d of capabilities; track d) {
|
||||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
@if (dimension) {
|
||||||
|
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
|
||||||
|
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
</fieldset>
|
</fieldset>
|
||||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||||
}
|
}
|
||||||
@@ -68,8 +76,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
@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 (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> }
|
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||||
<details><summary>Valores publicados</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>
|
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
|
||||||
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
|
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
|
||||||
</tbody></table></div>
|
</tbody></table></div>
|
||||||
</details>
|
</details>
|
||||||
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
|
||||||
@@ -102,7 +110,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
|||||||
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
||||||
.distribution-dimensions { margin-top: .75rem; }
|
.distribution-dimensions { margin-top: .75rem; }
|
||||||
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
|
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
|
||||||
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); color: var(--issste-text);
|
||||||
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||||
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||||
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
|
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
@@ -162,6 +170,18 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||||
}
|
}
|
||||||
dimension: DimensionEstrato | '' = '';
|
dimension: DimensionEstrato | '' = '';
|
||||||
|
readonly etiquetaDimension = etiquetaDimension;
|
||||||
|
// Counts or each category's share of its stratum; an indicator can ask to open with the share.
|
||||||
|
private medidaElegida?: MedidaEstrato;
|
||||||
|
get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; }
|
||||||
|
changeMedida(medida: MedidaEstrato) {
|
||||||
|
if (medida === this.medida) return;
|
||||||
|
this.medidaElegida = medida;
|
||||||
|
if (this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||||
|
try { this.result.set(this.presentStratified(this.stratifiedData)); }
|
||||||
|
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
|
||||||
|
}
|
||||||
|
}
|
||||||
cells: StratifiedCell[] = [];
|
cells: StratifiedCell[] = [];
|
||||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||||
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
|
||||||
@@ -181,7 +201,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
}
|
}
|
||||||
private presentStratified(data: IndicadorDatos): FigureState {
|
private presentStratified(data: IndicadorDatos): FigureState {
|
||||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida);
|
||||||
this.cells = adapted.cells;
|
this.cells = adapted.cells;
|
||||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||||
@@ -245,6 +265,17 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
const state = this.presentStratified(data); this.stratifiedData = data; return state;
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
if (c1DonutCapability(this.indicador.contrato, selection.figura)) {
|
||||||
|
if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1)
|
||||||
|
return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState);
|
||||||
|
return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => {
|
||||||
|
const adapted = c1DonutFigure(data, selection);
|
||||||
|
if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState;
|
||||||
|
return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes,
|
||||||
|
highlight: adapted.highlight, ownLayout: true, plotHeight: selection.figura === C1_AGE_BARS ? 400 : undefined,
|
||||||
|
emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined };
|
||||||
|
}));
|
||||||
|
}
|
||||||
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) {
|
||||||
// Both panels, KPI and numeric table share the exact same transport key.
|
// Both panels, KPI and numeric table share the exact same transport key.
|
||||||
// Do not catch /datos errors here: a backend failure is a real error state.
|
// Do not catch /datos errors here: a backend failure is a real error state.
|
||||||
@@ -265,6 +296,13 @@ export class IndicadorFigurePanel implements OnChanges {
|
|||||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||||
}
|
}
|
||||||
const adapted = c2Figure(data, selection);
|
const adapted = c2Figure(data, selection);
|
||||||
|
if (adapted.status === 'supported' && selection.dominio === 'tea') {
|
||||||
|
const base = { source: 'datos' as const, footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage };
|
||||||
|
if (selection.figura === 'fig_c2_donas') {
|
||||||
|
const tea = teaC2Donut(adapted.model, selection.tema, adapted.figure.layout['title']);
|
||||||
|
if (tea) return of({ ...this.present(tea.figure, selection), ...base, highlight: tea.highlight, ownLayout: true });
|
||||||
|
} else return of({ ...this.present(adapted.figure, selection), ...base, highlight: c2BarsHighlight(adapted.model) });
|
||||||
|
}
|
||||||
return adapted.status === 'supported'
|
return adapted.status === 'supported'
|
||||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||||
|
|||||||
@@ -13,13 +13,14 @@ import { MatCardModule } from '@angular/material/card';
|
|||||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||||
}
|
}
|
||||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||||
|
<!-- A card with its value shows nothing more; «Disponible» stays only for screen readers. -->
|
||||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
||||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||||
</mat-card>
|
</mat-card>
|
||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
:host { display: block; min-width: 0; }
|
:host { display: flex; flex-direction: column; min-width: 0; }
|
||||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
mat-card { box-sizing: border-box; flex: 1 1 auto; padding: var(--issste-space-6);
|
||||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||||
border-radius: var(--issste-radius); box-shadow: none; }
|
border-radius: var(--issste-radius); box-shadow: none; }
|
||||||
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import { provideRouter } from '@angular/router';
|
|||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { IndicadoresPage } from './indicadores-page';
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
import { CACU_RESULTADO_KPI, CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN as KPI_BASE } from './indicadores-kpi';
|
||||||
|
// CaMa's cards are its opportunity strip: the catalog here publishes all four, so none is pending.
|
||||||
|
const KPI_BY_DOMAIN = { ...KPI_BASE, cama: CAMA_OPORTUNIDAD_KPIS };
|
||||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||||
import { IndicadoresMemory } from './indicadores-memory';
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
@@ -27,9 +29,14 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo })));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
}
|
}
|
||||||
|
// Availability runs four requests at a time; flushing one batch starts the next.
|
||||||
|
function flushPeriodos(periodos: () => unknown[]) {
|
||||||
|
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos')))
|
||||||
|
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() }));
|
||||||
|
}
|
||||||
// Regression assertions below target the original KPI contracts. The added lab
|
// Regression assertions below target the original KPI contracts. The added lab
|
||||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||||
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
// Satisfy its independent request with an explicit empty response, never diagnosis data.
|
||||||
@@ -47,6 +54,18 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
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: [
|
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
|
||||||
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
{ periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||||
}
|
}
|
||||||
|
// Answers every card by its URL until none is waiting: a domain with more cards than the concurrent
|
||||||
|
// requests gets them in batches.
|
||||||
|
function flushAll(domain: Dominio, extra: Partial<IndicadorDatos> = {}) {
|
||||||
|
for (let reqs = requests(); reqs.length; reqs = requests()) {
|
||||||
|
// A flushed answer can cancel its siblings (a new anchor period); those are not answered.
|
||||||
|
for (const r of reqs.filter(r => !r.cancelled)) {
|
||||||
|
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.includes('/' + d.id + '/'));
|
||||||
|
r.flush({ ...response(index, domain, r.request.params.get('periodos') ?? '2025-S1'), ...extra });
|
||||||
|
}
|
||||||
|
fixture.detectChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
|
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[]] };
|
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||||
@@ -56,7 +75,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
expect(panels().map(p => p.definition.id)).toEqual([]);
|
expect(panels().map(p => p.definition.id)).toEqual([]);
|
||||||
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos'));
|
||||||
});
|
});
|
||||||
it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => {
|
it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => {
|
||||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]);
|
||||||
load('tea'); const initial = requests();
|
load('tea'); const initial = requests();
|
||||||
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']);
|
||||||
@@ -64,8 +83,10 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
const req = requests();
|
const req = requests();
|
||||||
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos'));
|
||||||
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges();
|
||||||
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]);
|
expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]);
|
||||||
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.');
|
||||||
|
expect(panels()[3].result().info).toBe('2 de 5 pacientes con TEA positivo tienen un EEG ligado.');
|
||||||
|
expect(panels()[4].result().info).toBe('2 de 5 pacientes con TEA positivo no tienen ningún EEG ligado.');
|
||||||
});
|
});
|
||||||
it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => {
|
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);
|
load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||||
@@ -80,7 +101,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||||
@@ -97,8 +118,9 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
|
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
|
||||||
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama')));
|
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); expect(requests().every(r => r.request.url.startsWith('/cama/'))).toBe(true); flushAll('cama');
|
||||||
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
// CaMa's last cards start after its first batch and are cancelled by the change of domain.
|
||||||
|
load('cacu'); const restored = requests().filter(r => !r.cancelled); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||||
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
||||||
});
|
});
|
||||||
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
it('el catálogo vigente retira los KPI que dejaron de publicarse', () => {
|
||||||
@@ -164,29 +186,28 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
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.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
flushPeriodos(() => []); fixture.detectChanges();
|
||||||
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||||
http.expectNone(r => r.url.endsWith('/datos'));
|
http.expectNone(r => r.url.endsWith('/datos'));
|
||||||
});
|
});
|
||||||
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||||
for (const domain of ['cacu', 'cama'] as const) {
|
for (const domain of ['cacu', 'cama'] as const) {
|
||||||
load(domain);
|
load(domain);
|
||||||
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
|
flushAll(domain, { notas: ['Nota del pie de la figura.'] });
|
||||||
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
|
|
||||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
|
||||||
fixture.detectChanges();
|
|
||||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
||||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]);
|
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7', '7']);
|
||||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]);
|
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined]
|
||||||
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', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
: ['pacientes', '%', 'días (mediana)', 'días (mediana)']);
|
||||||
|
// «Disponible» stays for screen readers, visually hidden; any other state is the visible message.
|
||||||
|
expect(cards.map(card => card.querySelector('.kpi-state:not(.visually-hidden)')?.textContent.trim())).toEqual(domain === 'cacu' ? [undefined, 'Selección no consolidable', undefined, 'Indicador no disponible', 'Indicador no disponible'] : Array(4).fill(undefined));
|
||||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||||
expect.stringContaining('2025-S1'),
|
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.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');
|
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||||
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
|
// CaCu and CaMa 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(false);
|
expect(fixture.nativeElement.textContent).not.toContain('Nota del pie de la figura.');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
it('Aplicar Todos después del periodo compartido conserva supresión del último sin retroceder', () => {
|
||||||
@@ -206,7 +227,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
|
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
|
||||||
for (const domain of ['cacu', 'cama'] as const) {
|
for (const domain of ['cacu', 'cama'] as const) {
|
||||||
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
|
load(domain, false, ['2025-S1'], true); requests()[0].flush(response(0, domain)); fixture.detectChanges();
|
||||||
requests().forEach((r, i) => r.flush(response(i + 1, domain))); fixture.detectChanges();
|
flushAll(domain);
|
||||||
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
|
expect(TestBed.inject(IndicadoresMemory).initialKpiPresentation(domain)).toBe(false);
|
||||||
}
|
}
|
||||||
load('cacu', false, ['2025-S1'], true);
|
load('cacu', false, ['2025-S1'], true);
|
||||||
@@ -218,7 +239,7 @@ describe('KPI integración con autoridad global', () => {
|
|||||||
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
|
const data = response(0, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; requests()[0].flush(data);
|
||||||
const old = requests(); expect(old).toHaveLength(1);
|
const old = requests(); expect(old).toHaveLength(1);
|
||||||
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
|
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
|
||||||
requests().forEach((r, i) => r.flush(response(i, 'cama')));
|
flushAll('cama');
|
||||||
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
|
load('cacu', false, ['2025-S2', '2025-S1'], true); const resumed = requests(); expect(resumed).toHaveLength(1);
|
||||||
resumed[0].flush(response(0)); fixture.detectChanges();
|
resumed[0].flush(response(0)); fixture.detectChanges();
|
||||||
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
|
requests().forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i + 1)); });
|
||||||
|
|||||||
@@ -19,15 +19,12 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
|||||||
imports: [IndicadorKpiCard, MatButtonModule],
|
imports: [IndicadorKpiCard, MatButtonModule],
|
||||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
|
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true" />
|
||||||
@if (result().state === 'Error de consulta') {
|
@if (result().state === 'Error de consulta') {
|
||||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||||
}`,
|
}`,
|
||||||
styles: `
|
// The card fills the panel, so cards in one grid row are as tall as the row.
|
||||||
:host { display: block; min-width: 0; }
|
styles: ':host { display: flex; flex-direction: column; min-width: 0; } app-indicador-kpi-card { flex: 1 1 auto; }',
|
||||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
|
||||||
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
|
|
||||||
`,
|
|
||||||
})
|
})
|
||||||
export class IndicadorKpiPanel implements OnChanges {
|
export class IndicadorKpiPanel implements OnChanges {
|
||||||
@Input({ required: true }) dominio!: Dominio;
|
@Input({ required: true }) dominio!: Dominio;
|
||||||
|
|||||||
@@ -50,47 +50,35 @@
|
|||||||
</section>
|
</section>
|
||||||
} @else {
|
} @else {
|
||||||
<section aria-label="Editor de filtros generales del proyecto">
|
<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">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis 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">
|
<div class="fields">
|
||||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
|
|
||||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||||
</mat-select>
|
</mat-select>
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
}
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
|
||||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
|
|
||||||
<mat-option value="todos">Todos con reporte</mat-option>
|
|
||||||
<mat-option value="manual">Elegir periodos</mat-option>
|
|
||||||
</mat-select>
|
|
||||||
</mat-form-field>
|
|
||||||
}
|
|
||||||
@if (entry.draft.mode !== 'todos') {
|
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodos seleccionados</mat-label>
|
|
||||||
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
|
|
||||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods.join(', ') }}</span></mat-select-trigger>
|
|
||||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||||
@if (availability) {
|
@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-select>
|
||||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
}
|
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||||
|
@if (hasPending) { <span class="pending" role="status">Hay cambios sin aplicar.</span> }
|
||||||
</div>
|
</div>
|
||||||
|
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}</p>
|
||||||
@if (availability) {
|
@if (availability) {
|
||||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||||
@else if (availability.status === 'error') {
|
@else if (availability.status === 'error') {
|
||||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
<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>
|
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
|
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||||
}
|
}
|
||||||
@if (!availability && entry.draft.mode !== 'todos') {
|
@if (!availability) {
|
||||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||||
<div class="fields period-builder">
|
<div class="fields period-builder">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||||
@@ -108,11 +96,6 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||||
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
@if (!canApply) { <p role="status">Selecciona un periodo válido para aplicar.</p> }
|
||||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
|
||||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
|
||||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
|
||||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
|
||||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
|
||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,15 +8,14 @@
|
|||||||
:host(.compacto) .apply-button { min-height: 40px; }
|
:host(.compacto) .apply-button { min-height: 40px; }
|
||||||
:host(.compacto) .period-builder button { min-height: 40px; }
|
:host(.compacto) .period-builder button { min-height: 40px; }
|
||||||
section { min-width: 0; }
|
section { min-width: 0; }
|
||||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
|
.fields { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); }
|
||||||
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
mat-form-field { flex: 0 1 14rem; min-width: 0; }
|
||||||
.period-builder mat-form-field { flex: 0 1 10rem; }
|
.period-builder mat-form-field { flex: 0 1 9rem; }
|
||||||
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
.period-builder button { min-height: 40px; }
|
||||||
p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; }
|
p { overflow-wrap: anywhere; line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
|
||||||
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.5; }
|
.select-value { white-space: normal; overflow-wrap: anywhere; line-height: 1.4; }
|
||||||
.filter-help, .applied-summary { color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
.filter-help, .applied-summary { color: var(--issste-text-secondary); }
|
||||||
.draft-summary { font-weight: 500; }
|
.pending { color: var(--issste-text); font: var(--mat-sys-body-small); border-left: 3px solid var(--issste-accent); padding-left: var(--issste-space-2); }
|
||||||
.pending { border-left: 3px solid var(--issste-text); padding-left: var(--issste-space-3); }
|
|
||||||
.error { color: var(--mat-sys-error); }
|
.error { color: var(--mat-sys-error); }
|
||||||
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
|
||||||
.remove button { min-height: 44px; }
|
.remove button { min-height: 44px; }
|
||||||
@@ -25,6 +24,5 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
|
|||||||
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
.fields.compact mat-form-field { flex: 0 1 14rem; }
|
||||||
.fields.compact .apply-button { margin-top: 0; }
|
.fields.compact .apply-button { margin-top: 0; }
|
||||||
@media (max-width: 550px) {
|
@media (max-width: 550px) {
|
||||||
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; }
|
mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; }
|
||||||
.period-builder button { margin-top: 0; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,25 +18,19 @@ describe('UX-04 control asistido', () => {
|
|||||||
control = fixture.componentInstance;
|
control = fixture.componentInstance;
|
||||||
});
|
});
|
||||||
afterEach(() => fixture.destroy());
|
afterEach(() => fixture.destroy());
|
||||||
it('en modo compacto agregar otro periodo sustituye la selección anterior', () => {
|
function periodSelect() {
|
||||||
fixture.componentRef.setInput('compact', true); fixture.detectChanges();
|
return fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
|
||||||
control.unit = 'S2'; control.add();
|
}
|
||||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
|
||||||
});
|
|
||||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
|
||||||
await fixture.whenStable(); fixture.detectChanges();
|
|
||||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
|
||||||
fixture.componentRef.setInput('state', {
|
fixture.componentRef.setInput('state', {
|
||||||
...control.state, editors: { ...control.state.editors, semestre: {
|
...control.state, editors: { ...control.state.editors, semestre: {
|
||||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||||
} },
|
} },
|
||||||
});
|
});
|
||||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||||
expect(values.map(e => e.textContent)).toContain('2025-S1, 2025-S2');
|
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||||
expect(values.map(e => e.textContent)).toContain('Elegir periodos');
|
|
||||||
fixture.componentRef.setInput('state', {
|
fixture.componentRef.setInput('state', {
|
||||||
...control.state, editors: { ...control.state.editors, semestre: {
|
...control.state, editors: { ...control.state.editors, semestre: {
|
||||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||||
@@ -50,10 +44,11 @@ describe('UX-04 control asistido', () => {
|
|||||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||||
fixture.changeDetectorRef.detach();
|
fixture.changeDetectorRef.detach();
|
||||||
control.changeMode('manual');
|
control.select([]);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
const select = periodSelect();
|
||||||
|
expect(select.componentInstance.multiple).toBe(false);
|
||||||
const model = select.injector.get(NgModel);
|
const model = select.injector.get(NgModel);
|
||||||
const writes = vi.spyOn(model.control, 'setValue');
|
const writes = vi.spyOn(model.control, 'setValue');
|
||||||
const edits = vi.spyOn(control.edited, 'emit');
|
const edits = vi.spyOn(control.edited, 'emit');
|
||||||
@@ -61,16 +56,16 @@ describe('UX-04 control asistido', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
}
|
}
|
||||||
expect(model.control.value).toEqual([]);
|
expect(model.control.value).toBeNull();
|
||||||
expect(writes).not.toHaveBeenCalled();
|
expect(writes).not.toHaveBeenCalled();
|
||||||
expect(edits).not.toHaveBeenCalled();
|
expect(edits).not.toHaveBeenCalled();
|
||||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||||
});
|
});
|
||||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
|
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar el selector', async () => {
|
||||||
control.changeTipo('mes');
|
control.changeTipo('mes');
|
||||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||||
fixture.detectChanges(); await fixture.whenStable();
|
fixture.detectChanges(); await fixture.whenStable();
|
||||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
const select = periodSelect();
|
||||||
const model = select.injector.get(NgModel);
|
const model = select.injector.get(NgModel);
|
||||||
const writes = vi.spyOn(model.control, 'setValue');
|
const writes = vi.spyOn(model.control, 'setValue');
|
||||||
for (let i = 0; i < 3; i++) {
|
for (let i = 0; i < 3; i++) {
|
||||||
@@ -85,7 +80,7 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
});
|
});
|
||||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||||
control.changeMode('manual');
|
control.select([]);
|
||||||
control.year = '1'; control.unit = 'S1'; control.add();
|
control.year = '1'; control.unit = 'S1'; control.add();
|
||||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||||
control.add();
|
control.add();
|
||||||
@@ -93,7 +88,7 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.entry.added).toEqual(['0001-S1']);
|
expect(control.entry.added).toEqual(['0001-S1']);
|
||||||
});
|
});
|
||||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||||
});
|
});
|
||||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||||
@@ -101,21 +96,22 @@ describe('UX-04 control asistido', () => {
|
|||||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||||
});
|
});
|
||||||
it('conserva borradores independientes sin convertir periodos', () => {
|
it('conserva borradores independientes sin convertir periodos', () => {
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||||
});
|
});
|
||||||
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
control.unit = 'S2'; control.add();
|
control.unit = 'S2'; control.add();
|
||||||
control.select(['2025-S2']);
|
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
|
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
const select = periodSelect();
|
||||||
expect(select).toBeTruthy();
|
expect(select.componentInstance.multiple).toBe(false);
|
||||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||||
fixture.nativeElement.querySelector('.remove button').click();
|
fixture.nativeElement.querySelector('.remove button').click();
|
||||||
@@ -126,7 +122,7 @@ describe('UX-04 control asistido', () => {
|
|||||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||||
const edited = vi.spyOn(control.edited, 'emit');
|
const edited = vi.spyOn(control.edited, 'emit');
|
||||||
const apply = vi.spyOn(control.apply, 'emit');
|
const apply = vi.spyOn(control.apply, 'emit');
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||||
@@ -135,11 +131,25 @@ describe('UX-04 control asistido', () => {
|
|||||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||||
expect(apply).toHaveBeenCalledTimes(1);
|
expect(apply).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
it('no ofrece Todos en meses cuando el primero es semestre', () => {
|
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
|
||||||
control.changeTipo('mes'); fixture.detectChanges();
|
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
expect(labels).toContain('Intervalo de análisis');
|
||||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
expect(labels).not.toContain('Modalidad');
|
||||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||||
expect(control.entry.draft.mode).toBe('empty');
|
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
|
||||||
|
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||||
|
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
|
||||||
|
expect(options).toEqual(['Semestral', 'Mensual']);
|
||||||
|
select.componentInstance.close();
|
||||||
|
});
|
||||||
|
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||||
|
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||||
|
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||||
|
fixture.detectChanges();
|
||||||
|
control.changeTipo('mes');
|
||||||
|
expect(control.selectedPeriods).toEqual(['2025-12']);
|
||||||
|
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
|
||||||
|
// A period already chosen for that interval is kept.
|
||||||
|
expect(control.selectedPeriods).toEqual(['2025-11']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export class IndicadorPeriodFilters implements OnChanges {
|
|||||||
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
||||||
get entry() { return this.state.editors[this.state.tipo]!; }
|
get entry() { return this.state.editors[this.state.tipo]!; }
|
||||||
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
||||||
// Keep the empty multiple-select value stable so an unchanged draft can settle.
|
// Keep the empty selection stable so an unchanged draft can settle.
|
||||||
private readonly emptyPeriods: string[] = [];
|
private readonly emptyPeriods: string[] = [];
|
||||||
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
|
get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; }
|
||||||
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
|
get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; }
|
||||||
@@ -45,21 +45,21 @@ export class IndicadorPeriodFilters implements OnChanges {
|
|||||||
get hasPending() { return pending(this.state); }
|
get hasPending() { return pending(this.state); }
|
||||||
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
||||||
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
||||||
|
// There is no "every period" choice in the editor: a new interval starts on its most recent
|
||||||
|
// period with a report (options are sorted newest first).
|
||||||
changeTipo(tipo: TipoPeriodo) {
|
changeTipo(tipo: TipoPeriodo) {
|
||||||
if (!this.types.includes(tipo)) return;
|
if (!this.types.includes(tipo)) return;
|
||||||
this.state.tipo = tipo;
|
this.state.tipo = tipo;
|
||||||
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
||||||
this.year = this.unit = this.error = '';
|
this.year = this.unit = this.error = '';
|
||||||
|
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
|
||||||
|
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
|
||||||
this.edited.emit();
|
this.edited.emit();
|
||||||
}
|
}
|
||||||
changeMode(mode: 'todos' | 'manual') {
|
// Only one period can be chosen: cards and figures never combine periods.
|
||||||
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
|
|
||||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
|
||||||
this.error = '';
|
|
||||||
this.edited.emit();
|
|
||||||
}
|
|
||||||
select(values: string[]) {
|
select(values: string[]) {
|
||||||
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
const unique = [...new Set(this.compact ? values.slice(-1) : values)];
|
||||||
|
if (unique.length > 1) return;
|
||||||
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return;
|
||||||
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
||||||
this.edited.emit();
|
this.edited.emit();
|
||||||
@@ -73,13 +73,11 @@ export class IndicadorPeriodFilters implements OnChanges {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
||||||
const selected = this.selectedPeriods;
|
|
||||||
this.entry.added.push(period);
|
this.entry.added.push(period);
|
||||||
this.select([...selected, period]);
|
this.select([period]);
|
||||||
}
|
}
|
||||||
remove(period: string) {
|
remove(period: string) {
|
||||||
this.entry.added = this.entry.added.filter(p => p !== period);
|
this.entry.added = this.entry.added.filter(p => p !== period);
|
||||||
// Removing an unselected option must not change the Todos mode.
|
|
||||||
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
||||||
else this.edited.emit();
|
else this.edited.emit();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||||
|
import { c2Theme } from './indicadores-c2-palette';
|
||||||
|
import { AnalisisResultados, AnalisisSubgrupos } from './indicadores-analisis.service';
|
||||||
|
|
||||||
|
const DIAS_POR_MES = 30.4375;
|
||||||
|
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||||
|
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||||
|
function transparente(hex: string, alfa: number) {
|
||||||
|
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
|
||||||
|
return m ? `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alfa})` : hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the stage measures: the cumulative incidence of its event, or the survival (alive at t).
|
||||||
|
export const nombreMedida = (medida: 'incidencia' | 'supervivencia') => medida === 'supervivencia' ? 'Supervivencia' : 'Incidencia acumulada';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stage's measure per published group (cumulative incidence, or survival in the survival stage): a step line with its 95 % band. The curve ends where the
|
||||||
|
* answer suppressed it (fewer at risk than the threshold); each line carries its group in `meta`, so a click
|
||||||
|
* can only change the filters, never read rows.
|
||||||
|
*/
|
||||||
|
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||||
|
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
|
||||||
|
const data: Record<string, unknown>[] = [];
|
||||||
|
const supervivencia = r.medida === 'supervivencia';
|
||||||
|
let maximo = 1, minimo = 100;
|
||||||
|
for (const g of r.grupos.filter(x => !x.suprimido)) {
|
||||||
|
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
|
||||||
|
if (!puntos.length) continue;
|
||||||
|
const x = puntos.map(c => +(c.t / DIAS_POR_MES).toFixed(2));
|
||||||
|
maximo = Math.max(maximo, ...puntos.map(c => c.ic_alto!)); minimo = Math.min(minimo, ...puntos.map(c => c.ic_bajo!));
|
||||||
|
const comun = { type: 'scatter', mode: 'lines', x, legendgroup: g.grupo, line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false };
|
||||||
|
data.push({ ...comun, y: puntos.map(c => c.ic_bajo) });
|
||||||
|
data.push({ ...comun, y: puntos.map(c => c.ic_alto), fill: 'tonexty', fillcolor: transparente(g.color, tema === 'oscuro' ? .28 : .16) });
|
||||||
|
data.push({
|
||||||
|
type: 'scatter', mode: 'lines', x, y: puntos.map(c => c.valor), name: `${escapar(g.etiqueta)} (n = ${miles(g.n!)}, ${miles(g.eventos!)} eventos)`,
|
||||||
|
legendgroup: g.grupo, meta: g.grupo, line: { shape: 'hv', width: 2.5, color: g.color },
|
||||||
|
customdata: puntos.map(c => [pct(c.valor!), pct(c.ic_bajo!), pct(c.ic_alto!), miles(c.n_riesgo!), miles(c.n_eventos!)]),
|
||||||
|
hovertemplate: `<b>${escapar(g.etiqueta)}</b><br>Mes %{x:.1f}: %{customdata[0]} % (IC 95 %: %{customdata[1]} a %{customdata[2]})<br>En riesgo: %{customdata[3]} · eventos acumulados: %{customdata[4]}<extra></extra>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
layout: {
|
||||||
|
autosize: true, height: 460, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||||
|
margin: { t: 16, l: 64, r: 16, b: 96 }, hovermode: 'closest',
|
||||||
|
legend: { orientation: 'h', y: -0.22, itemclick: false, itemdoubleclick: false },
|
||||||
|
xaxis: { title: { text: 'Meses desde el origen' }, range: [0, meses], dtick: 6, gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||||
|
yaxis: { title: { text: nombreMedida(r.medida) + ' (%)' }, range: supervivencia ? [Math.max(0, minimo - 10), 100] : [0, Math.min(100, maximo * 1.1)],
|
||||||
|
gridcolor: p.grid, zeroline: false, fixedrange: true, ticksuffix: ' %' },
|
||||||
|
},
|
||||||
|
config: { displayModeBar: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hazard ratio of each group against the reference, on a log axis; an open marker flags a failed proportional-hazards check. */
|
||||||
|
export function forestFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||||
|
const p = c2Theme(tema), e = r.efectos;
|
||||||
|
if (e.estado !== 'listo' || !e.filas.length) return { data: [], layout: {} };
|
||||||
|
const etiquetas = [`${escapar(e.etiqueta_referencia ?? e.referencia ?? '')} (referencia)`, ...e.filas.map(f => escapar(f.etiqueta))];
|
||||||
|
const falla = (ph: number | null) => ph !== null && ph < .05;
|
||||||
|
const minimo = Math.min(1, ...e.filas.map(f => f.ic_bajo)), maximo = Math.max(1, ...e.filas.map(f => f.ic_alto));
|
||||||
|
return {
|
||||||
|
data: [
|
||||||
|
{ type: 'scatter', mode: 'markers', x: [1], y: [etiquetas[0]], marker: { symbol: 'diamond', size: 10, color: p.outline }, hoverinfo: 'skip', showlegend: false },
|
||||||
|
{
|
||||||
|
type: 'scatter', mode: 'markers', x: e.filas.map(f => f.hr), y: etiquetas.slice(1), showlegend: false,
|
||||||
|
error_x: { type: 'data', symmetric: false, array: e.filas.map(f => f.ic_alto - f.hr), arrayminus: e.filas.map(f => f.hr - f.ic_bajo), color: p.text, thickness: 1.5, width: 6 },
|
||||||
|
marker: { size: 11, color: e.filas.map(f => falla(f.ph_p) ? p.background : p.text), line: { color: p.text, width: 2 }, symbol: 'square' },
|
||||||
|
customdata: e.filas.map(f => [f.ic_bajo.toLocaleString('es-MX'), f.ic_alto.toLocaleString('es-MX'), miles(f.n_eventos), falla(f.ph_p) ? '<br>Riesgos no proporcionales: el HR promedia un efecto que cambia.' : '']),
|
||||||
|
hovertemplate: '%{y}<br>HR %{x:.2f} (IC 95 %: %{customdata[0]} a %{customdata[1]})<br>%{customdata[2]} eventos%{customdata[3]}<extra></extra>',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
layout: {
|
||||||
|
autosize: true, height: Math.max(220, 70 + 44 * etiquetas.length), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||||
|
margin: { t: 16, l: 16, r: 24, b: 56 },
|
||||||
|
xaxis: { type: 'log', title: { text: 'Razón de riesgos (HR), escala logarítmica' }, range: [Math.log10(minimo * .7), Math.log10(maximo * 1.4)], gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||||
|
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
||||||
|
shapes: [{ type: 'line', xref: 'x', yref: 'paper', x0: 1, x1: 1, y0: 0, y1: 1, line: { color: p.outline, dash: 'dot', width: 1.5 } }],
|
||||||
|
},
|
||||||
|
config: { displayModeBar: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stage's measure at the horizon by its two variables (rows and columns). A suppressed cell is drawn grey with its
|
||||||
|
* reason, never as a colour; each cell carries its pair of codes, so a click only changes the filters.
|
||||||
|
*/
|
||||||
|
export function subgruposFigura(s: AnalisisSubgrupos, tema: Tema): PlotlyFigure {
|
||||||
|
const p = c2Theme(tema), horizonte = Math.round(s.horizonte_dias / DIAS_POR_MES);
|
||||||
|
const celda = (f: string, c: string) => s.celdas.find(x => x.fila === f && x.columna === c);
|
||||||
|
const z = s.filas.map(f => s.columnas.map(c => { const x = celda(f.codigo, c.codigo); return x && !x.suprimido ? x.valor : null; }));
|
||||||
|
const texto = s.filas.map(f => s.columnas.map(c => {
|
||||||
|
const x = celda(f.codigo, c.codigo);
|
||||||
|
if (!x || x.suprimido) return '<span style="opacity:.75">Suprimido</span>';
|
||||||
|
const meses = Math.round(x.t_dias! / DIAS_POR_MES);
|
||||||
|
return `<b>${pct(x.valor!)} %</b><br>${miles(x.eventos!)} de ${miles(x.n!)}${meses < horizonte ? `<br>a ${meses} meses` : ''}`;
|
||||||
|
}));
|
||||||
|
const ayuda = s.filas.map(f => s.columnas.map(c => {
|
||||||
|
const x = celda(f.codigo, c.codigo);
|
||||||
|
if (!x || x.suprimido) return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}: suprimido (${(x?.motivo ?? 'sin datos').toLowerCase()})`;
|
||||||
|
return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}<br>${pct(x.valor!)} % (IC 95 %: ${pct(x.ic_bajo!)} a ${pct(x.ic_alto!)})<br>${miles(x.eventos!)} eventos en ${miles(x.n!)} pacientes`;
|
||||||
|
}));
|
||||||
|
const maximo = Math.max(1, ...z.flat().filter((v): v is number => v !== null));
|
||||||
|
return {
|
||||||
|
data: [
|
||||||
|
// The grey layer under the colour: the cells the answer suppressed.
|
||||||
|
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z: z.map(r => r.map(v => v === null ? 1 : null)),
|
||||||
|
colorscale: [[0, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9'], [1, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9']], showscale: false, hoverinfo: 'skip', xgap: 3, ygap: 3 },
|
||||||
|
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z, zmin: 0, zmax: maximo, xgap: 3, ygap: 3,
|
||||||
|
customdata: s.filas.map(f => s.columnas.map(c => [f.codigo, c.codigo])), text: ayuda, hovertemplate: '%{text}<extra></extra>',
|
||||||
|
colorscale: [[0, tema === 'oscuro' ? '#1B3A5B' : '#EAF1F8'], [1, tema === 'oscuro' ? '#9DBFE3' : '#1F5F8B']],
|
||||||
|
colorbar: { title: { text: nombreMedida(s.medida) + ' (%)' }, ticksuffix: ' %', thickness: 12 } },
|
||||||
|
],
|
||||||
|
layout: {
|
||||||
|
autosize: true, height: 80 + 64 * s.filas.length, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||||
|
margin: { t: 16, l: 16, r: 16, b: 56 },
|
||||||
|
xaxis: { title: { text: escapar(s.dimension_columnas.etiqueta) }, side: 'bottom', fixedrange: true, automargin: true },
|
||||||
|
yaxis: { title: { text: escapar(s.dimension_filas.etiqueta) }, autorange: 'reversed', fixedrange: true, automargin: true },
|
||||||
|
annotations: s.filas.flatMap((f, i) => s.columnas.map((c, j) => {
|
||||||
|
const v = z[i][j];
|
||||||
|
return { x: c.etiqueta, y: f.etiqueta, xref: 'x', yref: 'y', showarrow: false, text: texto[i][j], font: { size: 12, color: v !== null && v > maximo * .55 ? '#FFFFFF' : p.text } };
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
config: { displayModeBar: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const mesesDe = (dias: number) => Math.round(dias / DIAS_POR_MES);
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { inject, Injectable } from '@angular/core';
|
||||||
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
|
import { map } from 'rxjs';
|
||||||
|
import { Dominio, requireDominio } from './indicadores.models';
|
||||||
|
|
||||||
|
// Exploratory outcomes of a domain's cohort: what can be asked (`/analisis`) and its aggregate answer
|
||||||
|
// (`/analisis/resultados`). The answer is curves (C9b), tests, effects (C12) and checks (C13), never patient rows.
|
||||||
|
// The analysis goes by stages (development, recurrence, survival). Each stage has its scenarios, its estimators
|
||||||
|
// and the two variables it is stratified and filtered by; each variable says its NOM numeral and whether the schema
|
||||||
|
// records it or the answer assumes it.
|
||||||
|
export interface AnalisisOpcion { clave: string; etiqueta: string; }
|
||||||
|
// `filtro_seguimiento`: the follow-up list's filters that list this scenario's population.
|
||||||
|
export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; etapa: string; filtro_seguimiento: Record<string, string>; }
|
||||||
|
export interface AnalisisEstimador extends AnalisisOpcion { nota: string; }
|
||||||
|
export type EstadoVariable = 'registrado' | 'supuesto';
|
||||||
|
export interface AnalisisVariable extends AnalisisOpcion { nom: string; estado: EstadoVariable; fuente: string; opciones: { codigo: string; etiqueta: string }[]; }
|
||||||
|
export interface AnalisisEtapa extends AnalisisOpcion {
|
||||||
|
pregunta: string; escenarios: string[]; estimadores: string[]; medida: 'incidencia' | 'supervivencia';
|
||||||
|
// The variables the stage can be compared by: one at a time in the curves, two at a time in the grid.
|
||||||
|
variables: string[]; evento_supuesto: string | null;
|
||||||
|
// Every variable the NOM asks for at this stage, and whether the schema has it.
|
||||||
|
requeridas: { variable: string; nom: string; estado: string }[];
|
||||||
|
}
|
||||||
|
export interface AnalisisBloqueado { clave: string; titulo: string; motivo: string; }
|
||||||
|
export interface AnalisisCatalogo {
|
||||||
|
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||||
|
etapas: AnalisisEtapa[]; escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[];
|
||||||
|
variables: AnalisisVariable[]; bloqueados: AnalisisBloqueado[];
|
||||||
|
}
|
||||||
|
// `grupos`: the values of the variable to compare, two or more; empty compares them all.
|
||||||
|
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; grupos: string[]; filtros: Record<string, string>; }
|
||||||
|
export interface PedidoSubgrupos { escenario: string; estimador: string; filas: string; columnas: string; }
|
||||||
|
// The log-rank of one variable of the grid, plain and at equal value of the other one.
|
||||||
|
export interface PruebaCruzada {
|
||||||
|
variable: string; etiqueta: string; estratificada_por: string; etiqueta_estrato: string;
|
||||||
|
logrank: { chi2: number; gl: number; p: number; grupos: number } | null; estratificado: { chi2: number; gl: number; p: number; grupos: number } | null;
|
||||||
|
}
|
||||||
|
// One epidemiological figure of the cohort at the horizon (incidence, recurrence, adherence or survival).
|
||||||
|
export interface IndicadorEpidemiologico {
|
||||||
|
clave: string; titulo: string; etapa: string; unidad: string; descripcion: string; supuesto: string | null; suprimido: boolean;
|
||||||
|
n: number | null; eventos: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; t_dias: number | null;
|
||||||
|
}
|
||||||
|
export interface AnalisisIndicadores { simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; indicadores: IndicadorEpidemiologico[]; }
|
||||||
|
|
||||||
|
export interface GrupoAnalisis { grupo: string; etiqueta: string; color: string; suprimido: boolean; motivo: string | null; n: number | null; eventos: number | null; competitivos: number | null; }
|
||||||
|
// C9b: one row per group and event time; a suppressed row ends the published curve.
|
||||||
|
export interface PuntoCurva { grupo: string; t: number; estimador: 'KM' | 'CIF'; valor: number | null; ic_bajo: number | null; ic_alto: number | null; n_riesgo: number | null; n_eventos: number | null; suprimido: 0 | 1; }
|
||||||
|
// C12
|
||||||
|
export interface FilaEfecto { termino: string; etiqueta: string; hr: number; ic_bajo: number; ic_alto: number; n_eventos: number; metodo: 'cox' | 'bayes'; ph_p: number | null; }
|
||||||
|
export interface Efectos { estado: 'listo' | 'insuficiente' | 'no_aplica'; motivo: string | null; metodo: string; referencia: string | null; etiqueta_referencia?: string; filas: FilaEfecto[]; }
|
||||||
|
// C13
|
||||||
|
export interface FilaValidacion { chequeo: string; escopo: string; estadistico: number | null; p: number | null; umbral: number | null; aprobado: boolean | null; nota: string | null; version_modelo: string; sql_sha: string | null; }
|
||||||
|
export interface AnalisisResultados {
|
||||||
|
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||||
|
etapa: string; medida: 'incidencia' | 'supervivencia';
|
||||||
|
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; grupos_elegidos: string[] | null;
|
||||||
|
// What of this answer rests on data the schema does not record.
|
||||||
|
supuestos: string[];
|
||||||
|
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
|
||||||
|
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
|
||||||
|
tabla_riesgo: { cortes_dias: number[]; filas: { grupo: string; cortes: (number | null)[] }[] };
|
||||||
|
pruebas: {
|
||||||
|
logrank: { chi2: number; gl: number; p: number } | null;
|
||||||
|
pares: { a: string; b: string; p: number; p_holm: number }[];
|
||||||
|
rmst: { grupo: string; rmst: number; dif: number | null; ic_bajo: number | null; ic_alto: number | null }[];
|
||||||
|
rmst_referencia?: string; nota: string | null;
|
||||||
|
};
|
||||||
|
efectos: Efectos; validacion: FilaValidacion[]; avisos: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The BI-RADS by age-group grid: the incidence at the horizon in each cell, or the reason it is suppressed.
|
||||||
|
export interface CeldaSubgrupo {
|
||||||
|
fila: string; columna: string; suprimido: boolean; motivo: string | null;
|
||||||
|
n: number | null; eventos: number | null; t_dias: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
|
||||||
|
}
|
||||||
|
export interface AnalisisSubgrupos {
|
||||||
|
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; escenario: string; estimador: string;
|
||||||
|
etapa: string; medida: 'incidencia' | 'supervivencia'; supuestos: string[];
|
||||||
|
dimension_filas: AnalisisOpcion; dimension_columnas: AnalisisOpcion; pruebas: PruebaCruzada[];
|
||||||
|
filas: { codigo: string; etiqueta: string }[]; columnas: { codigo: string; etiqueta: string }[]; celdas: CeldaSubgrupo[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
|
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||||
|
const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||||
|
const numONulo = (v: unknown) => v === null || num(v);
|
||||||
|
const lista = (v: unknown, f: (x: unknown) => boolean) => Array.isArray(v) && v.every(f);
|
||||||
|
const opcion = (v: unknown) => record(v) && text(v['clave']) && text(v['etiqueta']);
|
||||||
|
// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
|
||||||
|
const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
|
||||||
|
function sinFilasDePaciente(v: unknown): boolean {
|
||||||
|
if (Array.isArray(v)) return v.every(sinFilasDePaciente);
|
||||||
|
if (!record(v)) return true;
|
||||||
|
return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
|
||||||
|
}
|
||||||
|
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
||||||
|
|
||||||
|
export function analisisCatalogo(v: unknown): AnalisisCatalogo {
|
||||||
|
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||||
|
if (!text(v['corte']) || !num(v['horizonte_dias']) || !num(v['umbral_supresion'])
|
||||||
|
|| !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion']) && text(e['etapa'])
|
||||||
|
&& record(e['filtro_seguimiento']) && Object.values(e['filtro_seguimiento']).every(text)) || !(v['escenarios'] as unknown[]).length
|
||||||
|
|| !lista(v['estimadores'], e => opcion(e) && record(e) && text(e['nota'])) || !(v['estimadores'] as unknown[]).length
|
||||||
|
|| !lista(v['variables'], x => opcion(x) && record(x) && text(x['nom']) && ['registrado', 'supuesto'].includes(x['estado'] as string)
|
||||||
|
&& text(x['fuente']) && lista(x['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
|
||||||
|
|| !lista(v['etapas'], e => opcion(e) && record(e) && text(e['pregunta']) && ['incidencia', 'supervivencia'].includes(e['medida'] as string)
|
||||||
|
&& lista(e['escenarios'], text) && (e['escenarios'] as unknown[]).length > 0 && lista(e['estimadores'], text) && (e['estimadores'] as unknown[]).length > 0
|
||||||
|
&& lista(e['variables'], text) && (e['variables'] as unknown[]).length >= 2 && lista(e['requeridas'], record)) || !(v['etapas'] as unknown[]).length
|
||||||
|
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|
||||||
|
|| !sinFilasDePaciente(v)) invalido();
|
||||||
|
return v as unknown as AnalisisCatalogo;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function analisisResultados(v: unknown): AnalisisResultados {
|
||||||
|
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||||
|
if (!['incidencia', 'supervivencia'].includes(v['medida'] as string) || !lista(v['supuestos'], text)) invalido();
|
||||||
|
const pob = v['poblacion'], tabla = v['tabla_riesgo'], pruebas = v['pruebas'], efectos = v['efectos'];
|
||||||
|
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador']) || !text(v['estrato'])
|
||||||
|
|| !record(v['filtros']) || !record(pob) || !numONulo(pob['n']) || !numONulo(pob['eventos'])
|
||||||
|
|| !lista(v['grupos'], g => record(g) && text(g['grupo']) && text(g['etiqueta']) && text(g['color']) && typeof g['suprimido'] === 'boolean'
|
||||||
|
&& numONulo(g['n']) && numONulo(g['eventos']) && (!g['suprimido'] || g['n'] === null && g['eventos'] === null))
|
||||||
|
|| !lista(v['curvas'], c => record(c) && text(c['grupo']) && num(c['t']) && (c['estimador'] === 'KM' || c['estimador'] === 'CIF')
|
||||||
|
&& (c['suprimido'] === 1 ? c['valor'] === null && c['n_riesgo'] === null : num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['n_riesgo'])))
|
||||||
|
|| !record(tabla) || !lista(tabla['cortes_dias'], num) || !lista(tabla['filas'], f => record(f) && text(f['grupo']) && lista(f['cortes'], numONulo))
|
||||||
|
|| !record(pruebas) || !lista(pruebas['pares'], record) || !lista(pruebas['rmst'], record)
|
||||||
|
|| !record(efectos) || !['listo', 'insuficiente', 'no_aplica'].includes(efectos['estado'] as string)
|
||||||
|
|| !lista(efectos['filas'], f => record(f) && text(f['termino']) && num(f['hr']) && num(f['ic_bajo']) && num(f['ic_alto']) && num(f['n_eventos']))
|
||||||
|
|| !lista(v['validacion'], f => record(f) && text(f['chequeo']) && text(f['escopo']) && (f['aprobado'] === null || typeof f['aprobado'] === 'boolean'))
|
||||||
|
|| !lista(v['avisos'], text)) invalido();
|
||||||
|
// A published point must stay at or above the threshold of patients at risk.
|
||||||
|
const umbral = v['umbral_supresion'] as number;
|
||||||
|
if ((v['curvas'] as PuntoCurva[]).some(c => c.suprimido === 0 && c.n_riesgo! < umbral)) invalido();
|
||||||
|
return v as unknown as AnalisisResultados;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function analisisSubgrupos(v: unknown): AnalisisSubgrupos {
|
||||||
|
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||||
|
const eje = (x: unknown) => lista(x, o => record(o) && text(o['codigo']) && text(o['etiqueta']));
|
||||||
|
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador'])
|
||||||
|
|| !eje(v['filas']) || !eje(v['columnas']) || !opcion(v['dimension_filas']) || !opcion(v['dimension_columnas']) || !lista(v['supuestos'], text)
|
||||||
|
|| !lista(v['pruebas'], x => record(x) && text(x['variable']) && text(x['estratificada_por']) && (x['logrank'] === null || record(x['logrank'])) && (x['estratificado'] === null || record(x['estratificado'])))
|
||||||
|
|| !lista(v['celdas'], c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean'
|
||||||
|
&& (c['suprimido'] ? c['n'] === null && c['eventos'] === null && c['valor'] === null
|
||||||
|
: num(c['n']) && num(c['eventos']) && num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['t_dias'])))) invalido();
|
||||||
|
// A published cell never has fewer patients or events than the threshold.
|
||||||
|
const umbral = v['umbral_supresion'] as number;
|
||||||
|
if ((v['celdas'] as CeldaSubgrupo[]).some(c => !c.suprimido && (c.n! < umbral || c.eventos! < umbral))) invalido();
|
||||||
|
return v as unknown as AnalisisSubgrupos;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function analisisIndicadores(v: unknown): AnalisisIndicadores {
|
||||||
|
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||||
|
if (!sinFilasDePaciente(v) || !num(v['umbral_supresion']) || !lista(v['indicadores'], x => record(x) && text(x['clave']) && text(x['titulo'])
|
||||||
|
&& text(x['descripcion']) && typeof x['suprimido'] === 'boolean'
|
||||||
|
&& (x['suprimido'] ? x['valor'] === null && x['eventos'] === null : num(x['valor']) && num(x['n']) && num(x['eventos'])))) invalido();
|
||||||
|
// A published figure never stands on fewer patients than the threshold.
|
||||||
|
if ((v['indicadores'] as IndicadorEpidemiologico[]).some(x => !x.suprimido && x.n! < (v['umbral_supresion'] as number))) invalido();
|
||||||
|
return v as unknown as AnalisisIndicadores;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({ providedIn: 'root' })
|
||||||
|
export class AnalisisService {
|
||||||
|
private readonly http = inject(HttpClient);
|
||||||
|
catalogo(dominio: Dominio) {
|
||||||
|
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis`).pipe(map(analisisCatalogo));
|
||||||
|
}
|
||||||
|
resultados(dominio: Dominio, pedido: AnalisisPedido) {
|
||||||
|
let params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('estrato', pedido.estrato);
|
||||||
|
if (pedido.grupos.length) params = params.set('grupos', pedido.grupos.join(','));
|
||||||
|
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
|
||||||
|
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/resultados`, { params }).pipe(map(analisisResultados));
|
||||||
|
}
|
||||||
|
subgrupos(dominio: Dominio, pedido: PedidoSubgrupos) {
|
||||||
|
const params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('filas', pedido.filas).set('columnas', pedido.columnas);
|
||||||
|
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/subgrupos`, { params }).pipe(map(analisisSubgrupos));
|
||||||
|
}
|
||||||
|
indicadores(dominio: Dominio) {
|
||||||
|
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`).pipe(map(analisisIndicadores));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
import { Component, output } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import {
|
||||||
|
IndicadoresAnalisis, SeleccionPacientes, celdaDelClic, cruceDeEtapa, grupoDelClic, pedidoDeEtapa, seleccionDeCelda, seleccionDeCurva,
|
||||||
|
} from './indicadores-analisis';
|
||||||
|
import { curvasFigura, forestFigura, subgruposFigura } from './indicadores-analisis-figuras';
|
||||||
|
import {
|
||||||
|
AnalisisCatalogo, AnalisisIndicadores, AnalisisResultados, AnalisisSubgrupos, analisisCatalogo, analisisIndicadores, analisisResultados, analisisSubgrupos,
|
||||||
|
} from './indicadores-analisis.service';
|
||||||
|
|
||||||
|
// Covers the «Análisis epidemiológico» tab of breast cancer: the guards of its answers (aggregates only, nothing
|
||||||
|
// under the threshold), the figures built from them, the selections a curve or a cell sends to Seguimiento, and the
|
||||||
|
// tab's requests: the epidemiological figures, the curves of two or more values of one variable, and the heatmap of
|
||||||
|
// two distinct variables.
|
||||||
|
// Fixtures, all built below: `catalogo` (two stages, development with three variables and survival with two, one of
|
||||||
|
// them assumed; one blocked analysis), `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model),
|
||||||
|
// `subgrupos` (a two-by-two BI-RADS and age grid with one suppressed cell and its crossed tests) and `indicadores`
|
||||||
|
// (one published figure and one suppressed).
|
||||||
|
|
||||||
|
const catalogo = (): AnalisisCatalogo => ({
|
||||||
|
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
|
||||||
|
etapas: [
|
||||||
|
{ clave: 'desarrollo', etiqueta: 'Desarrollo', pregunta: '¿Quién llega a cáncer?', escenarios: ['diagnostico', 'incidencia'], estimadores: ['cif', 'km'],
|
||||||
|
medida: 'incidencia', variables: ['birads', 'grupo_edad', 'brca'], evento_supuesto: null,
|
||||||
|
requeridas: [{ variable: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado' }] },
|
||||||
|
{ clave: 'supervivencia', etiqueta: 'Supervivencia', pregunta: '¿Quién sigue viva?', escenarios: ['supervivencia'], estimadores: ['km'],
|
||||||
|
medida: 'supervivencia', variables: ['estadio', 'grupo_edad'], evento_supuesto: 'Estado vital supuesto.',
|
||||||
|
requeridas: [{ variable: 'Estado vital y causa de muerte', nom: '16.8', estado: 'supuesto' }] },
|
||||||
|
],
|
||||||
|
escenarios: [
|
||||||
|
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más', etapa: 'desarrollo', filtro_seguimiento: {} },
|
||||||
|
{ clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna', etapa: 'desarrollo', filtro_seguimiento: { resultado: 'BENIGNO' } },
|
||||||
|
{ clave: 'supervivencia', etiqueta: 'Supervivencia', evento: 'Muerte', origen: 'Diagnóstico', poblacion: 'Cáncer invasor', etapa: 'supervivencia', filtro_seguimiento: { resultado: 'INVASOR' } },
|
||||||
|
],
|
||||||
|
estimadores: [{ clave: 'km', etiqueta: '1 − Kaplan-Meier', nota: 'Censura la muerte.' }, { clave: 'cif', etiqueta: 'Aalen-Johansen', nota: 'Muerte competitiva.' }],
|
||||||
|
variables: [
|
||||||
|
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado', fuente: 'mastografia.birads',
|
||||||
|
opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }, { codigo: 'B6', etiqueta: 'BI-RADS 6' }] },
|
||||||
|
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', nom: '16.5', estado: 'registrado', fuente: 'paciente.fecha_nacimiento',
|
||||||
|
opciones: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }] },
|
||||||
|
{ clave: 'brca', etiqueta: 'BRCA1/2', nom: 'Factores de riesgo', estado: 'supuesto', fuente: 'Prueba genética.',
|
||||||
|
opciones: [{ codigo: 'BRCA1', etiqueta: 'Mutación BRCA1' }, { codigo: 'NEGATIVO', etiqueta: 'Sin mutación' }] },
|
||||||
|
{ clave: 'estadio', etiqueta: 'Estadio clínico', nom: '10.3.2', estado: 'supuesto', fuente: 'Nota de oncología.',
|
||||||
|
opciones: [{ codigo: 'I', etiqueta: 'Estadio I' }, { codigo: 'IV', etiqueta: 'Estadio IV' }] },
|
||||||
|
],
|
||||||
|
bloqueados: [{ clave: 'sobrevida', titulo: 'Sobrevida por etapa clínica', motivo: 'No hay etapa clínica ni estado vital.' }],
|
||||||
|
});
|
||||||
|
const punto = (grupo: string, t: number, valor: number, n_riesgo: number, n_eventos: number) =>
|
||||||
|
({ grupo, t, estimador: 'CIF' as const, valor, ic_bajo: valor * .8, ic_alto: valor * 1.2, n_riesgo, n_eventos, suprimido: 0 as const });
|
||||||
|
const resultados = (): AnalisisResultados => ({
|
||||||
|
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
|
||||||
|
escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {}, grupos_elegidos: null,
|
||||||
|
poblacion: { n: null, eventos: null, totales_ocultos: true, seguimiento_mediano_dias: 700 },
|
||||||
|
grupos: [
|
||||||
|
{ grupo: 'B4A', etiqueta: 'BI-RADS 4A', color: '#1F5F8B', suprimido: false, motivo: null, n: 180, eventos: 11, competitivos: null },
|
||||||
|
{ grupo: 'B5', etiqueta: 'BI-RADS 5', color: '#C26A2B', suprimido: false, motivo: null, n: 120, eventos: 100, competitivos: null },
|
||||||
|
{ grupo: 'B6', etiqueta: 'BI-RADS 6', color: '#4E8A4B', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, competitivos: null },
|
||||||
|
],
|
||||||
|
curvas: [punto('B4A', 0, 0, 180, 0), punto('B4A', 90, 4, 150, 7), punto('B4A', 730, 6, 90, 11),
|
||||||
|
punto('B5', 0, 0, 120, 0), punto('B5', 40, 70, 30, 85),
|
||||||
|
{ grupo: 'B5', t: 300, estimador: 'CIF', valor: null, ic_bajo: null, ic_alto: null, n_riesgo: null, n_eventos: null, suprimido: 1 }],
|
||||||
|
tabla_riesgo: { cortes_dias: [0, 365, 730], filas: [{ grupo: 'B4A', cortes: [180, 130, 90] }, { grupo: 'B5', cortes: [120, 6, null] }] },
|
||||||
|
pruebas: { logrank: { chi2: 120.5, gl: 1, p: 1e-20 }, pares: [{ a: 'B4A', b: 'B5', p: 1e-20, p_holm: 1e-20 }],
|
||||||
|
rmst: [{ grupo: 'B4A', rmst: 700, dif: null, ic_bajo: null, ic_alto: null }, { grupo: 'B5', rmst: 210, dif: -490, ic_bajo: -520, ic_alto: -460 }],
|
||||||
|
rmst_referencia: 'B4A', nota: 'Prueba de Gray pendiente.' },
|
||||||
|
efectos: { estado: 'listo', motivo: null, metodo: 'cox', referencia: 'B4A', etiqueta_referencia: 'BI-RADS 4A',
|
||||||
|
filas: [{ termino: 'B5', etiqueta: 'BI-RADS 5', hr: 30, ic_bajo: 16, ic_alto: 59, n_eventos: 100, metodo: 'cox', ph_p: .01 }] },
|
||||||
|
validacion: [{ chequeo: 'Eventos por grupo', escopo: 'BI-RADS 6', estadistico: null, p: null, umbral: 5, aprobado: false, nota: 'Menos de 5 eventos', version_modelo: 'mock-0.1', sql_sha: null }],
|
||||||
|
avisos: ['Análisis descriptivo, no causal.', 'Horizonte de 2 años (730 días).', 'Requiere el estado vital.'],
|
||||||
|
});
|
||||||
|
const subgrupos = (): AnalisisSubgrupos => ({
|
||||||
|
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
|
||||||
|
etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
|
||||||
|
dimension_filas: { clave: 'birads', etiqueta: 'Categoría BI-RADS' }, dimension_columnas: { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
|
||||||
|
pruebas: [{ variable: 'birads', etiqueta: 'Categoría BI-RADS', estratificada_por: 'grupo_edad', etiqueta_estrato: 'Grupo de edad',
|
||||||
|
logrank: { chi2: 90, gl: 1, p: 1e-10, grupos: 2 }, estratificado: { chi2: 85, gl: 1, p: 1e-9, grupos: 2 } },
|
||||||
|
{ variable: 'grupo_edad', etiqueta: 'Grupo de edad', estratificada_por: 'birads', etiqueta_estrato: 'Categoría BI-RADS', logrank: null, estratificado: null }],
|
||||||
|
filas: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }],
|
||||||
|
columnas: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }],
|
||||||
|
celdas: [
|
||||||
|
{ fila: 'B4A', columna: '40-49', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, t_dias: null, valor: null, ic_bajo: null, ic_alto: null },
|
||||||
|
{ fila: 'B4A', columna: '50-59', suprimido: false, motivo: null, n: 60, eventos: 6, t_dias: 730, valor: 10, ic_bajo: 4, ic_alto: 20 },
|
||||||
|
{ fila: 'B5', columna: '40-49', suprimido: false, motivo: null, n: 40, eventos: 36, t_dias: 120, valor: 90, ic_bajo: 78, ic_alto: 96 },
|
||||||
|
{ fila: 'B5', columna: '50-59', suprimido: false, motivo: null, n: 50, eventos: 45, t_dias: 730, valor: 92, ic_bajo: 81, ic_alto: 97 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const indicadores = (): AnalisisIndicadores => ({
|
||||||
|
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, indicadores: [
|
||||||
|
{ clave: 'desarrollo', titulo: 'Incidencia de cáncer a 24 meses', etapa: 'desarrollo', unidad: '%', descripcion: 'Llegan a cáncer.', supuesto: null,
|
||||||
|
suprimido: false, n: 600, eventos: 274, valor: 45.7, ic_bajo: 41.6, ic_alto: 49.6, t_dias: 730 },
|
||||||
|
{ clave: 'recaida', titulo: 'Recaída a 24 meses', etapa: 'recaida', unidad: '%', descripcion: 'Recaen.', supuesto: 'Recaída supuesta.',
|
||||||
|
suprimido: true, n: null, eventos: null, valor: null, ic_bajo: null, ic_alto: null, t_dias: null },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Respuestas del análisis', () => {
|
||||||
|
it('admiten solo agregados de demostración', () => {
|
||||||
|
// Fails if the guards stop rejecting real records or anything shaped like a patient row, at any depth.
|
||||||
|
expect(analisisResultados(resultados()).grupos).toHaveLength(3);
|
||||||
|
expect(analisisCatalogo(catalogo()).etapas).toHaveLength(2);
|
||||||
|
expect(analisisIndicadores(indicadores()).indicadores).toHaveLength(2);
|
||||||
|
expect(() => analisisResultados({ ...resultados(), simulado: false })).toThrow();
|
||||||
|
expect(() => analisisResultados({ ...resultados(), pruebas: { ...resultados().pruebas, items: [{ id_seudonimo: 'M-1' }] } })).toThrow();
|
||||||
|
expect(() => analisisCatalogo({ ...catalogo(), pacientes: [] })).toThrow();
|
||||||
|
});
|
||||||
|
it('rechazan cifras bajo el umbral: un punto de curva, un grupo suprimido con conteos, una celda o un indicador', () => {
|
||||||
|
// Fails if a curve's tail, a suppressed group, a heatmap cell or an epidemiological figure can carry counts under the threshold.
|
||||||
|
const r = resultados();
|
||||||
|
expect(() => analisisResultados({ ...r, curvas: [...r.curvas, punto('B4A', 740, 7, 3, 12)] })).toThrow();
|
||||||
|
expect(() => analisisResultados({ ...r, grupos: r.grupos.map(g => g.suprimido ? { ...g, n: 4 } : g) })).toThrow();
|
||||||
|
expect(() => analisisSubgrupos({ ...subgrupos(), celdas: subgrupos().celdas.map(c => c.suprimido ? c : { ...c, eventos: 3 }) })).toThrow();
|
||||||
|
expect(() => analisisIndicadores({ ...indicadores(), indicadores: [{ ...indicadores().indicadores[0], n: 3 }] })).toThrow();
|
||||||
|
});
|
||||||
|
it('una etapa necesita al menos dos variables para comparar', () => {
|
||||||
|
// Fails if a stage with a single variable reaches the curves or the heatmap, which compare two or more.
|
||||||
|
expect(() => analisisCatalogo({ ...catalogo(), etapas: [{ ...catalogo().etapas[0], variables: ['birads'] }] })).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Figuras del análisis', () => {
|
||||||
|
it('dibuja una curva con su banda por grupo publicado y la corta donde la respuesta la suprime', () => {
|
||||||
|
// Fails if a suppressed group gets a trace, the curve runs past its suppressed tail, or a line loses its group.
|
||||||
|
const fig = curvasFigura(resultados(), 'claro');
|
||||||
|
const lineas = fig.data.filter(t => t['meta']);
|
||||||
|
expect(lineas.map(t => t['meta'])).toEqual(['B4A', 'B5']);
|
||||||
|
expect(fig.data).toHaveLength(6);
|
||||||
|
expect(lineas[1]['y'] as number[]).toEqual([0, 70]);
|
||||||
|
});
|
||||||
|
it('en la etapa de supervivencia la curva baja desde 100 % y el eje dice Supervivencia', () => {
|
||||||
|
// Fails if the survival stage is drawn on the incidence axis.
|
||||||
|
const r = resultados();
|
||||||
|
const fig = curvasFigura({ ...r, medida: 'supervivencia', curvas: r.curvas.map(c => c.valor === null ? c : { ...c, valor: 100 - c.valor, ic_bajo: 100 - c.ic_alto!, ic_alto: 100 - c.ic_bajo! }) }, 'claro');
|
||||||
|
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Supervivencia (%)');
|
||||||
|
expect((fig.data.find(t => t['meta'] === 'B4A')!['y'] as number[])[0]).toBe(100);
|
||||||
|
});
|
||||||
|
it('marca vacío el HR con riesgos no proporcionales y no dibuja nada sin modelo', () => {
|
||||||
|
// Fails if the forest plot hides the PH warning or draws an effect the answer did not publish.
|
||||||
|
const fig = forestFigura(resultados(), 'claro');
|
||||||
|
expect((fig.data[1]['marker'] as { color: string[] }).color[0]).toBe('#FFFFFF');
|
||||||
|
expect(forestFigura({ ...resultados(), efectos: { ...resultados().efectos, estado: 'insuficiente', filas: [] } }, 'claro').data).toEqual([]);
|
||||||
|
});
|
||||||
|
it('el mapa de calor dibuja gris lo suprimido y nombra sus dos variables', () => {
|
||||||
|
// Fails if a suppressed cell is drawn as a colour, or the axes stop naming the variables chosen.
|
||||||
|
const fig = subgruposFigura(subgrupos(), 'claro');
|
||||||
|
expect((fig.data[1]['z'] as (number | null)[][])[0]).toEqual([null, 10]);
|
||||||
|
expect((fig.data[0]['z'] as (number | null)[][])[0]).toEqual([1, null]);
|
||||||
|
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Categoría BI-RADS');
|
||||||
|
expect((fig.layout['annotations'] as { text: string }[])[2].text).toContain('a 4 meses');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Selecciones que van a Seguimiento', () => {
|
||||||
|
it('una curva lleva la población del escenario y el valor del grupo', () => {
|
||||||
|
// Fails if a curve opens a list wider than its own patients, or names another group.
|
||||||
|
const pedido = { escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} };
|
||||||
|
expect(grupoDelClic({ points: [{ data: { meta: 'IV' } }] })).toBe('IV');
|
||||||
|
expect(grupoDelClic({ points: [{ data: {} }] })).toBeUndefined();
|
||||||
|
expect(seleccionDeCurva(catalogo(), pedido, 'IV')).toEqual({ filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio clínico, Estadio IV' });
|
||||||
|
expect(seleccionDeCurva(catalogo(), pedido, 'XX')).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('una celda lleva sus dos valores, y una celda gris nada', () => {
|
||||||
|
// Fails if a click on a suppressed cell could open the patients the answer hid.
|
||||||
|
expect(celdaDelClic({ points: [{ customdata: ['B5', '40-49'], z: 90 }] })).toEqual({ fila: 'B5', columna: '40-49' });
|
||||||
|
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
|
||||||
|
expect(seleccionDeCelda(catalogo(), subgrupos(), { fila: 'B5', columna: '40-49' }))
|
||||||
|
.toEqual({ filtros: { birads: 'B5', grupo_edad: '40-49' }, etiqueta: 'Cáncer confirmado: BI-RADS 5 y 40-49 años' });
|
||||||
|
});
|
||||||
|
it('cada etapa abre con su primera variable y su primer cruce, y conserva un cruce que le pertenece', () => {
|
||||||
|
// Fails if a stage keeps another stage's variable or an estimator it does not admit.
|
||||||
|
expect(pedidoDeEtapa(catalogo(), 'supervivencia', { escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', grupos: ['B5', 'B6'], filtros: {} }))
|
||||||
|
.toEqual({ escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} });
|
||||||
|
const [desarrollo, supervivencia] = catalogo().etapas;
|
||||||
|
expect(cruceDeEtapa(desarrollo, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'brca', columnas: 'birads' });
|
||||||
|
expect(cruceDeEtapa(supervivencia, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'estadio', columnas: 'grupo_edad' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||||
|
class ChartStub { readonly plotClick = output<unknown>(); }
|
||||||
|
|
||||||
|
describe('Pestaña Análisis epidemiológico', () => {
|
||||||
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
|
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
|
||||||
|
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
|
||||||
|
});
|
||||||
|
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||||
|
const text = () => fixture.nativeElement.textContent as string;
|
||||||
|
const curvas = () => http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||||
|
const abrir = () => {
|
||||||
|
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||||
|
http.expectOne('/cama/analisis').flush(catalogo()); fixture.detectChanges();
|
||||||
|
http.expectOne('/cama/analisis/indicadores').flush(indicadores());
|
||||||
|
};
|
||||||
|
|
||||||
|
it('no pide nada hasta abrirse; luego los indicadores y la primera variable con todos sus valores', () => {
|
||||||
|
// Fails if the tab loads while hidden, or its first request stops being the stage's first variable.
|
||||||
|
fixture.detectChanges();
|
||||||
|
http.expectNone('/cama/analisis');
|
||||||
|
abrir();
|
||||||
|
const req = curvas();
|
||||||
|
expect(['escenario', 'estimador', 'estrato', 'grupos'].map(k => req.request.params.get(k))).toEqual(['diagnostico', 'cif', 'birads', null]);
|
||||||
|
req.flush(resultados()); fixture.detectChanges();
|
||||||
|
expect(text()).toContain('Indicadores epidemiológicos');
|
||||||
|
expect(text()).toContain('IC 95 %: 41.6 a 49.6 %');
|
||||||
|
expect(text()).toContain('Dato oculto por tamaño');
|
||||||
|
expect(text()).toContain('Grupos suprimidos: BI-RADS 6');
|
||||||
|
});
|
||||||
|
it('compara dos o más grupos: con uno avisa y no consulta; con todos no los nombra', () => {
|
||||||
|
// Fails if a single group is sent for a log-rank, or a full selection is sent as a list.
|
||||||
|
abrir(); curvas().flush(resultados());
|
||||||
|
const tab = fixture.componentInstance;
|
||||||
|
tab.elegirGrupos(['B5']); fixture.detectChanges();
|
||||||
|
http.expectNone(r => r.url === '/cama/analisis/resultados');
|
||||||
|
expect(text()).toContain('Elija al menos dos grupos para comparar.');
|
||||||
|
tab.elegirGrupos(['B4A', 'B5']);
|
||||||
|
let req = curvas(); expect(req.request.params.get('grupos')).toBe('B4A,B5'); req.flush(resultados());
|
||||||
|
tab.elegirGrupos(['B4A', 'B5', 'B6']);
|
||||||
|
req = curvas(); expect(req.request.params.has('grupos')).toBe(false); req.flush(resultados());
|
||||||
|
tab.estratificar('brca');
|
||||||
|
req = curvas(); expect([req.request.params.get('estrato'), req.request.params.get('grupos')]).toEqual(['brca', null]); req.flush(resultados());
|
||||||
|
});
|
||||||
|
it('el mapa de calor se pide al abrir su parte, con filas y columnas distintas que se eligen por separado', () => {
|
||||||
|
// Fails if the grid loads with the tab, repeats a request without a change, or accepts the same variable twice.
|
||||||
|
abrir(); curvas().flush(resultados());
|
||||||
|
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
||||||
|
const tab = fixture.componentInstance;
|
||||||
|
tab.elegirVista('subgrupos'); fixture.detectChanges();
|
||||||
|
let req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||||
|
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'grupo_edad']);
|
||||||
|
req.flush(subgrupos()); fixture.detectChanges();
|
||||||
|
expect(text()).toContain('Estratificado por la otra');
|
||||||
|
tab.cruzar({ columnas: 'birads' }); fixture.detectChanges();
|
||||||
|
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
||||||
|
tab.cruzar({ columnas: 'brca' }); fixture.detectChanges();
|
||||||
|
req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||||
|
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'brca']);
|
||||||
|
req.flush(subgrupos());
|
||||||
|
});
|
||||||
|
it('una curva, su botón de la tabla o una celda emiten la selección para Seguimiento', () => {
|
||||||
|
// Fails if a click stops reaching Seguimiento, or sends a selection without the scenario's population.
|
||||||
|
const emitidas: SeleccionPacientes[] = [];
|
||||||
|
fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
|
||||||
|
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||||
|
fixture.componentInstance.clicCurva({ points: [{ data: { meta: 'B5' } }] });
|
||||||
|
(fixture.nativeElement.querySelector('.riesgo .ver') as HTMLButtonElement).click();
|
||||||
|
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
|
||||||
|
http.expectOne(r => r.url === '/cama/analisis/subgrupos').flush(subgrupos()); fixture.detectChanges();
|
||||||
|
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B5', '50-59'], z: 92 }] });
|
||||||
|
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B4A', '40-49'], z: null }] });
|
||||||
|
expect(emitidas.map(e => e.filtros)).toEqual([{ birads: 'B5' }, { birads: 'B4A' }, { birads: 'B5', grupo_edad: '50-59' }]);
|
||||||
|
});
|
||||||
|
it('cambiar de etapa pide su primera variable y anuncia lo supuesto', () => {
|
||||||
|
// Fails if a stage keeps another stage's variable or an estimator it does not admit, or hides its assumptions.
|
||||||
|
abrir(); curvas().flush(resultados());
|
||||||
|
fixture.componentInstance.elegirEtapa('supervivencia'); fixture.detectChanges();
|
||||||
|
const req = curvas();
|
||||||
|
expect(['escenario', 'estimador', 'estrato'].map(k => req.request.params.get(k))).toEqual(['supervivencia', 'km', 'estadio']);
|
||||||
|
req.flush({ ...resultados(), etapa: 'supervivencia', medida: 'supervivencia', escenario: 'supervivencia', estimador: 'km', estrato: 'estadio',
|
||||||
|
supuestos: ['Estado vital supuesto.'] });
|
||||||
|
fixture.detectChanges();
|
||||||
|
expect(text()).toContain('¿Quién sigue viva?');
|
||||||
|
expect(fixture.nativeElement.querySelector('.supuestos')?.textContent).toContain('Estado vital supuesto.');
|
||||||
|
expect(fixture.nativeElement.querySelector('#analisis-curvas h2')?.textContent).toContain('Supervivencia a 24 meses');
|
||||||
|
});
|
||||||
|
it('el diagnóstico muestra el estado de la cohorte, la validación y las variables de la NOM', () => {
|
||||||
|
// Fails if the cohort's status loses a figure, or a hidden total is shown as a number.
|
||||||
|
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||||
|
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
|
||||||
|
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
|
||||||
|
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
|
||||||
|
expect(diagnostico.querySelector('.requeridas')?.textContent).toContain('Categoría BI-RADS');
|
||||||
|
expect(diagnostico.querySelector('tr.falla')?.textContent).toContain('No cumple');
|
||||||
|
});
|
||||||
|
it('las flechas mueven entre las tres partes', () => {
|
||||||
|
// Fails if the parts stop behaving as a keyboard tab list.
|
||||||
|
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||||
|
const lista = fixture.nativeElement.querySelector('.subsecciones') as HTMLElement;
|
||||||
|
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
|
||||||
|
expect(fixture.componentInstance.vista()).toBe('diagnostico');
|
||||||
|
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
|
||||||
|
expect(fixture.componentInstance.vista()).toBe('curvas');
|
||||||
|
});
|
||||||
|
it('sin análisis publicado queda pendiente', () => {
|
||||||
|
// Fails if a 404 on the catalog is shown as an error instead of a feature not yet published.
|
||||||
|
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||||
|
http.expectOne('/cama/analisis').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
|
||||||
|
expect(text()).toContain('Funcionalidad pendiente de publicación');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,535 @@
|
|||||||
|
import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
|
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||||
|
import { curvasFigura, forestFigura, mesesDe, nombreMedida, subgruposFigura } from './indicadores-analisis-figuras';
|
||||||
|
import {
|
||||||
|
AnalisisCatalogo, AnalisisEtapa, AnalisisIndicadores, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable,
|
||||||
|
IndicadorEpidemiologico, PedidoSubgrupos,
|
||||||
|
} from './indicadores-analisis.service';
|
||||||
|
import { httpMessage } from './indicadores-http';
|
||||||
|
import { Dominio, Tema } from './indicadores.models';
|
||||||
|
|
||||||
|
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' };
|
||||||
|
|
||||||
|
export const formatoP = (p: number | null) => p === null ? '—' : p < .001 ? '< 0.001' : p.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
|
||||||
|
export type VistaAnalisis = 'curvas' | 'subgrupos' | 'diagnostico';
|
||||||
|
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
|
||||||
|
{ id: 'curvas', etiqueta: 'Curvas (Kaplan-Meier)' },
|
||||||
|
{ id: 'subgrupos', etiqueta: 'Mapa de calor entre variables' },
|
||||||
|
{ id: 'diagnostico', etiqueta: 'Diagnóstico de la cohorte' },
|
||||||
|
];
|
||||||
|
// The patients behind a curve or a heatmap cell: the follow-up list's filters and how to name the selection.
|
||||||
|
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; }
|
||||||
|
|
||||||
|
/** The cell of the grid: its row and column codes, from the coloured layer only (grey cells are suppressed). */
|
||||||
|
export function celdaDelClic(evento: unknown): { fila: string; columna: string } | undefined {
|
||||||
|
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
||||||
|
const c = punto?.customdata;
|
||||||
|
return Array.isArray(c) && typeof c[0] === 'string' && typeof c[1] === 'string' && typeof punto?.z === 'number' ? { fila: c[0], columna: c[1] } : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The group of the clicked curve, from the line's `meta`; bands and empty clicks give nothing. */
|
||||||
|
export function grupoDelClic(evento: unknown): string | undefined {
|
||||||
|
const punto = (evento as { points?: { data?: { meta?: unknown } }[] } | undefined)?.points?.[0];
|
||||||
|
return typeof punto?.data?.meta === 'string' ? punto.data.meta : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The stage a scenario belongs to. */
|
||||||
|
export const etapaDe = (catalogo: AnalisisCatalogo, escenario: string | undefined): AnalisisEtapa | undefined =>
|
||||||
|
catalogo.etapas.find(e => e.escenarios.includes(escenario ?? ''));
|
||||||
|
|
||||||
|
/** The request a stage opens with: its first scenario and variable, all its values, the estimator if the stage admits it. */
|
||||||
|
export function pedidoDeEtapa(catalogo: AnalisisCatalogo, clave: string, actual?: AnalisisPedido): AnalisisPedido {
|
||||||
|
const etapa = catalogo.etapas.find(e => e.clave === clave) ?? catalogo.etapas[0];
|
||||||
|
const estimador = actual && etapa.estimadores.includes(actual.estimador) ? actual.estimador : etapa.estimadores[0];
|
||||||
|
return { escenario: etapa.escenarios[0], estimador, estrato: etapa.variables[0], grupos: [], filtros: {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The grid a stage opens with: its first two variables, or the current ones while they belong to it. */
|
||||||
|
export function cruceDeEtapa(etapa: AnalisisEtapa, actual?: { filas: string; columnas: string }) {
|
||||||
|
const valido = actual && actual.filas !== actual.columnas && etapa.variables.includes(actual.filas) && etapa.variables.includes(actual.columnas);
|
||||||
|
return valido ? { filas: actual.filas, columnas: actual.columnas } : { filas: etapa.variables[0], columnas: etapa.variables[1] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The follow-up filters of a curve: the scenario's population and the group's value of the compared variable. */
|
||||||
|
export function seleccionDeCurva(catalogo: AnalisisCatalogo, pedido: AnalisisPedido, grupo: string): SeleccionPacientes | undefined {
|
||||||
|
const escenario = catalogo.escenarios.find(e => e.clave === pedido.escenario), variable = catalogo.variables.find(v => v.clave === pedido.estrato);
|
||||||
|
if (!escenario || !variable) return undefined;
|
||||||
|
const valor = variable.opciones.find(o => o.codigo === grupo);
|
||||||
|
if (!valor) return undefined;
|
||||||
|
return { filtros: { ...escenario.filtro_seguimiento, [variable.clave]: grupo }, etiqueta: `${escenario.etiqueta}: ${variable.etiqueta}, ${valor.etiqueta}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The follow-up filters of a grid cell: the scenario's population and both values. */
|
||||||
|
export function seleccionDeCelda(catalogo: AnalisisCatalogo, sub: AnalisisSubgrupos, celda: { fila: string; columna: string }): SeleccionPacientes | undefined {
|
||||||
|
const escenario = catalogo.escenarios.find(e => e.clave === sub.escenario);
|
||||||
|
const fila = sub.filas.find(f => f.codigo === celda.fila), columna = sub.columnas.find(c => c.codigo === celda.columna);
|
||||||
|
if (!escenario || !fila || !columna) return undefined;
|
||||||
|
return { filtros: { ...escenario.filtro_seguimiento, [sub.dimension_filas.clave]: celda.fila, [sub.dimension_columnas.clave]: celda.columna },
|
||||||
|
etiqueta: `${escenario.etiqueta}: ${fila.etiqueta} y ${columna.etiqueta}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Epidemiological analysis of the BI-RADS 4+ cohort. On top, the cohort's figures (incidence of cancer and of
|
||||||
|
// recurrence, follow-up adherence and survival). Then, by stage (development, recurrence, survival), three parts:
|
||||||
|
// the Kaplan-Meier curves of two or more values of one variable, the heatmap of two distinct variables, and the
|
||||||
|
// cohort's diagnostics. A curve or a cell opens its patients in Seguimiento; nothing else leaves the aggregates.
|
||||||
|
// Nothing is requested until the tab is first opened, and the grid only once its part is.
|
||||||
|
@Component({
|
||||||
|
selector: 'app-indicadores-analisis',
|
||||||
|
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorKpiCard],
|
||||||
|
template: `
|
||||||
|
@switch (catalogo().estado) {
|
||||||
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando el análisis" /> }
|
||||||
|
@case ('pendiente') { <p role="status" class="panel">Funcionalidad pendiente de publicación.</p> }
|
||||||
|
@case ('error') { <div role="alert" class="panel"><p>{{ $any(catalogo()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentarCatalogo()">Reintentar consulta</button></div> }
|
||||||
|
}
|
||||||
|
@if (cat(); as c) {
|
||||||
|
<section class="epidemiologicos" aria-labelledby="indicadores-epidemiologicos">
|
||||||
|
<h2 id="indicadores-epidemiologicos">Indicadores epidemiológicos</h2>
|
||||||
|
<p class="nota">De toda la cohorte, a {{ meses(c.horizonte_dias) }} meses. Descriptivos, no causales.</p>
|
||||||
|
@switch (indicadores().estado) {
|
||||||
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores epidemiológicos" /> }
|
||||||
|
@case ('error') { <div role="alert"><p>{{ $any(indicadores()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarIndicadores()">Reintentar consulta</button></div> }
|
||||||
|
}
|
||||||
|
@if (ind(); as i) {
|
||||||
|
<div class="kpis">
|
||||||
|
@for (x of i.indicadores; track x.clave) {
|
||||||
|
<app-indicador-kpi-card [title]="x.titulo" [value]="x.valor === null ? null : x.valor.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 })"
|
||||||
|
[unit]="x.unidad" [state]="x.suprimido ? 'Dato oculto por tamaño' : 'Disponible'" [quietWhenAvailable]="true" [additionalInfo]="infoIndicador(x)" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="controles">
|
||||||
|
<span id="analisis-etapa" class="etiqueta">Etapa</span>
|
||||||
|
<mat-button-toggle-group class="etapas" aria-labelledby="analisis-etapa" hideSingleSelectionIndicator [value]="etapa()?.clave" (change)="elegirEtapa($event.value)">
|
||||||
|
@for (e of c.etapas; track e.clave) { <mat-button-toggle [value]="e.clave">{{ e.etiqueta }}</mat-button-toggle> }
|
||||||
|
</mat-button-toggle-group>
|
||||||
|
@if (escenariosEtapa().length > 1) {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Escenario</mat-label>
|
||||||
|
<mat-select [value]="pedido()!.escenario" (selectionChange)="cambiar({ escenario: $event.value })">
|
||||||
|
@for (e of escenariosEtapa(); track e.clave) { <mat-option [value]="e.clave">{{ e.etiqueta }}</mat-option> }
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@if (estimadoresEtapa().length > 1) {
|
||||||
|
<span id="analisis-estimador" class="etiqueta">Estimador</span>
|
||||||
|
<mat-button-toggle-group aria-labelledby="analisis-estimador" hideSingleSelectionIndicator [value]="pedido()!.estimador" (change)="cambiar({ estimador: $event.value })">
|
||||||
|
@for (e of estimadoresEtapa(); track e.clave) { <mat-button-toggle [value]="e.clave" [attr.title]="e.nota">{{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }}</mat-button-toggle> }
|
||||||
|
</mat-button-toggle-group>
|
||||||
|
} @else { <span class="etiqueta">Kaplan-Meier</span> }
|
||||||
|
</div>
|
||||||
|
@if (escenario(); as e) {
|
||||||
|
<p class="contexto">@if (etapa(); as et) { <strong>{{ et.pregunta }}</strong><br> }{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="subsecciones" role="tablist" aria-label="Partes del análisis" (keydown)="teclaVista($event)">
|
||||||
|
@for (v of VISTAS; track v.id) {
|
||||||
|
<button type="button" role="tab" [id]="'analisis-tab-' + v.id" [attr.aria-controls]="'analisis-' + v.id" [attr.aria-selected]="vista() === v.id"
|
||||||
|
[tabIndex]="vista() === v.id ? 0 : -1" (click)="elegirVista(v.id)">{{ v.etiqueta }}</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Curves: two or more values of one variable, compared by log-rank and Cox. -->
|
||||||
|
<section id="analisis-curvas" role="tabpanel" aria-labelledby="analisis-tab-curvas" [hidden]="vista() !== 'curvas'">
|
||||||
|
<div class="controles-panel">
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Comparar por</mat-label>
|
||||||
|
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
|
||||||
|
@for (v of variablesEtapa(); track v.clave) {
|
||||||
|
<mat-option [value]="v.clave">{{ v.etiqueta }}@if (v.estado === 'supuesto') { <span class="motivo"> · supuesto</span> }</mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
@if (variableCurvas(); as v) {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Grupos a comparar</mat-label>
|
||||||
|
<mat-select multiple [value]="gruposMostrados()" (selectionChange)="elegirGrupos($event.value)">
|
||||||
|
@for (o of v.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@if (pocosGrupos()) { <span class="aviso-grupos" role="alert">Elija al menos dos grupos para comparar.</span> }
|
||||||
|
</div>
|
||||||
|
@switch (resultados().estado) {
|
||||||
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
|
||||||
|
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
|
||||||
|
}
|
||||||
|
@if (res(); as r) {
|
||||||
|
<p class="resumen" role="status">
|
||||||
|
@if (r.poblacion.n !== null) { {{ miles(r.poblacion.n) }} pacientes · {{ miles(r.poblacion.eventos ?? 0) }} eventos }
|
||||||
|
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
|
||||||
|
</p>
|
||||||
|
@if (r.supuestos.length) {
|
||||||
|
<div class="supuestos" role="note"><strong>Datos supuestos en el mock.</strong>
|
||||||
|
<ul>@for (t of r.supuestos; track t) { <li>{{ t }}</li> }</ul></div>
|
||||||
|
}
|
||||||
|
<div class="paneles">
|
||||||
|
<article class="panel ancho">
|
||||||
|
<h2>{{ nombreMedida() }} a {{ meses(r.horizonte_dias) }} meses por {{ variableCurvas()?.etiqueta?.toLowerCase() }}</h2>
|
||||||
|
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una curva para ver sus pacientes en Seguimiento.</p>
|
||||||
|
@if (figuraCurvas().data.length) {
|
||||||
|
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
|
||||||
|
[label]="nombreMedida() + ' por ' + (variableCurvas()?.etiqueta ?? 'grupo')" />
|
||||||
|
<table class="riesgo">
|
||||||
|
<caption>Pacientes en riesgo</caption>
|
||||||
|
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }<th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@for (f of r.tabla_riesgo.filas; track f.grupo) {
|
||||||
|
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }
|
||||||
|
<td><button type="button" class="ver" (click)="verGrupo(f.grupo)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(f.grupo) + ' en Seguimiento'">Ver pacientes</button></td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con esta selección.</p> }
|
||||||
|
@if (suprimidos().length) { <p class="nota">Grupos suprimidos: {{ textoSuprimidos() }}.</p> }
|
||||||
|
<p class="nota">La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.</p>
|
||||||
|
@for (a of r.avisos.slice(2); track a) { <p class="nota">{{ a }}</p> }
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article class="panel">
|
||||||
|
<h2>Comparación entre grupos</h2>
|
||||||
|
@if (r.pruebas.logrank; as lr) {
|
||||||
|
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
|
||||||
|
@if (r.pruebas.pares.length > 1) {
|
||||||
|
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
|
||||||
|
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
|
||||||
|
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
|
||||||
|
</table>
|
||||||
|
}
|
||||||
|
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
|
||||||
|
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
|
||||||
|
@if (r.pruebas.rmst.length) {
|
||||||
|
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
|
||||||
|
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
|
||||||
|
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
|
||||||
|
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
|
||||||
|
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article class="panel">
|
||||||
|
<h2>Razón de riesgos (Cox)</h2>
|
||||||
|
@if (r.efectos.estado === 'listo') {
|
||||||
|
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
|
||||||
|
<p class="nota">Modelo de Cox de una variable ({{ variableCurvas()?.etiqueta?.toLowerCase() }}), contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
|
||||||
|
} @else {
|
||||||
|
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
|
||||||
|
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Heatmap: two distinct variables of the stage, each tested plain and at equal value of the other. -->
|
||||||
|
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
|
||||||
|
@if (cruce(); as x) {
|
||||||
|
<div class="controles-panel">
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Filas</mat-label>
|
||||||
|
<mat-select [value]="x.filas" (selectionChange)="cruzar({ filas: $event.value })">
|
||||||
|
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.columnas">{{ v.etiqueta }}</mat-option> }
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Columnas</mat-label>
|
||||||
|
<mat-select [value]="x.columnas" (selectionChange)="cruzar({ columnas: $event.value })">
|
||||||
|
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.filas">{{ v.etiqueta }}</mat-option> }
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<div class="paneles">
|
||||||
|
<article class="panel ancho">
|
||||||
|
<h2>{{ nombreMedida() }} a {{ meses(c.horizonte_dias) }} meses@if (sub(); as s) { por {{ s.dimension_filas.etiqueta.toLowerCase() }} y {{ s.dimension_columnas.etiqueta.toLowerCase() }} }</h2>
|
||||||
|
@switch (subgrupos().estado) {
|
||||||
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa de calor" /> }
|
||||||
|
@case ('error') { <div role="alert"><p>{{ $any(subgrupos()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarSubgrupos(true)">Reintentar consulta</button></div> }
|
||||||
|
}
|
||||||
|
@if (sub(); as s) {
|
||||||
|
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus pacientes en Seguimiento.</p>
|
||||||
|
@if (s.supuestos.length) { <p class="nota">Supuesto en el mock: {{ s.supuestos.join(' ') }}</p> }
|
||||||
|
<app-plotly-chart [style.--plot-height]="figuraSubgrupos().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraSubgrupos()" (plotClick)="clicCelda($event)"
|
||||||
|
[label]="nombreMedida() + ' por ' + s.dimension_filas.etiqueta + ' y ' + s.dimension_columnas.etiqueta" />
|
||||||
|
<p class="nota">Cada celda dice el porcentaje, los eventos y las pacientes. Una celda gris tiene menos de {{ s.umbral_supresion }} pacientes o eventos. «A N meses» marca una celda cuya curva termina antes del horizonte.</p>
|
||||||
|
<table>
|
||||||
|
<caption>Log-rank de cada variable</caption>
|
||||||
|
<thead><tr><th scope="col">Variable</th><th scope="col">Log-rank</th><th scope="col">Estratificado por la otra</th></tr></thead>
|
||||||
|
<tbody>@for (pr of s.pruebas; track pr.variable) {
|
||||||
|
<tr><td>{{ pr.etiqueta }}</td>
|
||||||
|
<td>{{ pr.logrank ? 'χ² ' + pr.logrank.chi2.toLocaleString('es-MX') + ', ' + pr.logrank.gl + ' gl, p ' + formatoP(pr.logrank.p) : 'Menos de dos grupos con eventos suficientes' }}</td>
|
||||||
|
<td>{{ pr.estratificado ? 'p ' + formatoP(pr.estratificado.p) + ' (por ' + pr.etiqueta_estrato.toLowerCase() + ')' : '—' }}</td></tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
<p class="nota">El log-rank estratificado compara los grupos de una variable dentro de cada valor de la otra: si la diferencia desaparece, la explicaba la otra variable.</p>
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Diagnostics: the statistical status of the cohort and the checks behind every figure. -->
|
||||||
|
<section id="analisis-diagnostico" role="tabpanel" aria-labelledby="analisis-tab-diagnostico" [hidden]="vista() !== 'diagnostico'">
|
||||||
|
@if (res(); as r) {
|
||||||
|
<div class="estado-cohorte">
|
||||||
|
<div class="dato"><span class="cifra">{{ r.poblacion.n === null ? 'Oculto' : miles(r.poblacion.n) }}</span><span>pacientes en la población</span></div>
|
||||||
|
<div class="dato"><span class="cifra">{{ r.poblacion.eventos === null ? 'Oculto' : miles(r.poblacion.eventos) }}</span><span>eventos en {{ meses(r.horizonte_dias) }} meses</span></div>
|
||||||
|
<div class="dato"><span class="cifra">{{ r.poblacion.seguimiento_mediano_dias === null ? 'Sin dato' : meses(r.poblacion.seguimiento_mediano_dias) + ' meses' }}</span><span>seguimiento mediano</span></div>
|
||||||
|
<div class="dato"><span class="cifra">{{ eventosPorParametro() ?? '—' }}</span><span>eventos por parámetro (mínimo 10)</span></div>
|
||||||
|
<div class="dato"><span class="cifra">{{ r.umbral_supresion }}</span><span>umbral de supresión</span></div>
|
||||||
|
</div>
|
||||||
|
@if (r.poblacion.totales_ocultos) { <p class="nota">Los totales se ocultan porque un grupo está suprimido y se podría deducir.</p> }
|
||||||
|
<article class="panel">
|
||||||
|
<h2>Reporte de validación</h2>
|
||||||
|
<p class="nota">De las curvas: {{ escenario()?.etiqueta?.toLowerCase() }}, por {{ variableCurvas()?.etiqueta?.toLowerCase() }}.</p>
|
||||||
|
<table class="validacion">
|
||||||
|
<thead><tr><th scope="col">Chequeo</th><th scope="col">Alcance</th><th scope="col">Valor</th><th scope="col">Umbral</th><th scope="col">Resultado</th><th scope="col">Nota</th></tr></thead>
|
||||||
|
<tbody>@for (v of r.validacion; track $index) {
|
||||||
|
<tr [class.falla]="v.aprobado === false">
|
||||||
|
<td>{{ v.chequeo }}</td><td>{{ v.escopo }}</td>
|
||||||
|
<td>{{ v.p !== null ? 'p ' + formatoP(v.p) : v.estadistico !== null ? v.estadistico.toLocaleString('es-MX') : '—' }}</td>
|
||||||
|
<td>{{ v.umbral === null ? '—' : v.umbral.toLocaleString('es-MX') }}</td>
|
||||||
|
<td>{{ v.aprobado === null ? 'No aplica' : v.aprobado ? 'Cumple' : 'No cumple' }}</td>
|
||||||
|
<td>{{ v.nota ?? '' }}</td>
|
||||||
|
</tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
|
||||||
|
</article>
|
||||||
|
}
|
||||||
|
@if (etapa(); as et) {
|
||||||
|
<article class="panel requeridas">
|
||||||
|
<h2>Variables de la NOM para la etapa de {{ et.etiqueta.toLowerCase() }}</h2>
|
||||||
|
<p class="nota">Lo que hay que registrar para estratificar estas curvas, ajustar Cox y aplicar el log-rank. Las de esta etapa:
|
||||||
|
@for (v of variablesEtapa(); track v.clave) { {{ v.etiqueta }} ({{ v.estado === 'registrado' ? 'registrada' : 'supuesta' }}){{ $last ? '.' : ';' }} }</p>
|
||||||
|
<table>
|
||||||
|
<thead><tr><th scope="col">Variable</th><th scope="col">NOM</th><th scope="col">En el esquema</th></tr></thead>
|
||||||
|
<tbody>@for (v of et.requeridas; track v.variable) {
|
||||||
|
<tr [class.falta]="v.estado !== 'registrado'"><td>{{ v.variable }}</td><td>{{ v.nom }}</td><td>{{ v.estado }}</td></tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
</article>
|
||||||
|
}
|
||||||
|
<section class="pendientes" aria-labelledby="analisis-pendientes">
|
||||||
|
<h2 id="analisis-pendientes">Lo que la cohorte aún no permite</h2>
|
||||||
|
<div class="tarjetas">
|
||||||
|
@for (b of c.bloqueados; track b.clave) { <article class="bloqueado"><h3>{{ b.titulo }}</h3><p>{{ b.motivo }}</p></article> }
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { display: block; min-width: 0; }
|
||||||
|
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6);
|
||||||
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
|
.controles mat-form-field { min-width: 12rem; }
|
||||||
|
.controles mat-form-field:first-child { min-width: 20rem; }
|
||||||
|
.contexto, .resumen { margin: var(--issste-space-3) 0 0; font: var(--mat-sys-body-medium); color: var(--issste-text); }
|
||||||
|
.resumen { margin: 0 0 var(--issste-space-4); color: var(--issste-text-secondary); }
|
||||||
|
.motivo, .nota, .etiqueta { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||||
|
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||||
|
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
|
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||||
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
|
.panel.ancho { grid-column: 1 / -1; }
|
||||||
|
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
|
||||||
|
p { margin: var(--issste-space-3) 0 0; }
|
||||||
|
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||||
|
table { width: 100%; margin-top: var(--issste-space-4); border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
||||||
|
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
||||||
|
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
||||||
|
.riesgo td { text-align: right; font-variant-numeric: tabular-nums; }
|
||||||
|
.validacion tr.falla td { font-weight: 600; }
|
||||||
|
.estado-modelo { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
|
.estado-modelo.insuficiente { border-style: solid; }
|
||||||
|
.pendientes { margin-top: var(--issste-space-6); }
|
||||||
|
.tarjetas { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||||
|
.bloqueado { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); background: transparent; }
|
||||||
|
.bloqueado h3 { margin: 0; font: var(--mat-sys-title-small); }
|
||||||
|
.epidemiologicos { margin-bottom: var(--issste-space-6); }
|
||||||
|
.epidemiologicos .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); grid-auto-rows: 1fr; gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||||
|
.controles-panel { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
|
||||||
|
.controles-panel mat-form-field { min-width: 14rem; }
|
||||||
|
.ver { padding: 0; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
||||||
|
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
|
.aviso-grupos { color: var(--issste-text); font-weight: 600; }
|
||||||
|
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||||
|
.subsecciones { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin: var(--issste-space-4) 0; border-bottom: 1px solid var(--issste-border); }
|
||||||
|
.subsecciones button { padding: var(--issste-space-2) var(--issste-space-4); border: 0; border-bottom: 3px solid transparent; background: none; color: var(--issste-text-secondary);
|
||||||
|
font: var(--mat-sys-title-small); cursor: pointer; min-height: 44px; }
|
||||||
|
.subsecciones button[aria-selected='true'] { color: var(--issste-text); border-bottom-color: var(--issste-accent); }
|
||||||
|
.subsecciones button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
|
.supuestos { margin: 0 0 var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border-left: 4px solid var(--issste-accent);
|
||||||
|
background: var(--issste-surface); color: var(--issste-text); font: var(--mat-sys-body-medium); }
|
||||||
|
.supuestos ul { margin: var(--issste-space-1) 0 0; padding-left: var(--issste-space-6); }
|
||||||
|
.requeridas { margin-top: var(--issste-space-6); }
|
||||||
|
.requeridas tr.falta td:last-child { font-weight: 600; }
|
||||||
|
.comparacion { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||||
|
@container dashboard (min-width: 960px) { .comparacion { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
|
.estado-cohorte { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: var(--issste-space-4); margin-bottom: var(--issste-space-4); }
|
||||||
|
.dato { display: flex; flex-direction: column; gap: var(--issste-space-1); padding: var(--issste-space-4); background: var(--issste-surface);
|
||||||
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||||
|
.dato .cifra { color: var(--issste-text); font-size: 1.5rem; font-weight: 500; line-height: 1.2; }
|
||||||
|
@media (max-width: 600px) { .controles { padding: var(--issste-space-3); } .controles mat-form-field, .controles mat-form-field:first-child { min-width: 100%; } }
|
||||||
|
`,
|
||||||
|
|
||||||
|
})
|
||||||
|
export class IndicadoresAnalisis {
|
||||||
|
readonly dominio = input.required<Dominio>();
|
||||||
|
readonly tema = input.required<Tema>();
|
||||||
|
readonly active = input(false);
|
||||||
|
// The patients of a curve or a heatmap cell, for the page to open them in Seguimiento.
|
||||||
|
readonly verPacientes = output<SeleccionPacientes>();
|
||||||
|
readonly formatoP = formatoP;
|
||||||
|
readonly miles = (v: number) => v.toLocaleString('es-MX');
|
||||||
|
readonly meses = mesesDe;
|
||||||
|
readonly VISTAS = VISTAS;
|
||||||
|
private readonly service = inject(AnalisisService);
|
||||||
|
readonly catalogo = signal<Carga<AnalisisCatalogo>>({ estado: 'cargando' });
|
||||||
|
readonly resultados = signal<Carga<AnalisisResultados>>({ estado: 'cargando' });
|
||||||
|
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
|
||||||
|
readonly indicadores = signal<Carga<AnalisisIndicadores>>({ estado: 'cargando' });
|
||||||
|
readonly pedido = signal<AnalisisPedido | undefined>(undefined);
|
||||||
|
readonly cruce = signal<{ filas: string; columnas: string } | undefined>(undefined);
|
||||||
|
readonly vista = signal<VistaAnalisis>('curvas');
|
||||||
|
readonly pocosGrupos = signal(false);
|
||||||
|
private readonly pedidos = new Subject<AnalisisPedido>();
|
||||||
|
private readonly pedidosSubgrupos = new Subject<PedidoSubgrupos>();
|
||||||
|
private readonly catalogos = new Subject<void>();
|
||||||
|
private readonly pedidosIndicadores = new Subject<void>();
|
||||||
|
private abierto = false;
|
||||||
|
private subgruposDe?: string;
|
||||||
|
|
||||||
|
readonly cat = computed(() => { const c = this.catalogo(); return c.estado === 'listo' ? c.datos : undefined; });
|
||||||
|
readonly res = computed(() => { const r = this.resultados(); return r.estado === 'listo' ? r.datos : undefined; });
|
||||||
|
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
|
||||||
|
readonly ind = computed(() => { const i = this.indicadores(); return i.estado === 'listo' ? i.datos : undefined; });
|
||||||
|
readonly escenario = computed(() => this.cat()?.escenarios.find(e => e.clave === this.pedido()?.escenario));
|
||||||
|
readonly estimadorElegido = computed(() => this.cat()?.estimadores.find(e => e.clave === this.pedido()?.estimador));
|
||||||
|
readonly etapa = computed(() => { const c = this.cat(); return c ? etapaDe(c, this.pedido()?.escenario) : undefined; });
|
||||||
|
readonly nombreMedida = computed(() => nombreMedida(this.etapa()?.medida ?? 'incidencia'));
|
||||||
|
readonly variablesEtapa = computed(() => (this.etapa()?.variables ?? [] as readonly string[])
|
||||||
|
.map(k => this.cat()?.variables.find(v => v.clave === k)).filter((v): v is AnalisisVariable => !!v));
|
||||||
|
readonly escenariosEtapa = computed(() => this.cat()?.escenarios.filter(e => this.etapa()?.escenarios.includes(e.clave)) ?? []);
|
||||||
|
readonly estimadoresEtapa = computed(() => this.cat()?.estimadores.filter(e => this.etapa()?.estimadores.includes(e.clave)) ?? []);
|
||||||
|
readonly variableCurvas = computed(() => this.variablesEtapa().find(v => v.clave === this.pedido()?.estrato));
|
||||||
|
// Every value when none was picked; the selector shows them checked.
|
||||||
|
readonly gruposMostrados = computed(() => { const p = this.pedido(); return p?.grupos.length ? p.grupos : this.variableCurvas()?.opciones.map(o => o.codigo) ?? []; });
|
||||||
|
readonly suprimidos = computed(() => this.res()?.grupos.filter(g => g.suprimido) ?? []);
|
||||||
|
readonly textoSuprimidos = computed(() => this.suprimidos().map(g => `${g.etiqueta} (${(g.motivo ?? 'suprimido').toLowerCase()})`).join('; '));
|
||||||
|
readonly figuraCurvas = computed(() => { const r = this.res(); return r ? curvasFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||||
|
readonly figuraForest = computed(() => { const r = this.res(); return r ? forestFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||||
|
readonly figuraSubgrupos = computed(() => { const s = this.sub(); return s ? subgruposFigura(s, this.tema()) : { data: [], layout: {} }; });
|
||||||
|
readonly eventosPorParametro = computed(() => {
|
||||||
|
const fila = this.res()?.validacion.find(v => v.chequeo === 'Eventos por parámetro');
|
||||||
|
return fila?.estadistico == null ? null : fila.estadistico.toLocaleString('es-MX');
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
const destroy = inject(DestroyRef);
|
||||||
|
const cargar = <T>(fuente: () => Observable<T>, pendiente = false) => fuente().pipe(
|
||||||
|
map((datos): Carga<T> => ({ estado: 'listo', datos })),
|
||||||
|
catchError(error => of<Carga<T>>(pendiente && error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
|
||||||
|
startWith<Carga<T>>({ estado: 'cargando' }));
|
||||||
|
this.catalogos.pipe(switchMap(() => cargar(() => this.service.catalogo(this.dominio()), true)), takeUntilDestroyed(destroy)).subscribe(carga => {
|
||||||
|
this.catalogo.set(carga);
|
||||||
|
if (carga.estado === 'listo' && !this.pedido()) {
|
||||||
|
this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
|
||||||
|
this.cargarIndicadores();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.pedidos.pipe(switchMap(p => cargar(() => this.service.resultados(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.resultados.set(c));
|
||||||
|
this.pedidosSubgrupos.pipe(switchMap(p => cargar(() => this.service.subgrupos(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.subgrupos.set(c));
|
||||||
|
this.pedidosIndicadores.pipe(switchMap(() => cargar(() => this.service.indicadores(this.dominio()))), takeUntilDestroyed(destroy)).subscribe(c => this.indicadores.set(c));
|
||||||
|
// The grid follows the stage, the scenario, the estimator and its two variables; it is asked for when its part is open.
|
||||||
|
effect(() => {
|
||||||
|
const vista = this.vista(), pedido = this.pedido(), cruce = this.cruce();
|
||||||
|
if (vista === 'subgrupos' && pedido && cruce) untracked(() => this.cargarSubgrupos());
|
||||||
|
});
|
||||||
|
effect(() => {
|
||||||
|
if (!this.active() || this.abierto) return;
|
||||||
|
untracked(() => { this.abierto = true; this.catalogos.next(); });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
cambiar(cambio: Partial<AnalisisPedido>) {
|
||||||
|
const pedido: AnalisisPedido = { escenario: '', estimador: '', estrato: '', grupos: [], filtros: {}, ...this.pedido(), ...cambio };
|
||||||
|
this.pedido.set(pedido);
|
||||||
|
this.pocosGrupos.set(false);
|
||||||
|
const etapa = this.cat() && etapaDe(this.cat()!, pedido.escenario);
|
||||||
|
if (etapa) this.cruce.set(cruceDeEtapa(etapa, this.cruce()));
|
||||||
|
this.pedidos.next(pedido);
|
||||||
|
}
|
||||||
|
// A stage keeps the estimator when it admits it, and starts from its first scenario and variable.
|
||||||
|
elegirEtapa(clave: string) {
|
||||||
|
const c = this.cat();
|
||||||
|
if (c && clave !== this.etapa()?.clave) this.cambiar(pedidoDeEtapa(c, clave, this.pedido()));
|
||||||
|
}
|
||||||
|
estratificar(estrato: string) { this.cambiar({ estrato, grupos: [] }); }
|
||||||
|
// Two or more values are compared; with all of them checked, the request names none.
|
||||||
|
elegirGrupos(grupos: string[]) {
|
||||||
|
if (grupos.length < 2) { this.pocosGrupos.set(true); return; }
|
||||||
|
const todos = this.variableCurvas()?.opciones.length ?? 0;
|
||||||
|
this.cambiar({ grupos: grupos.length === todos ? [] : grupos });
|
||||||
|
}
|
||||||
|
cruzar(cambio: Partial<{ filas: string; columnas: string }>) {
|
||||||
|
const actual = this.cruce();
|
||||||
|
if (!actual) return;
|
||||||
|
const siguiente = { ...actual, ...cambio };
|
||||||
|
if (siguiente.filas !== siguiente.columnas) this.cruce.set(siguiente);
|
||||||
|
}
|
||||||
|
infoIndicador(x: IndicadorEpidemiologico) {
|
||||||
|
if (x.suprimido) return x.descripcion;
|
||||||
|
const intervalo = x.ic_bajo !== null && x.ic_alto !== null ? `IC 95 %: ${x.ic_bajo.toLocaleString('es-MX')} a ${x.ic_alto.toLocaleString('es-MX')} %. ` : '';
|
||||||
|
const conteo = x.clave === 'adherencia' ? `${this.miles(x.eventos!)} de ${this.miles(x.n!)} pacientes. ` : `${this.miles(x.eventos!)} eventos en ${this.miles(x.n!)} pacientes. `;
|
||||||
|
return intervalo + conteo + x.descripcion + (x.supuesto ? ' ' + x.supuesto : '');
|
||||||
|
}
|
||||||
|
clicCurva(evento: unknown) {
|
||||||
|
const grupo = grupoDelClic(evento);
|
||||||
|
if (grupo) this.verGrupo(grupo);
|
||||||
|
}
|
||||||
|
verGrupo(grupo: string) {
|
||||||
|
const c = this.cat(), p = this.pedido(), seleccion = c && p ? seleccionDeCurva(c, p, grupo) : undefined;
|
||||||
|
if (seleccion) this.verPacientes.emit(seleccion);
|
||||||
|
}
|
||||||
|
clicCelda(evento: unknown) {
|
||||||
|
const celda = celdaDelClic(evento), c = this.cat(), s = this.sub();
|
||||||
|
const seleccion = celda && c && s ? seleccionDeCelda(c, s, celda) : undefined;
|
||||||
|
if (seleccion) this.verPacientes.emit(seleccion);
|
||||||
|
}
|
||||||
|
elegirVista(vista: VistaAnalisis) { this.vista.set(vista); }
|
||||||
|
teclaVista(event: KeyboardEvent) {
|
||||||
|
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||||
|
event.preventDefault();
|
||||||
|
const i = VISTAS.findIndex(v => v.id === this.vista());
|
||||||
|
const j = event.key === 'Home' ? 0 : event.key === 'End' ? VISTAS.length - 1 : (i + (event.key === 'ArrowRight' ? 1 : -1) + VISTAS.length) % VISTAS.length;
|
||||||
|
this.vista.set(VISTAS[j].id);
|
||||||
|
(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>('[role="tab"]')[j]?.focus();
|
||||||
|
}
|
||||||
|
cargarSubgrupos(forzar = false) {
|
||||||
|
const p = this.pedido(), x = this.cruce();
|
||||||
|
if (!p || !x) return;
|
||||||
|
const pedido = { escenario: p.escenario, estimador: p.estimador, ...x };
|
||||||
|
const clave = JSON.stringify(pedido);
|
||||||
|
if (!forzar && clave === this.subgruposDe) return;
|
||||||
|
this.subgruposDe = clave;
|
||||||
|
this.pedidosSubgrupos.next(pedido);
|
||||||
|
}
|
||||||
|
cargarIndicadores() { this.pedidosIndicadores.next(); }
|
||||||
|
etiqueta(grupo: string) { return this.res()?.grupos.find(g => g.grupo === grupo)?.etiqueta ?? grupo; }
|
||||||
|
reintentar() { const p = this.pedido(); if (p) this.pedidos.next(p); }
|
||||||
|
reintentarCatalogo() { this.catalogos.next(); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { c1DonutCapability, c1DonutFigure, c1DonutLabels } from './indicadores-c1-donut';
|
||||||
|
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||||
|
|
||||||
|
const fila = (estrato: string, numerador: number, denominador: number, extra: object = {}) => ({
|
||||||
|
periodo: '2025-S2', grupo: 'TOTAL', estrato, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null,
|
||||||
|
n_sin_evento: denominador - numerador, n_excluido: 0, ...extra,
|
||||||
|
});
|
||||||
|
const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]): IndicadorDatos => ({
|
||||||
|
id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unidad: 'paciente',
|
||||||
|
tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'grupo_edad', valores_estrato: ['16-23', '24-29', '30-36'],
|
||||||
|
etiquetas_estrato: { '16-23': '16 a 23 meses', '24-29': '24 a 29 meses', '30-36': '30 a 36 meses' },
|
||||||
|
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas,
|
||||||
|
});
|
||||||
|
const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||||
|
|
||||||
|
describe('Dona de dos anillos para C1', () => {
|
||||||
|
it('solo aplica a C1 con las figuras por grupo de edad', () => {
|
||||||
|
expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true);
|
||||||
|
expect(c1DonutCapability('C1', 'fig_c1_dona_edad')).toBe(true);
|
||||||
|
expect(c1DonutCapability('C1', 'fig_c1_barras_edad')).toBe(true);
|
||||||
|
expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false);
|
||||||
|
expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false);
|
||||||
|
});
|
||||||
|
it('anillo interior con y sin el evento; exterior por grupo de edad, con el total al centro', () => {
|
||||||
|
const result = c1DonutFigure(datos(), selection);
|
||||||
|
expect(result.status).toBe('supported');
|
||||||
|
if (result.status !== 'supported') return;
|
||||||
|
const [center, inner, outer] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
|
||||||
|
expect(center.text[0]).toContain('<b>64</b>');
|
||||||
|
expect(inner.labels).toEqual(['Con EEG', 'Sin EEG']);
|
||||||
|
expect(inner.values).toEqual([46, 18]);
|
||||||
|
expect(inner.text).toEqual(['Con EEG<br>71.9 %', 'Sin EEG<br>28.1 %']);
|
||||||
|
expect(outer.labels).toEqual(['Con EEG · 16 a 23 meses', 'Con EEG · 24 a 29 meses', 'Con EEG · 30 a 36 meses',
|
||||||
|
'Sin EEG · 16 a 23 meses', 'Sin EEG · 24 a 29 meses', 'Sin EEG · 30 a 36 meses']);
|
||||||
|
expect(outer.values).toEqual([16, 13, 17, 8, 5, 5]);
|
||||||
|
// Inside the outer ring only the age group; slices under 5 % stay unlabeled.
|
||||||
|
expect(outer.text[0]).toMatch(/^16 a 23 meses<br>/);
|
||||||
|
expect(outer.text[4]).toMatch(/^24 a 29 meses<br>7.8/);
|
||||||
|
const small = c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 14), fila('30-36', 17, 40)]), selection);
|
||||||
|
if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe('');
|
||||||
|
expect(result.total).toBe(64);
|
||||||
|
expect(result.notes).toEqual(['Datos ficticios.']);
|
||||||
|
expect(result.highlight.groups.map(g => g.label)).toEqual(['Con EEG', 'Sin EEG']);
|
||||||
|
expect(result.highlight.items.map(i => i.short)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||||
|
expect(result.highlight.groups[1].center).toBe('<b>18</b><br>Sin EEG');
|
||||||
|
expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' });
|
||||||
|
});
|
||||||
|
it('dona por grupo de edad: solo los pacientes con el evento, con el porcentaje total al centro', () => {
|
||||||
|
const result = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||||
|
if (result.status !== 'supported') throw new Error(result.reason);
|
||||||
|
expect(result.figure.data).toHaveLength(1);
|
||||||
|
// Only the patients with EEG, by age group; each slice is its share of those 46 patients.
|
||||||
|
const [ring] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[];
|
||||||
|
expect(ring.labels).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||||
|
expect(ring.values).toEqual([16, 13, 17]);
|
||||||
|
expect(ring.text[0]).toMatch(/^16 a 23 meses<br>34.8/);
|
||||||
|
expect((result.figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>71.9 %</b>');
|
||||||
|
expect(result.highlight.groups).toEqual([]);
|
||||||
|
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||||
|
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||||
|
});
|
||||||
|
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||||
|
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||||
|
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||||
|
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||||
|
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||||
|
expect(dona.highlight.items.map(i => i.color)).toEqual(colores);
|
||||||
|
const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
|
||||||
|
if (barras.status !== 'supported') throw new Error('sin figura');
|
||||||
|
expect((barras.figure.data[0] as { marker: { color: string[] } }).marker.color).toEqual(colores);
|
||||||
|
expect(barras.highlight.items.map(i => i.color)).toEqual(colores);
|
||||||
|
});
|
||||||
|
it('barras apiladas por grupo de edad: confirmados y en proceso, con un botón por estado', () => {
|
||||||
|
const result = c1DonutFigure({ ...datos(), id: 'M24_confirmacion_diagnostico' }, { ...selection, indicador: 'M24_confirmacion_diagnostico', figura: 'fig_c1_barras_apiladas_edad' });
|
||||||
|
if (result.status !== 'supported') throw new Error('sin figura');
|
||||||
|
expect(result.figure.layout['barmode']).toBe('stack');
|
||||||
|
expect(result.figure.data.map(t => [t['name'], t['y']])).toEqual([['Diagnóstico confirmado', [16, 13, 17]], ['En proceso', [8, 5, 5]]]);
|
||||||
|
expect(result.figure.data[1]['text']).toEqual(['8 (33.3 %)', '5 (27.8 %)', '5 (22.7 %)']);
|
||||||
|
expect(result.highlight.items.map(i => i.label)).toEqual(['Diagnóstico confirmado', 'En proceso']);
|
||||||
|
});
|
||||||
|
it('barras por grupo de edad: una barra por grupo con su porcentaje', () => {
|
||||||
|
const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' },
|
||||||
|
{ ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' });
|
||||||
|
if (result.status !== 'supported') throw new Error(result.reason);
|
||||||
|
const [bars] = result.figure.data as { type: string; x: string[]; y: number[]; text: string[] }[];
|
||||||
|
expect(bars.type).toBe('bar');
|
||||||
|
expect(bars.x).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||||
|
expect(bars.text).toEqual(['33.3 %', '27.8 %', '22.7 %']);
|
||||||
|
expect(JSON.stringify(result.figure.layout['yaxis'])).toContain('% de pacientes sin EEG');
|
||||||
|
expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]);
|
||||||
|
});
|
||||||
|
it('usa etiquetas propias por indicador y neutrales para otros', () => {
|
||||||
|
expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Diagnóstico confirmado', 'En proceso']);
|
||||||
|
expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']);
|
||||||
|
expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']);
|
||||||
|
});
|
||||||
|
it('solo un semestre', () => {
|
||||||
|
expect(c1DonutFigure({ ...datos(), tipo_periodo: 'mes', periodos: ['2025-12'] }, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-12'] }))
|
||||||
|
.toEqual({ status: 'unsupported', reason: 'Esta figura solo está disponible para un semestre.' });
|
||||||
|
expect(c1DonutFigure({ ...datos(), periodos: ['2025-S1', '2025-S2'] }, { ...selection, periodos: ['2025-S1', '2025-S2'] }).status).toBe('unsupported');
|
||||||
|
expect(c1DonutFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported');
|
||||||
|
});
|
||||||
|
it('rechaza estratos incompletos, suprimidos o imposibles', () => {
|
||||||
|
expect(c1DonutFigure({ ...datos(), estrato: null }, selection).status).toBe('unsupported');
|
||||||
|
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18)]), selection).status).toBe('unsupported');
|
||||||
|
expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', null as unknown as number, 22, { suprimido: 1 })]), selection).status).toBe('unsupported');
|
||||||
|
expect(c1DonutFigure(datos([fila('16-23', 30, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]), selection).status).toBe('unsupported');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
|
||||||
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
|
||||||
|
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||||
|
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||||
|
|
||||||
|
// Figures by age group for a C1 proportion over one semester, built from the age-stratified C1 rows:
|
||||||
|
// - fig_c1_donas: double donut drawn like CaCu's «Distribución de resultados citológicos»; the inner ring
|
||||||
|
// splits the denominator into patients with and without the event, the outer ring each of them by age group.
|
||||||
|
// - fig_c1_dona_edad: only the patients with the event, by age group, with the overall percentage in the centre.
|
||||||
|
// - fig_c1_barras_edad: one bar per age group with its percentage.
|
||||||
|
export const C1_DONUT = 'fig_c1_donas';
|
||||||
|
export const C1_RING = 'fig_c1_dona_edad';
|
||||||
|
export const C1_AGE_BARS = 'fig_c1_barras_edad';
|
||||||
|
export const C1_AGE_STACK = 'fig_c1_barras_apiladas_edad';
|
||||||
|
const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS, C1_AGE_STACK];
|
||||||
|
export const C1_DONUT_ESTRATO = 'grupo_edad';
|
||||||
|
// Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording.
|
||||||
|
const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
|
||||||
|
M21_diagnosticados_con_eeg: ['Con EEG', 'Sin EEG'],
|
||||||
|
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
|
||||||
|
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
|
||||||
|
};
|
||||||
|
// Green for the event, red for its complement; age groups get lighter shades.
|
||||||
|
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
|
||||||
|
// One colour per age group, the same in the donut (M21) and the bars (M22).
|
||||||
|
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
|
||||||
|
|
||||||
|
export type C1DonutResult = { status: 'unsupported'; reason: string }
|
||||||
|
| { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] };
|
||||||
|
export function c1DonutCapability(contract: string, representation: string): boolean {
|
||||||
|
return contract === 'C1' && C1_AGE_FIGURES.includes(representation);
|
||||||
|
}
|
||||||
|
export function c1DonutLabels(indicador: string): readonly [string, string] {
|
||||||
|
return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento'];
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
|
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
||||||
|
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
function shade(hex: string, step: number, steps: number): string {
|
||||||
|
const t = steps > 1 ? 0.65 * step / (steps - 1) : 0;
|
||||||
|
const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)).map(c => Math.round(c + (255 - c) * t));
|
||||||
|
return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): C1DonutResult {
|
||||||
|
const unsupported = (reason: string): C1DonutResult => ({ status: 'unsupported', reason });
|
||||||
|
if (!c1DonutCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada');
|
||||||
|
if (selection.tipoPeriodo !== 'semestre' || data.tipo_periodo !== 'semestre') return unsupported('Esta figura solo está disponible para un semestre.');
|
||||||
|
if (data.periodos.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0])))
|
||||||
|
return unsupported('Se requiere un semestre único concordante');
|
||||||
|
const values = data['valores_estrato'], names = data['etiquetas_estrato'];
|
||||||
|
if (data['estrato'] !== C1_DONUT_ESTRATO || !Array.isArray(values) || !values.length || !values.every(v => typeof v === 'string')
|
||||||
|
|| new Set(values).size !== values.length || (names != null && !record(names))) return unsupported('Estratificación por grupo de edad no verificable');
|
||||||
|
const period = data.periodos[0];
|
||||||
|
const rows = values.map(v => data.filas.filter(r => r['periodo'] === period && r['estrato'] === v));
|
||||||
|
if (rows.some(r => r.length !== 1) || data.filas.length !== values.length) return unsupported('Partición por grupo de edad incompleta');
|
||||||
|
const strata = rows.map(([r], i) => ({ id: values[i] as string, label: typeof names?.[values[i]] === 'string' ? names[values[i]] as string : values[i] as string,
|
||||||
|
numerador: r['numerador'], denominador: r['denominador'], suprimido: r['suprimido'], grupo: r['grupo'] }));
|
||||||
|
if (strata.some(s => s.grupo !== 'TOTAL' || (s.suprimido !== 0 && s.suprimido !== false)
|
||||||
|
|| !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables');
|
||||||
|
|
||||||
|
const labels = c1DonutLabels(data.id);
|
||||||
|
const notes = Array.isArray(data.notas) ? [...data.notas] : [];
|
||||||
|
const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period };
|
||||||
|
const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0);
|
||||||
|
if (selection.figura === C1_AGE_STACK) {
|
||||||
|
const figure = ageStack(strata, labels, selection);
|
||||||
|
figure.layout = { ...figure.layout, title };
|
||||||
|
const highlight: FigureHighlight = { groups: [], traces: [0, 1], allLabel: 'Todos los pacientes',
|
||||||
|
items: labels.map((label, g) => ({ id: g ? 'SIN' : 'CON', label, color: RING_COLORS[g], points: strata.map((_, i) => ({ trace: g, index: i })) })) };
|
||||||
|
return { status: 'supported', figure, highlight, total, notes };
|
||||||
|
}
|
||||||
|
if (selection.figura === C1_AGE_BARS) {
|
||||||
|
const figure = ageBars(strata, labels[0], selection);
|
||||||
|
figure.layout = { ...figure.layout, title };
|
||||||
|
const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad',
|
||||||
|
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }] })) };
|
||||||
|
return { status: 'supported', figure, highlight, total, notes };
|
||||||
|
}
|
||||||
|
|
||||||
|
const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] }));
|
||||||
|
const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {};
|
||||||
|
grupos.forEach((g, gi) => strata.forEach((s, i) => {
|
||||||
|
const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number;
|
||||||
|
// Unique labels: Plotly merges pie slices that share one.
|
||||||
|
categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id });
|
||||||
|
celdas[id] = { n, estado: 'Publicado' };
|
||||||
|
}));
|
||||||
|
const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' },
|
||||||
|
escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' };
|
||||||
|
const figure = dona(modelo, {}, selection.tema);
|
||||||
|
if (figure.data.length === 3) {
|
||||||
|
const [, inner, outer] = figure.data as Record<string, unknown>[];
|
||||||
|
const hover = '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de ' + total + '<extra></extra>';
|
||||||
|
inner['hovertemplate'] = outer['hovertemplate'] = hover;
|
||||||
|
// Inside the outer ring the colour already tells the group: show only the age group and its share.
|
||||||
|
const outerValues = outer['values'] as number[];
|
||||||
|
outer['text'] = categorias.map((c, i) => outerValues[i] / total < .05 ? ''
|
||||||
|
: escape(strata[i % strata.length].label) + '<br>' + shareText(outerValues[i], total));
|
||||||
|
inner['text'] = grupos.map((g, i) => {
|
||||||
|
const n = (inner['values'] as number[])[i];
|
||||||
|
return n / total < .05 ? '' : escape(g.etiqueta) + '<br>' + percentNumber(100 * n / total) + ' %';
|
||||||
|
});
|
||||||
|
if (selection.figura === C1_RING) {
|
||||||
|
// Only the patients with the event, by age group, around the overall percentage of the event.
|
||||||
|
// Each slice is its age group's share of those patients.
|
||||||
|
const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0);
|
||||||
|
const values = strata.map(s => s.numerador as number);
|
||||||
|
figure.data = [{ ...outer, hole: .6, values, labels: strata.map(s => escape(s.label)),
|
||||||
|
marker: { ...(outer['marker'] as object), colors: strata.map((_, i) => ageColor(i)) },
|
||||||
|
text: values.map((n, i) => !numerador || n / numerador < .05 ? '' : escape(strata[i].label) + '<br>' + shareText(n, numerador)),
|
||||||
|
customdata: values.map(n => [n, numerador ? percentNumber(100 * n / numerador) : '0']),
|
||||||
|
hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '<extra></extra>' }];
|
||||||
|
figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||||
|
text: '<b>' + percentNumber(100 * numerador / total) + ' %</b>', font: { size: 26, color: c2Theme(selection.tema).text } }] };
|
||||||
|
const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0],
|
||||||
|
items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }],
|
||||||
|
center: '<b>' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %</b><br>' + escape(s.label) })) };
|
||||||
|
return { status: 'supported', figure, highlight, total, notes };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
figure.layout = { ...figure.layout, title };
|
||||||
|
// Next to its group's button, a category only needs its age group.
|
||||||
|
const highlight = donaHighlight(modelo, id => strata.find(s => id.endsWith(':' + s.id))?.label);
|
||||||
|
return { status: 'supported', figure, highlight, total, notes };
|
||||||
|
}
|
||||||
|
|
||||||
|
// "Con EEG" -> "con EEG", to follow «pacientes».
|
||||||
|
const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1);
|
||||||
|
// One stacked bar per age group: how many of its patients have the event and how many don't.
|
||||||
|
function ageStack(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], labels: readonly [string, string], selection: FigureSelection): PlotlyFigure {
|
||||||
|
const theme = c2Theme(selection.tema);
|
||||||
|
const x = strata.map(s => escape(s.label));
|
||||||
|
const conEvento = strata.map(s => s.numerador as number), sinEvento = strata.map(s => (s.denominador as number) - (s.numerador as number));
|
||||||
|
return { data: [conEvento, sinEvento].map((y, g) => ({ type: 'bar', name: escape(labels[g]), x, y, marker: { color: RING_COLORS[g], line: { color: theme.background, width: 1 } },
|
||||||
|
text: y.map((n, i) => (strata[i].denominador as number) ? n + ' (' + percentNumber(100 * n / (strata[i].denominador as number)) + ' %)' : ''),
|
||||||
|
textposition: 'inside', insidetextanchor: 'middle', hovertemplate: '%{x}<br>%{fullData.name}: %{y} pacientes<extra></extra>' })),
|
||||||
|
layout: { autosize: true, height: 400, barmode: 'stack', margin: { t: 24, l: 72, r: 24, b: 80 }, showlegend: true,
|
||||||
|
legend: { orientation: 'h', y: -0.28, itemclick: false, itemdoubleclick: false },
|
||||||
|
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||||
|
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
|
||||||
|
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero', gridcolor: theme.grid, zeroline: false } },
|
||||||
|
config: { displayModeBar: false } };
|
||||||
|
}
|
||||||
|
// One bar per age group: the share of its patients with the event.
|
||||||
|
function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure {
|
||||||
|
const theme = c2Theme(selection.tema);
|
||||||
|
const x = strata.map(s => escape(s.label));
|
||||||
|
const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null);
|
||||||
|
return { data: [{ type: 'bar', x, y, marker: { color: strata.map((_, i) => ageColor(i)), line: { color: theme.background, width: 1 } },
|
||||||
|
text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false,
|
||||||
|
customdata: strata.map(s => [s.numerador, s.denominador]),
|
||||||
|
hovertemplate: '%{x}<br>%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)<extra></extra>' }],
|
||||||
|
layout: { autosize: true, height: 400, margin: { t: 24, l: 72, r: 24, b: 64 }, showlegend: false,
|
||||||
|
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||||
|
xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true },
|
||||||
|
yaxis: { title: { text: '% de pacientes ' + escape(what(event)) }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } },
|
||||||
|
config: { displayModeBar: false } };
|
||||||
|
}
|
||||||
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
|
|||||||
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
|
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
|
||||||
const legend = donutLegend(final), view = donutSimpleView(final);
|
const legend = donutLegend(final), view = donutSimpleView(final);
|
||||||
expect(legend).toEqual([
|
expect(legend).toEqual([
|
||||||
{ label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' },
|
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
|
||||||
]);
|
]);
|
||||||
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||||
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||||
@@ -161,12 +161,12 @@ describe('paleta C2 institucional y semántica', () => {
|
|||||||
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
|
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
|
||||||
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||||
const figure = supported(data, { ...selection, tema }).figure;
|
const figure = supported(data, { ...selection, tema }).figure;
|
||||||
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#A4B88A', '#D0B778']);
|
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
|
||||||
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
||||||
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
||||||
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
||||||
expect(c2Color(undefined, 0)).toBe('#7184A2'); expect(c2Color(undefined, 1)).toBe('#A4B88A');
|
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
|
||||||
expect(c2Color(undefined, 2)).toBe('#D0B778'); expect(c2Color(undefined, 3)).toBe('#B78B8E');
|
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
|
||||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
||||||
});
|
});
|
||||||
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
|
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ describe('selección local segura de barras generales C2', () => {
|
|||||||
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
|
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
|
||||||
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
|
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
|
||||||
const view = c2GeneralSelection(source, data, selection, local)!;
|
const view = c2GeneralSelection(source, data, selection, local)!;
|
||||||
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } });
|
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
|
||||||
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
|
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
|
||||||
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
|
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
|
||||||
expect(view.context).toContain('G2, 2025-S2');
|
expect(view.context).toContain('G2, 2025-S2');
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ import { Tema } from './indicadores.models';
|
|||||||
// Matches src/styles.scss: interface tokens are the source of these candidates,
|
// Matches src/styles.scss: interface tokens are the source of these candidates,
|
||||||
// not a certified brand guide. Published semantic colours always take priority.
|
// not a certified brand guide. Published semantic colours always take priority.
|
||||||
export const C2_PALETTE = Object.freeze({
|
export const C2_PALETTE = Object.freeze({
|
||||||
series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']),
|
// ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
|
||||||
|
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
|
||||||
|
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
|
||||||
|
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
||||||
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||||
|
|||||||
@@ -59,7 +59,18 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
|||||||
http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'});
|
http.expectOne(r => r.url.includes('/figuras/')).flush({}, {status:503,statusText:'Failure'});
|
||||||
expect(fixture.componentInstance.result().status).toBe('error');
|
expect(fixture.componentInstance.result().status).toBe('error');
|
||||||
});
|
});
|
||||||
|
it('TEA: dona de un periodo con ambos anillos y botones para resaltar grupos y categorías', () => {
|
||||||
|
fixture.detectChanges(); dataRequest().flush(c2Fixture());
|
||||||
|
const result = fixture.componentInstance.result();
|
||||||
|
expect(result.status).toBe('ready');
|
||||||
|
expect(result.hierarchy).toBeUndefined();
|
||||||
|
expect(result.figure?.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||||
|
expect(result.highlight?.groups.length).toBeGreaterThan(0);
|
||||||
|
expect(result.highlight?.items.every(i => i.group)).toBe(true);
|
||||||
|
});
|
||||||
it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => {
|
it('cambio de periodo cancela lectura, limpia selección y no expone snapshot previo', () => {
|
||||||
|
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
|
||||||
|
fixture.componentRef.setInput('dominio', 'cama');
|
||||||
fixture.detectChanges(); const old = dataRequest();
|
fixture.detectChanges(); const old = dataRequest();
|
||||||
fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges();
|
fixture.componentRef.setInput('applied', { ...applied, revision:2,selection:{mode:'explicit',periodos:['2026-S1']} }); fixture.detectChanges();
|
||||||
expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1');
|
expect(old.cancelled).toBe(true); const current = dataRequest(); expect(current.request.params.get('periodos')).toBe('2026-S1');
|
||||||
|
|||||||
@@ -96,17 +96,17 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
|||||||
expect(card('cacu_eu13')).toBeDefined();
|
expect(card('cacu_eu13')).toBeDefined();
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
|
it('EU7 primero sin alterar catálogo; selección y fijación prevalecen y conservan identidades y memoria', () => {
|
||||||
const original = page.catalog(), before = cards();
|
const original = page.catalog(), before = cards();
|
||||||
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
||||||
expect(before[0].indicador.id).toBe('cacu_eu7');
|
expect(before[0].indicador.id).toBe('cacu_eu7');
|
||||||
page.togglePinned(original[0]); fixture.detectChanges();
|
page.togglePinned(original[0]); fixture.detectChanges();
|
||||||
expect(cards()[0]).toBe(card('cacu_eu13'));
|
expect(cards()[0]).toBe(card('cacu_eu13'));
|
||||||
page.changeSearchQuery('anómala'); fixture.detectChanges();
|
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
|
||||||
expect(cards()[0].indicador.id).toBe('ind1');
|
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
|
||||||
page.changeSearchQuery(''); fixture.detectChanges();
|
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
|
||||||
|
page.showAllIndicators(); fixture.detectChanges();
|
||||||
expect(cards()[0].indicador.id).toBe('cacu_eu13');
|
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(page.catalog()).toBe(original);
|
||||||
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
|
|||||||
@@ -340,12 +340,10 @@ describe('Filtros generales de CaMa: periodo único', () => {
|
|||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.');
|
expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.');
|
||||||
});
|
});
|
||||||
it('los demás dominios conservan Modalidad, la selección múltiple y sus resúmenes', () => {
|
it('los demás dominios usan la misma selección de un periodo, sin la fila compacta', () => {
|
||||||
// Fails if the single-period layout leaks to CaCu or TEA.
|
// Every domain selects one period; fails if the compact row of CaMa leaks to CaCu or TEA.
|
||||||
mount(false, { mode: 'todos' }, { mode: 'todos' });
|
mount(false, { mode: 'todos' }, { mode: 'todos' });
|
||||||
expect(labels()).toEqual(['Intervalo de tiempo', 'Modalidad']);
|
expect(labels()).toEqual(['Intervalo de análisis', 'Periodo seleccionado']);
|
||||||
const text = fixture.nativeElement.textContent as string;
|
expect(fixture.nativeElement.querySelector('.fields.compact')).toBeNull();
|
||||||
expect(text).toContain('Selección en edición: Todos con reporte');
|
|
||||||
expect(text).toContain('Sin cambios pendientes.');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -105,14 +105,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
|
||||||
expect(titles()).toEqual(before);
|
expect(titles()).toEqual(before);
|
||||||
});
|
});
|
||||||
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados, navegación flotante, selector y conteo de figuras', domain => {
|
it.each(['tea', 'cacu'] as const)('%s conserva el selector de indicadores y los fijados desde cinco indicadores', domain => {
|
||||||
// Fails if CaMa's simplified section leaks into the other domains.
|
// Fails if CaMa's simplified section leaks into the other domains. In every domain the cards carry no
|
||||||
|
// representation selector or figure count, and there is no floating navigation: the selector replaces it.
|
||||||
open(domain, OTRO(domain));
|
open(domain, OTRO(domain));
|
||||||
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
||||||
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||||
expect(root().querySelector('.graphic-navigation-trigger')).not.toBeNull();
|
expect(root().querySelector('.graphic-navigation-trigger')).toBeNull();
|
||||||
expect(section().querySelector('app-indicador-catalog-card mat-form-field')).not.toBeNull();
|
expect(section().textContent).not.toContain('figuras publicadas');
|
||||||
expect(section().textContent).toContain('2 figuras publicadas');
|
|
||||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
|
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
|
||||||
});
|
});
|
||||||
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
|||||||
expect(text()).not.toContain('Indicador de CaMa');
|
expect(text()).not.toContain('Indicador de CaMa');
|
||||||
});
|
});
|
||||||
it('los controles propios de cada dominio se conservan al ir y volver', () => {
|
it('los controles propios de cada dominio se conservan al ir y volver', () => {
|
||||||
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
|
// CaCu keeps its search and pins; CaMa, with fewer cards, does not have them; neither state contaminates the other.
|
||||||
const abrir = (d: 'cacu' | 'cama', n: number) => {
|
const abrir = (d: 'cacu' | 'cama', n: number) => {
|
||||||
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
|
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
|
||||||
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
|
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
|
||||||
@@ -44,17 +44,14 @@ describe('Cambio de dominio con consultas pendientes', () => {
|
|||||||
abrir('cacu', 6);
|
abrir('cacu', 6);
|
||||||
expect(el().querySelector('.catalog-search')).not.toBeNull();
|
expect(el().querySelector('.catalog-search')).not.toBeNull();
|
||||||
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
|
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||||
expect(el().textContent).toContain('Modalidad');
|
|
||||||
abrir('cama', 6);
|
abrir('cama', 6);
|
||||||
expect(el().querySelector('.catalog-search')).toBeNull();
|
expect(el().querySelector('.catalog-search')).toBeNull();
|
||||||
expect(el().querySelector('.pin-toggle')).toBeNull();
|
expect(el().querySelector('.pin-toggle')).toBeNull();
|
||||||
expect(el().textContent).not.toContain('Modalidad');
|
|
||||||
expect(el().textContent).not.toContain('cacu_');
|
expect(el().textContent).not.toContain('cacu_');
|
||||||
abrir('cacu', 6);
|
abrir('cacu', 6);
|
||||||
// On the way back the page state (not only the DOM) says CaCu has its search again.
|
// On the way back the page state (not only the DOM) says CaCu has its search again.
|
||||||
expect(fixture.componentInstance.dominio).toBe('cacu');
|
expect(fixture.componentInstance.dominio).toBe('cacu');
|
||||||
expect(fixture.componentInstance.searchVisible()).toBe(true);
|
expect(fixture.componentInstance.searchVisible()).toBe(true);
|
||||||
expect(el().textContent).toContain('Modalidad');
|
|
||||||
expect(el().textContent).not.toContain('cama_');
|
expect(el().textContent).not.toContain('cama_');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
|||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { GlobalApplied } from './indicadores-memory';
|
import { GlobalApplied } from './indicadores-memory';
|
||||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
import { clicConfirmacion, clicDona, ConfirmacionIncompatible, CONFIRMACION_CACU, CONFIRMACION_CAMA, donaConfirmacion, donaExpandible, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
periodosConfirmacion, rangoTasas, seleccionBase, seleccionEtiqueta, tasas, vistaConfirmacion, wilson } from './indicadores-confirmacion-citologia';
|
||||||
|
|
||||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
|
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
|
||||||
|
|
||||||
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
||||||
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
||||||
@@ -62,7 +62,7 @@ describe('Confirmación histopatológica: modelo', () => {
|
|||||||
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
|
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
|
||||||
const m = modeloConfirmacion(d, '2026-S2');
|
const m = modeloConfirmacion(d, '2026-S2');
|
||||||
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
|
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(tasas(m, seleccionBase(m)).map(t => estadoTasa(t))).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
|
||||||
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
|
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
|
||||||
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
|
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
|
||||||
const s = modeloConfirmacion(d, '2026-S2');
|
const s = modeloConfirmacion(d, '2026-S2');
|
||||||
@@ -223,3 +223,65 @@ describe('Confirmación histopatológica: componente', () => {
|
|||||||
card.destroy(); http.expectNone(() => true);
|
card.destroy(); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Cáncer de mama's configuration of the same view. Fixture: a one-period answer of cama_histopatologia_birads
|
||||||
|
// built below, with two BI-RADS categories published and biopsies without a result kept apart.
|
||||||
|
describe('Confirmación histopatológica de cáncer de mama', () => {
|
||||||
|
const categorias = {
|
||||||
|
BENIGNO: { etiqueta: 'Benigno', color: '#9DBFE3', grupo: 'NO_MALIGNO' }, RIESGO_B3: { etiqueta: 'Lesión de riesgo (B3)', color: '#2F6DB3', grupo: 'NO_MALIGNO' },
|
||||||
|
IN_SITU: { etiqueta: 'Carcinoma in situ', color: '#D9822B', grupo: 'MALIGNO' }, INVASOR: { etiqueta: 'Carcinoma invasor', color: '#B5482E', grupo: 'MALIGNO' },
|
||||||
|
SIN_DATO: { etiqueta: 'Sin resultado histopatológico', color: '#BDBDBD', grupo: 'SIN_DATO' },
|
||||||
|
};
|
||||||
|
const n: Record<string, Record<string, number>> = {
|
||||||
|
BIRADS_5: { BENIGNO: 3, RIESGO_B3: 0, IN_SITU: 11, INVASOR: 38, SIN_DATO: 3 },
|
||||||
|
BIRADS_4A: { BENIGNO: 91, RIESGO_B3: 15, IN_SITU: 1, INVASOR: 7, SIN_DATO: 9 },
|
||||||
|
};
|
||||||
|
const datos = () => ({ id: 'cama_histopatologia_birads', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'birads',
|
||||||
|
valores_estrato: Object.keys(n), categorias, grupos_de_categoria: { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' },
|
||||||
|
filas: Object.entries(n).flatMap(([estrato, c]) => Object.entries(c).map(([categoria, v]) =>
|
||||||
|
({ periodo: '2025-S2', grupo: 'TOTAL', estrato, categoria, n: v, suprimido: 0 }))) }) as IndicadorDatos;
|
||||||
|
|
||||||
|
it('la elige el dominio y el indicador', () => {
|
||||||
|
// Fails if the view stops being found for cáncer de mama, or leaks to another indicator.
|
||||||
|
expect(vistaConfirmacion('cama', { id: 'cama_histopatologia_birads' })).toBe(CONFIRMACION_CAMA);
|
||||||
|
expect(vistaConfirmacion('cama', { id: 'cacu_confirmacion_citologia' })).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('filas BI-RADS de la más grave a la menor, base maligna y sin resultado aparte', () => {
|
||||||
|
// Fails if the rows don't follow the configuration, the base isn't malignancy or «Sin dato» enters the rate.
|
||||||
|
const m = modeloConfirmacion(datos(), '2025-S2', CONFIRMACION_CAMA), base = seleccionBase(m);
|
||||||
|
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_6', 'BIRADS_5', 'BIRADS_4C', 'BIRADS_4B', 'BIRADS_4A']);
|
||||||
|
expect(base).toEqual({ grupo: 'MALIGNO' });
|
||||||
|
expect(lectura(m, base)).toBe('Detección de cáncer (valor predictivo positivo)');
|
||||||
|
const t = tasas(m, base);
|
||||||
|
expect(t[1].k).toBe(49); expect(t[1].fila.den).toBe(52);
|
||||||
|
expect(t[4].k).toBe(8); expect(t[4].fila.den).toBe(114);
|
||||||
|
expect(estadoTasa(t[0], m.vista.textos.sujetos)).toBe('Sin pacientes con biopsia');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Dona interactiva como la de CaCu (sin botones)', () => {
|
||||||
|
const vista = { ...CONFIRMACION_CAMA, id: 'cacu_confirmacion_citologia', estrato: 'citologia_alto_grado' as const, filas: CONFIRMACION_CACU.filas, base: 'LIEAG' };
|
||||||
|
const modelo = () => modeloConfirmacion(respuesta(), '2026-S2', vista);
|
||||||
|
it('total → grupo → resultado y el centro regresa un paso hasta el total', () => {
|
||||||
|
// Fails if the centre stops returning to the total, or a group click no longer narrows to it.
|
||||||
|
const m = modelo(), g = m.grupos.findIndex(x => x.id === m.base), c = m.grados.findIndex(x => x.grupo === m.base);
|
||||||
|
let s = clicDona(m, {}, 'grupos', g); expect(s).toEqual({ grupo: m.base });
|
||||||
|
s = clicDona(m, s, 'categorias', c); expect(s).toEqual({ grupo: m.base, categoria: m.grados[c].id });
|
||||||
|
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({ grupo: m.base });
|
||||||
|
s = clicDona(m, s, 'centro', 0); expect(s).toEqual({});
|
||||||
|
expect(clicDona(m, { grupo: m.base }, 'grupos', g)).toEqual({});
|
||||||
|
const otra = m.grados.findIndex(x => x.grupo !== m.base);
|
||||||
|
expect(clicDona(m, { grupo: m.base }, 'categorias', otra)).toEqual({ grupo: m.base });
|
||||||
|
});
|
||||||
|
it('el grupo elegido llena los dos anillos y el total cuenta el grupo base en las tasas', () => {
|
||||||
|
// Fails if the other group's slices stay (no expansion), or the total stops reading as the base rate.
|
||||||
|
const m = modelo(), base = m.grupos.find(x => x.id === m.base)!;
|
||||||
|
const d = donaExpandible(m, { grupo: m.base }, 'claro');
|
||||||
|
const exterior = d.data[2]['values'] as number[];
|
||||||
|
m.grados.forEach((g, i) => expect(exterior[i] === 0).toBe(g.grupo !== m.base));
|
||||||
|
expect((d.data[1]['values'] as number[]).filter(v => v > 0)).toHaveLength(1);
|
||||||
|
expect(d.data[0]['text']).toEqual([`<b>${base.grados.reduce((s, c) => s + m.totales[c]!, 0)}</b><br>${base.etiqueta}`]);
|
||||||
|
expect(tasas(m, {}).map(t => t.k)).toEqual(tasas(m, seleccionBase(m)).map(t => t.k));
|
||||||
|
expect(lectura(m, {})).toBe(vista.textos.base);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||||
import { c2Theme } from './indicadores-c2-palette';
|
import { c2Theme } from './indicadores-c2-palette';
|
||||||
import { percentNumber, shareText } from './indicadores-format';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
|
||||||
@@ -24,6 +24,36 @@ export const FILAS_CITOLOGIA = [
|
|||||||
] as const;
|
] as const;
|
||||||
export const Z95 = 1.959963984540054;
|
export const Z95 = 1.959963984540054;
|
||||||
|
|
||||||
|
// One confirmation view: which indicator and stratum, its fixed rows (most severe on top), the grade whose group is
|
||||||
|
// the base view (the true positives), the grade read as a false positive, and the words the view uses.
|
||||||
|
export interface VistaConfirmacion {
|
||||||
|
id: string; estrato: DimensionEstrato; filas: readonly { id: string; etiqueta: string }[];
|
||||||
|
base: string; falsoPositivo: string;
|
||||||
|
// With buttons, the choice is made on them; without, on the donut (donaExpandible), whose centre names it.
|
||||||
|
botones: boolean;
|
||||||
|
textos: { base: string; falsoPositivo: string; sinConfirmacion: string; filas: string; encabezado: string; sujetos: string; vacio: string };
|
||||||
|
}
|
||||||
|
export const CONFIRMACION_CACU: VistaConfirmacion = {
|
||||||
|
id: ID_CONFIRMACION, estrato: ESTRATO_CITOLOGIA, filas: FILAS_CITOLOGIA, base: 'LIEAG', falsoPositivo: 'NORMAL', botones: true,
|
||||||
|
textos: { base: 'Verdaderos positivos (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia no confirmó lesión',
|
||||||
|
sinConfirmacion: 'Sin confirmación de alto grado', filas: 'Por resultado de la citología', encabezado: 'Citología', sujetos: 'mujeres',
|
||||||
|
vacio: 'No hay citologías de alto grado publicadas para este periodo.' },
|
||||||
|
};
|
||||||
|
// Cáncer de mama: the biopsies by the BI-RADS of the mammogram that led to them; the base is malignancy.
|
||||||
|
export const CONFIRMACION_CAMA: VistaConfirmacion = {
|
||||||
|
id: 'cama_histopatologia_birads', estrato: 'birads', base: 'INVASOR', falsoPositivo: 'BENIGNO', botones: false,
|
||||||
|
filas: [{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6' }, { id: 'BIRADS_5', etiqueta: 'BI-RADS 5' }, { id: 'BIRADS_4C', etiqueta: 'BI-RADS 4C' },
|
||||||
|
{ id: 'BIRADS_4B', etiqueta: 'BI-RADS 4B' }, { id: 'BIRADS_4A', etiqueta: 'BI-RADS 4A' }],
|
||||||
|
textos: { base: 'Detección de cáncer (valor predictivo positivo)', falsoPositivo: 'Falsos positivos: la biopsia resultó benigna',
|
||||||
|
sinConfirmacion: 'Sin malignidad', filas: 'Por categoría BI-RADS', encabezado: 'BI-RADS', sujetos: 'pacientes',
|
||||||
|
vacio: 'No hay biopsias publicadas para este periodo.' },
|
||||||
|
};
|
||||||
|
const VISTAS_CONFIRMACION: Readonly<Partial<Record<Dominio, VistaConfirmacion>>> = { cacu: CONFIRMACION_CACU, cama: CONFIRMACION_CAMA };
|
||||||
|
export function vistaConfirmacion(dominio: Dominio, indicador: Pick<Indicador, 'id'>): VistaConfirmacion | undefined {
|
||||||
|
const vista = VISTAS_CONFIRMACION[dominio];
|
||||||
|
return vista?.id === indicador.id ? vista : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||||
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
|
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
|
||||||
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
|
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
|
||||||
@@ -37,9 +67,10 @@ export interface FilaCitologia {
|
|||||||
export interface ModeloConfirmacion {
|
export interface ModeloConfirmacion {
|
||||||
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
|
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
|
||||||
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
|
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
|
||||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; vista: VistaConfirmacion;
|
||||||
}
|
}
|
||||||
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
|
// Without a group, the total: every result is shown and the rates count the base group.
|
||||||
|
export interface SeleccionConfirmacion { grupo?: string; categoria?: string; }
|
||||||
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||||
export class ConfirmacionIncompatible extends Error {}
|
export class ConfirmacionIncompatible extends Error {}
|
||||||
|
|
||||||
@@ -81,8 +112,8 @@ function rgba(hex: string, alfa: number): string {
|
|||||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
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. */
|
/** Validated periods of one stratified response, in request order or sorted. */
|
||||||
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[], vista = CONFIRMACION_CACU): string[] {
|
||||||
if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA
|
if (datos.id !== vista.id || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== vista.estrato
|
||||||
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|
|| !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))
|
|| 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)))
|
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|
||||||
@@ -93,8 +124,8 @@ export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solici
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** One /datos payload -> the contingency table of a single period. */
|
/** One /datos payload -> the contingency table of a single period. */
|
||||||
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): ModeloConfirmacion {
|
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string, vista = CONFIRMACION_CACU): ModeloConfirmacion {
|
||||||
periodosConfirmacion(datos, datos.tipo_periodo);
|
periodosConfirmacion(datos, datos.tipo_periodo, undefined, vista);
|
||||||
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
||||||
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
|
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 aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
|
||||||
@@ -112,8 +143,8 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
|||||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
||||||
grados: propios.map(g => g.id) };
|
grados: propios.map(g => g.id) };
|
||||||
});
|
});
|
||||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
// The base view is the group of the view's base grade (CaCu: "LIEAG o más"): the true positives.
|
||||||
const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.');
|
const base = grados.find(g => g.id === vista.base)?.grupo ?? fail(`El catálogo no publica el grado ${vista.base}.`);
|
||||||
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
|
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
|
||||||
const index = new Map<string, Record<string, unknown>>();
|
const index = new Map<string, Record<string, unknown>>();
|
||||||
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
||||||
@@ -128,11 +159,11 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
|||||||
}
|
}
|
||||||
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
|
// 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;
|
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.');
|
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos inválidos.');
|
||||||
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
||||||
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
||||||
if (!totales.every(registro)) fail('Totales de citología inválidos.');
|
if (!totales.every(registro)) fail('Totales por estrato inválidos.');
|
||||||
const filas = FILAS_CITOLOGIA.map(({ id, etiqueta }) => {
|
const filas = vista.filas.map(({ id, etiqueta }) => {
|
||||||
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
|
const 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 tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
|
||||||
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
|
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
|
||||||
@@ -148,15 +179,26 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
|||||||
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
|
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,
|
return { periodo, grados, grupos, base, filas, totales: porGrado,
|
||||||
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
|
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
|
||||||
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])] };
|
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])], vista };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
|
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
|
||||||
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
|
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
|
||||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.grados ?? [];
|
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === (sel.grupo ?? m.base))?.grados ?? [];
|
||||||
}
|
}
|
||||||
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
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;
|
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta
|
||||||
|
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'Todos los resultados';
|
||||||
|
}
|
||||||
|
/** CaCu's interactive donut: a group narrows to it, a result is chosen inside its group, the centre steps back
|
||||||
|
* (result -> its group -> the total), and choosing the chosen entry again also steps back. */
|
||||||
|
export function clicDona(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||||
|
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
|
||||||
|
if (traza === 'grupos') { const g = m.grupos[indice]?.id; return !g ? sel : sel.grupo === g && !sel.categoria ? {} : { grupo: g }; }
|
||||||
|
if (traza !== 'categorias') return sel;
|
||||||
|
const c = m.grados[indice];
|
||||||
|
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||||
|
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||||
}
|
}
|
||||||
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
/** 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 {
|
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||||
@@ -169,9 +211,9 @@ export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
|||||||
}
|
}
|
||||||
/** The axis title says what the rate reads. */
|
/** The axis title says what the rate reads. */
|
||||||
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||||
if (!sel.categoria && sel.grupo === m.base) return 'Verdaderos positivos (valor predictivo positivo)';
|
if (!sel.categoria && (sel.grupo ?? m.base) === m.base) return m.vista.textos.base;
|
||||||
if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión';
|
if (sel.categoria === m.vista.falsoPositivo) return m.vista.textos.falsoPositivo;
|
||||||
if (!sel.categoria) return 'Sin confirmación de alto grado';
|
if (!sel.categoria) return m.vista.textos.sinConfirmacion;
|
||||||
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
|
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
|
||||||
}
|
}
|
||||||
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
|
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
|
||||||
@@ -184,8 +226,8 @@ export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[]
|
|||||||
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
export function estadoTasa(t: Tasa): string {
|
export function estadoTasa(t: Tasa, sujetos = 'mujeres'): string {
|
||||||
return t.fila.den === 0 ? 'Sin mujeres con biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
return t.fila.den === 0 ? `Sin ${sujetos} con biopsia` : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||||||
}
|
}
|
||||||
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
||||||
export function rangoTasas(valores: Tasa[]): [number, number] {
|
export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||||
@@ -199,14 +241,14 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
|
|||||||
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||||
const p = c2Theme(tema);
|
const p = c2Theme(tema);
|
||||||
const valores = tasas(m, sel);
|
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 color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === (sel.grupo ?? m.base))!.color;
|
||||||
const y = valores.map(t => t.fila.etiqueta);
|
const y = valores.map(t => t.fila.etiqueta);
|
||||||
return { data: [{
|
return { data: [{
|
||||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||||
marker: { size: 12, color }, cliponaxis: false,
|
marker: { size: 12, color }, cliponaxis: false,
|
||||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
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!) },
|
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!)]),
|
customdata: valores.map(t => t.k === null ? [estadoTasa(t, m.vista.textos.sujetos), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||||
}], layout: {
|
}], layout: {
|
||||||
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||||
@@ -215,7 +257,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t
|
|||||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
|
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',
|
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 },
|
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}` })),
|
text: t.k === null ? estadoTasa(t, m.vista.textos.sujetos) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||||
}, config: { displayModeBar: false } };
|
}, config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,7 +269,7 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
|||||||
const interior = m.grupos.map(g => g.grados.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 exterior = m.grados.map(g => m.totales[g.id]!);
|
||||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
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 hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
|
||||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||||
return { data: [
|
return { data: [
|
||||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||||
@@ -242,3 +284,41 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
|||||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
], 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 } };
|
config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Donut without buttons, drawn like CaCu's interactive one: the chosen group fills both rings (the other's
|
||||||
|
* slices are zero, so its results expand), a chosen result keeps its colour and its siblings fade, and the
|
||||||
|
* centre names the choice. The traces keep their names and counts, so a choice animates. */
|
||||||
|
export function donaExpandible(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||||
|
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
|
||||||
|
const p = c2Theme(tema), total = m.conBiopsia;
|
||||||
|
const nGrupo = (g: GrupoGrados) => g.grados.reduce((s, c) => s + m.totales[c]!, 0);
|
||||||
|
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(g) : 0);
|
||||||
|
const exterior = m.grados.map(g => !sel.grupo || sel.grupo === g.grupo ? m.totales[g.id]! : 0);
|
||||||
|
const centro = sel.categoria ? m.totales[sel.categoria]! : sel.grupo ? nGrupo(m.grupos.find(g => g.id === sel.grupo)!) : total;
|
||||||
|
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||||
|
const suma = values.reduce((s, n) => s + n, 0);
|
||||||
|
return values.map((v, i) => !suma || v / suma < .05 ? '' : escapar(labels[i]) + (pct ? '<br>' + shareText(v, suma) : ''));
|
||||||
|
};
|
||||||
|
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'text', textposition: 'inside',
|
||||||
|
insidetextorientation: 'horizontal' };
|
||||||
|
const hover = { hovertemplate: `%{label}<br>%{customdata[0]} ${m.vista.textos.sujetos} con biopsia, %{customdata[1]}<extra></extra>` };
|
||||||
|
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||||
|
return { data: [
|
||||||
|
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
||||||
|
text: [`<b>${miles(centro)}</b><br>${escapar(sel.grupo || sel.categoria ? seleccionEtiqueta(m, sel) : 'Con biopsia')}`],
|
||||||
|
textfont: { size: 16, color: p.text }, marker: { colors: [p.background] },
|
||||||
|
hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Todos los resultados') + '<extra></extra>' },
|
||||||
|
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||||
|
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||||
|
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
|
||||||
|
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||||
|
// Outer labels go outside the ring with a leader line, at full size; automargin makes room for them and
|
||||||
|
// shrinks the three rings together, so they stay concentric.
|
||||||
|
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||||
|
labels: m.grados.map(g => escapar(g.etiqueta)), textposition: 'outside', automargin: true,
|
||||||
|
text: exterior.map((v, i) => v ? escapar(m.grados[i].etiqueta) + '<br>' + shareText(v, exterior.reduce((s, n) => s + n, 0)) : ''),
|
||||||
|
textfont: { size: 12, color: p.text }, customdata: custom(exterior),
|
||||||
|
marker: { colors: m.grados.map(g => rgba(g.color, sel.categoria && g.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||||
|
], layout: { autosize: true, height: 440, margin: { t: 30, l: 30, r: 30, b: 30 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||||
|
config: { displayModeBar: false } };
|
||||||
|
}
|
||||||
|
|||||||
@@ -176,6 +176,8 @@ describe('navegación multiperiodo en el panel común', () => {
|
|||||||
expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true);
|
expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => {
|
it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => {
|
||||||
|
// TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts).
|
||||||
|
fixture.componentRef.setInput('dominio', 'cama');
|
||||||
apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges();
|
apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges();
|
||||||
expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy();
|
expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy();
|
||||||
apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true);
|
apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true);
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import eu7 from './fixtures/eu7-c2-ejemplos.json';
|
||||||
|
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||||
|
import { modelo, vistaEscenario } from './indicadores-eu7-escenario';
|
||||||
|
|
||||||
|
// Covers what lets a domain reuse CaCu's interactive donut and bars without code of its own: the view is
|
||||||
|
// chosen by the catalog's `escenario`. The follow-up list announced by the answer is covered by
|
||||||
|
// `seguimiento-tabla.service.spec.ts` and `indicadores-seguimiento-tabla.spec.ts`.
|
||||||
|
// Fixture: `eu7-c2-ejemplos.json` (CaCu's EU7 answers, relabelled here as another stratum).
|
||||||
|
|
||||||
|
describe('Vista de dona y barras por estrato', () => {
|
||||||
|
const item = (extra: Partial<Indicador> = {}): Indicador => ({ id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'], ...extra });
|
||||||
|
it('la elige el campo escenario del catálogo, y CaCu EU7 la conserva sin él', () => {
|
||||||
|
// Fails if the view goes back to being recognised by CaCu's indicator id only.
|
||||||
|
expect(vistaEscenario('cama', item({ escenario: { estrato: 'birads', etiqueta: 'categoría BI-RADS' } }))?.estrato).toBe('birads');
|
||||||
|
expect(vistaEscenario('cacu', item({ id: 'cacu_eu7' }))?.estrato).toBe('estatus_seguimiento');
|
||||||
|
expect(vistaEscenario('cama', item())).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('arma el modelo con otro indicador y otro estrato', () => {
|
||||||
|
// Fails if `modelo` checks CaCu's id or its stratum instead of the ones it is given.
|
||||||
|
const relabel = (d: unknown, estrato: string | null) => ({ ...structuredClone(d) as IndicadorDatos, id: 'cama_histopatologia_birads', ...(estrato ? { estrato } : {}) });
|
||||||
|
const general = relabel(eu7.general, null), porBirads = relabel(eu7.estatus_seguimiento, 'birads');
|
||||||
|
expect(modelo(general, porBirads, '2025-S2', 'birads').total).toBe(946);
|
||||||
|
expect(() => modelo(general, porBirads, '2025-S2')).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,11 +1,18 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
|
||||||
import { c2Theme } from './indicadores-c2-palette';
|
import { c2Theme } from './indicadores-c2-palette';
|
||||||
import { percentNumber, shareText } from './indicadores-format';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
|
||||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||||
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
// A C2 distribution with category groups, next to the same categories by one stratum. Unknown cells never become zero.
|
||||||
export const ESTRATO = 'estatus_seguimiento';
|
export const ESTRATO = 'estatus_seguimiento';
|
||||||
const SIN_DATO = 'SIN_DATO';
|
const SIN_DATO = 'SIN_DATO';
|
||||||
|
// CaCu's EU7 predates the catalog's `escenario` field.
|
||||||
|
const EU7: VistaEscenario = { estrato: ESTRATO, etiqueta: 'escenario clínico' };
|
||||||
|
export function vistaEscenario(dominio: Dominio, indicador: Indicador): VistaEscenario | undefined {
|
||||||
|
if (indicador.escenario) return indicador.escenario;
|
||||||
|
return dominio === 'cacu' && indicador.id === 'cacu_eu7' ? EU7 : undefined;
|
||||||
|
}
|
||||||
|
export const esEu7 = (vista: VistaEscenario) => vista === EU7;
|
||||||
export interface Seleccion { grupo?: string; categoria?: string; }
|
export interface Seleccion { grupo?: string; categoria?: string; }
|
||||||
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
|
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
|
||||||
export interface Grupo { id: string; etiqueta: string; color: string; }
|
export interface Grupo { id: string; etiqueta: string; color: string; }
|
||||||
@@ -64,7 +71,7 @@ function catalogo(data: IndicadorDatos): Categoria[] {
|
|||||||
/** Validate the common temporal scope before exposing any period's figures. */
|
/** Validate the common temporal scope before exposing any period's figures. */
|
||||||
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||||
for (const d of [general, escenarios]) {
|
for (const d of [general, escenarios]) {
|
||||||
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
if (d.id !== general.id || 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'
|
|| 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))
|
|| !(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))) {
|
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
|
||||||
@@ -80,10 +87,10 @@ export function periodosCompatibles(general: IndicadorDatos, escenarios: Indicad
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
|
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
|
||||||
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo {
|
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string, estrato: DimensionEstrato = ESTRATO): Modelo {
|
||||||
periodosCompatibles(general, porEscenario, general.tipo_periodo);
|
periodosCompatibles(general, porEscenario, general.tipo_periodo);
|
||||||
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
|
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
|
||||||
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo)
|
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
|
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|
||||||
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|
|| !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)) {
|
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
|
||||||
@@ -212,7 +219,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
|||||||
config: { displayModeBar: false } };
|
config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
/** Selection never changes the original denominator or renormalizes a subset. */
|
/** Selection never changes the original denominator or renormalizes a subset. */
|
||||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
export function barras(m: Modelo, sel: Seleccion, tema: Tema, eje = '% de pacientes del escenario con resultado'): PlotlyFigure {
|
||||||
const p = c2Theme(tema);
|
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 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 y = m.escenarios.map(s => escapar(s.etiqueta));
|
||||||
@@ -235,7 +242,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
|||||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
||||||
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
||||||
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
|
xaxis: { title: { text: eje }, 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],
|
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] },
|
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,
|
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||||
|
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
|
||||||
|
fig_c1_barras_edad: 'Barras por grupo de edad',
|
||||||
|
fig_c1_dona_edad: 'Dona por grupo de edad',
|
||||||
|
fig_c1_donas: 'Dona de dos anillos',
|
||||||
fig_c1_grupos: 'Grupos',
|
fig_c1_grupos: 'Grupos',
|
||||||
fig_c1_puntos: 'Puntos',
|
fig_c1_puntos: 'Puntos',
|
||||||
fig_c2_apiladas: 'Barras apiladas',
|
fig_c2_apiladas: 'Barras apiladas',
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
|||||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
|
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
|
||||||
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); }
|
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); }
|
||||||
function draft(tipo: TipoPeriodo, periods: string[]) {
|
function draft(tipo: TipoPeriodo, periods: string[]) {
|
||||||
const control = editor(); control.changeTipo(tipo); control.changeMode('manual');
|
const control = editor(); control.changeTipo(tipo); control.select([]);
|
||||||
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
|
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
|
||||||
}
|
}
|
||||||
function apply() { page.applyFilters(); fixture.detectChanges(); }
|
function apply() { page.applyFilters(); fixture.detectChanges(); }
|
||||||
@@ -67,7 +67,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
|||||||
});
|
});
|
||||||
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
|
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
|
||||||
load(); open(); respond(); const result = panels()[0].result();
|
load(); open(); respond(); const result = panels()[0].result();
|
||||||
editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0);
|
editor().select([]); apply(); expect(page.filters!.applied.revision).toBe(0);
|
||||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||||
draft('semestre', ['2025-S1']); fixture.detectChanges();
|
draft('semestre', ['2025-S1']); fixture.detectChanges();
|
||||||
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||||
@@ -82,9 +82,9 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
|||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
|
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
|
||||||
load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond();
|
load(); open(); respond(); draft('semestre', ['2025-S2']); apply(); respond();
|
||||||
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
|
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
|
||||||
editor().select(['2025-S2', '2025-S1']); apply();
|
editor().select(['2025-S2']); apply();
|
||||||
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
|
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
|
||||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
@@ -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();
|
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
|
||||||
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
|
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(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
|
||||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de tiempo mes');
|
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de análisis mensual');
|
||||||
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||||
r.flush({ data: [], layout: {} });
|
r.flush({ data: [], layout: {} });
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||||
@@ -145,7 +145,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
|||||||
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
|
editor().year = '2025'; editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
|
||||||
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
|
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||||
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
|
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
|
||||||
expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
expect(editor().selectedPeriods).toEqual(['2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
||||||
expect(cards()[0].visible).toBe(false);
|
expect(cards()[0].visible).toBe(false);
|
||||||
http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
|
http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, toggleHighlight } from './indicadores-highlight';
|
||||||
|
import { PlotlyFigure } from './indicadores.models';
|
||||||
|
|
||||||
|
// A double donut like dona(): 0 centre, 1 groups, 2 categories.
|
||||||
|
const figure: PlotlyFigure = { data: [
|
||||||
|
{ type: 'pie', values: [1], text: ['<b>10</b><br>TOTAL'] },
|
||||||
|
{ type: 'pie', values: [6, 4], marker: { colors: ['rgba(10, 20, 30, 1)', '#FF0000'] } },
|
||||||
|
{ type: 'pie', values: [2, 4, 4], marker: { colors: ['#000000', '#111111', '#222222'] } },
|
||||||
|
], layout: {} };
|
||||||
|
const h: FigureHighlight = { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
|
||||||
|
groups: [{ id: 'A', label: 'Grupo A', color: '#000000', points: [{ trace: 1, index: 0 }, { trace: 2, index: 0 }, { trace: 2, index: 1 }], center: 'A' },
|
||||||
|
{ id: 'B', label: 'Grupo B', color: '#FF0000', points: [{ trace: 1, index: 1 }, { trace: 2, index: 2 }], center: 'B' }],
|
||||||
|
items: [{ id: 'a1', label: 'A · 1', short: '1', color: '#000000', group: 'A', points: [{ trace: 2, index: 0 }], center: 'a1' },
|
||||||
|
{ id: 'a2', label: 'A · 2', short: '2', color: '#111111', group: 'A', points: [{ trace: 2, index: 1 }] },
|
||||||
|
{ id: 'b1', label: 'B · 1', short: '1', color: '#222222', group: 'B', points: [{ trace: 2, index: 2 }] }] };
|
||||||
|
const colors = (f: PlotlyFigure, t: number) => (f.data[t]['marker'] as { colors: string[] }).colors;
|
||||||
|
|
||||||
|
describe('Botones que resaltan una parte de la figura', () => {
|
||||||
|
it('sin selección deja la figura intacta', () => {
|
||||||
|
expect(highlightFigure(figure, h, {})).toBe(figure);
|
||||||
|
expect(highlightLabel(h, {})).toBe('TOTAL');
|
||||||
|
});
|
||||||
|
it('un grupo conserva su parte de ambos anillos y atenúa el resto, también colores rgba', () => {
|
||||||
|
const f = highlightFigure(figure, h, { group: 'B' });
|
||||||
|
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 0.3)', '#FF0000']);
|
||||||
|
expect(colors(f, 2)).toEqual(['rgba(0, 0, 0, 0.3)', 'rgba(17, 17, 17, 0.3)', '#222222']);
|
||||||
|
expect(f.data[0]['text']).toEqual(['B']);
|
||||||
|
expect(colors(figure, 2)).toEqual(['#000000', '#111111', '#222222']);
|
||||||
|
});
|
||||||
|
it('una categoría conserva su grupo en el anillo interior', () => {
|
||||||
|
const f = highlightFigure(figure, h, { item: 'a1' });
|
||||||
|
expect(colors(f, 1)).toEqual(['rgba(10, 20, 30, 1)', 'rgba(255, 0, 0, 0.3)']);
|
||||||
|
expect(colors(f, 2)).toEqual(['#000000', 'rgba(17, 17, 17, 0.3)', 'rgba(34, 34, 34, 0.3)']);
|
||||||
|
expect(f.data[0]['text']).toEqual(['a1']);
|
||||||
|
});
|
||||||
|
it('en barras atenúa con la opacidad de cada barra', () => {
|
||||||
|
const bars: PlotlyFigure = { data: [{ type: 'bar', x: ['a', 'b', 'c'], y: [1, 2, 3], marker: { color: '#000000' } }], layout: {} };
|
||||||
|
const hb: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todas', items: ['a', 'b', 'c'].map((id, i) => ({ id, label: id, color: '#000000', points: [{ trace: 0, index: i }] })) };
|
||||||
|
expect((highlightFigure(bars, hb, { item: 'b' }).data[0]['marker'] as { opacity: number[] }).opacity).toEqual([.3, 1, .3]);
|
||||||
|
});
|
||||||
|
it('alterna como CaCu: repetir vuelve un paso y un grupo limita las categorías', () => {
|
||||||
|
expect(toggleHighlight(h, {}, 'group', 'A')).toEqual({ group: 'A' });
|
||||||
|
expect(toggleHighlight(h, { group: 'A' }, 'group', 'A')).toEqual({});
|
||||||
|
expect(toggleHighlight(h, { group: 'A' }, 'item', 'a2')).toEqual({ group: 'A', item: 'a2' });
|
||||||
|
expect(toggleHighlight(h, { group: 'A', item: 'a2' }, 'item', 'a2')).toEqual({ group: 'A' });
|
||||||
|
expect(toggleHighlight(h, { group: 'A' }, 'item', 'b1')).toEqual({ group: 'A' });
|
||||||
|
expect(toggleHighlight(h, {}, 'item', 'b1')).toEqual({ item: 'b1' });
|
||||||
|
});
|
||||||
|
it('un clic en el anillo exterior es la categoría; en el interior, el grupo', () => {
|
||||||
|
expect(highlightAt(h, { trace: 2, index: 1 })).toEqual({ kind: 'item', id: 'a2' });
|
||||||
|
expect(highlightAt(h, { trace: 1, index: 1 })).toEqual({ kind: 'group', id: 'B' });
|
||||||
|
expect(highlightAt(h, { trace: 0, index: 0 })).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('agrupa los botones en filas: cada grupo seguido de sus categorías', () => {
|
||||||
|
expect(highlightRows(h).map(r => [r.group?.id, r.items.map(i => i.id)])).toEqual([['A', ['a1', 'a2']], ['B', ['b1']]]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { Modelo } from './indicadores-eu7-escenario';
|
||||||
|
import { PlotlyFigure } from './indicadores.models';
|
||||||
|
|
||||||
|
// Legend buttons that highlight one part of a figure, like CaCu's «Distribución de resultados
|
||||||
|
// citológicos»: the chosen group or category keeps its colour and everything else fades.
|
||||||
|
export interface HighlightPoint { trace: number; index: number; }
|
||||||
|
export interface HighlightEntry {
|
||||||
|
id: string; label: string; color: string;
|
||||||
|
// Shorter label for the button when it sits next to its group's button.
|
||||||
|
short?: string;
|
||||||
|
// Only for categories: the group they belong to (its button narrows the categories on offer).
|
||||||
|
group?: string;
|
||||||
|
points: readonly HighlightPoint[];
|
||||||
|
// Text for the centre of a donut while this entry is chosen.
|
||||||
|
center?: string;
|
||||||
|
}
|
||||||
|
export interface FigureHighlight {
|
||||||
|
groups: readonly HighlightEntry[];
|
||||||
|
items: readonly HighlightEntry[];
|
||||||
|
// Traces whose points fade when they are not part of the choice.
|
||||||
|
traces: readonly number[];
|
||||||
|
// Where a donut shows its centre text: a pie trace's single text, or a layout annotation.
|
||||||
|
center?: { trace: number } | { annotation: number };
|
||||||
|
// Name of the whole, for the status line.
|
||||||
|
allLabel: string;
|
||||||
|
}
|
||||||
|
export interface HighlightSelection { group?: string; item?: string; }
|
||||||
|
|
||||||
|
const FADED = .3;
|
||||||
|
// Accepts #RRGGBB and rgb()/rgba() (dona() already writes its colours as rgba).
|
||||||
|
function rgba(color: string, alpha: number): string {
|
||||||
|
const hex = /^#([0-9a-f]{6})$/i.exec(color);
|
||||||
|
if (hex) {
|
||||||
|
const [r, g, b] = [0, 2, 4].map(i => parseInt(hex[1].slice(i, i + 2), 16));
|
||||||
|
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||||
|
}
|
||||||
|
const rgb = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(color);
|
||||||
|
return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color;
|
||||||
|
}
|
||||||
|
export function highlightEntry(h: FigureHighlight, sel: HighlightSelection): HighlightEntry | undefined {
|
||||||
|
return sel.item ? h.items.find(e => e.id === sel.item) : sel.group ? h.groups.find(e => e.id === sel.group) : undefined;
|
||||||
|
}
|
||||||
|
export function highlightLabel(h: FigureHighlight, sel: HighlightSelection): string {
|
||||||
|
return highlightEntry(h, sel)?.label ?? h.allLabel;
|
||||||
|
}
|
||||||
|
// Same state machine as CaCu: choosing the chosen entry again goes back one step.
|
||||||
|
export function toggleHighlight(h: FigureHighlight, sel: HighlightSelection, kind: 'group' | 'item', id: string): HighlightSelection {
|
||||||
|
if (kind === 'group') return !h.groups.some(g => g.id === id) || sel.group === id ? {} : { group: id };
|
||||||
|
const item = h.items.find(e => e.id === id);
|
||||||
|
if (!item || (sel.group && item.group !== sel.group)) return sel;
|
||||||
|
return sel.item === id ? (sel.group ? { group: sel.group } : {}) : { ...(sel.group ? { group: sel.group } : {}), item: id };
|
||||||
|
}
|
||||||
|
// The entry a click on the figure means: a category first, otherwise a group.
|
||||||
|
export function highlightAt(h: FigureHighlight, point: HighlightPoint): { kind: 'group' | 'item'; id: string } | undefined {
|
||||||
|
const hit = (e: HighlightEntry) => e.points.some(p => p.trace === point.trace && p.index === point.index);
|
||||||
|
// A group also covers its categories' slices, so an outer slice hits both: the category wins.
|
||||||
|
const item = h.items.find(hit);
|
||||||
|
if (item) return { kind: 'item', id: item.id };
|
||||||
|
const group = h.groups.find(hit);
|
||||||
|
return group ? { kind: 'group', id: group.id } : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function highlightFigure(figure: PlotlyFigure, h: FigureHighlight, sel: HighlightSelection): PlotlyFigure {
|
||||||
|
const entry = highlightEntry(h, sel);
|
||||||
|
if (!entry) return figure;
|
||||||
|
const keep = new Set(entry.points.map(p => p.trace + ':' + p.index));
|
||||||
|
// A chosen category also keeps its group's slice of the inner ring (not its sibling categories).
|
||||||
|
const group = entry.group ? h.groups.find(g => g.id === entry.group) : undefined;
|
||||||
|
const own = new Set(entry.points.map(p => p.trace));
|
||||||
|
group?.points.filter(p => !own.has(p.trace)).forEach(p => keep.add(p.trace + ':' + p.index));
|
||||||
|
const data = figure.data.map((trace, t) => {
|
||||||
|
if (!h.traces.includes(t)) return trace;
|
||||||
|
const marker = (trace['marker'] ?? {}) as Record<string, unknown>;
|
||||||
|
if (trace['type'] === 'pie') {
|
||||||
|
const colors = (marker['colors'] as unknown[] | undefined) ?? [];
|
||||||
|
return { ...trace, marker: { ...marker, colors: colors.map((c, i) => typeof c === 'string' && !keep.has(t + ':' + i) ? rgba(c, FADED) : c) } };
|
||||||
|
}
|
||||||
|
const count = Array.isArray(trace['x']) ? (trace['x'] as unknown[]).length : Array.isArray(trace['y']) ? (trace['y'] as unknown[]).length : 0;
|
||||||
|
return { ...trace, marker: { ...marker, opacity: Array.from({ length: count }, (_, i) => keep.has(t + ':' + i) ? 1 : FADED) } };
|
||||||
|
});
|
||||||
|
let layout = figure.layout;
|
||||||
|
if (entry.center !== undefined && h.center) {
|
||||||
|
if ('trace' in h.center) {
|
||||||
|
const t = h.center.trace;
|
||||||
|
data[t] = { ...data[t], text: [entry.center] };
|
||||||
|
} else {
|
||||||
|
const annotations = [...((layout['annotations'] as Record<string, unknown>[] | undefined) ?? [])];
|
||||||
|
if (annotations[h.center.annotation]) annotations[h.center.annotation] = { ...annotations[h.center.annotation], text: entry.center };
|
||||||
|
layout = { ...layout, annotations };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ...figure, data, layout };
|
||||||
|
}
|
||||||
|
|
||||||
|
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
// Buttons for a figure drawn by dona() (traces: 0 centre, 1 groups, 2 categories). A group also
|
||||||
|
// covers its categories' slices; the centre shows the count of the choice. `short` gives each
|
||||||
|
// category's button label next to its group (by default, its full label).
|
||||||
|
export function donaHighlight(m: Modelo, short: (id: string) => string | undefined = () => undefined): FigureHighlight {
|
||||||
|
const centre = (n: number, label: string) => '<b>' + n.toLocaleString('es-MX') + '</b><br>' + escape(label);
|
||||||
|
return { traces: [1, 2], center: { trace: 0 }, allLabel: 'TOTAL',
|
||||||
|
groups: m.grupos.map((g, gi) => {
|
||||||
|
const children = m.categorias.map((c, i) => ({ c, i })).filter(({ c }) => c.grupo === g.id);
|
||||||
|
return { id: g.id, label: g.etiqueta, color: g.color,
|
||||||
|
points: [{ trace: 1, index: gi }, ...children.map(({ i }) => ({ trace: 2, index: i }))],
|
||||||
|
center: centre(children.reduce((n, { c }) => n + (m.celdas[c.id].n ?? 0), 0), g.etiqueta) };
|
||||||
|
}),
|
||||||
|
items: m.categorias.map((c, i) => ({ id: c.id, label: c.etiqueta, short: short(c.id), color: c.color, group: c.grupo,
|
||||||
|
points: [{ trace: 2, index: i }], center: centre(m.celdas[c.id].n ?? 0, c.etiqueta) })) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rows of buttons: each group followed by its categories; categories without a group share one row.
|
||||||
|
export function highlightRows(h: FigureHighlight): { group?: HighlightEntry; items: HighlightEntry[] }[] {
|
||||||
|
const rows = h.groups.map(group => ({ group, items: h.items.filter(i => i.group === group.id) }));
|
||||||
|
const loose = h.items.filter(i => !i.group || !h.groups.some(g => g.id === i.group));
|
||||||
|
return loose.length ? [...rows, { items: loose }] : rows;
|
||||||
|
}
|
||||||
@@ -26,6 +26,13 @@ const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
|
|||||||
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
|
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
|
||||||
};
|
};
|
||||||
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'casos', eje: 'Casos' };
|
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'casos', eje: 'Casos' };
|
||||||
|
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
|
||||||
|
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||||
|
export interface HistoricoOpciones {
|
||||||
|
// Same vertical scale across small charts, so their heights compare.
|
||||||
|
yMax?: number;
|
||||||
|
pequena?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
function validar(data: IndicadorDatos) {
|
function validar(data: IndicadorDatos) {
|
||||||
for (const row of data.filas) {
|
for (const row of data.filas) {
|
||||||
@@ -33,14 +40,14 @@ function validar(data: IndicadorDatos) {
|
|||||||
}
|
}
|
||||||
return cronologico(data.periodos);
|
return cronologico(data.periodos);
|
||||||
}
|
}
|
||||||
function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string) {
|
function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string, pequena = false) {
|
||||||
const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo);
|
const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo);
|
||||||
// A label for every month does not fit: one per quarter is still readable, with the full period on hover.
|
// A label for every month does not fit: one per quarter is still readable, with the full period on hover.
|
||||||
return {
|
return {
|
||||||
autosize: true, height: 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
autosize: true, height: pequena ? 340 : 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
|
||||||
margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false },
|
margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false },
|
||||||
xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0,
|
xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0,
|
||||||
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % 3 === 0) },
|
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % (pequena && periodos.length > 12 ? 6 : 3) === 0) },
|
||||||
yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false },
|
yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false },
|
||||||
// Shaded, because an empty space alone reads as zero. Text below the figure says the same.
|
// Shaded, because an empty space alone reads as zero. Text below the figure says the same.
|
||||||
shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 },
|
shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 },
|
||||||
@@ -83,7 +90,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
|||||||
const periodos = validar(data);
|
const periodos = validar(data);
|
||||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = c2Theme(tema).line;
|
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line;
|
||||||
return {
|
return {
|
||||||
figure: { data: [
|
figure: { data: [
|
||||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
|
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
|
||||||
@@ -95,7 +102,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
|||||||
suprimidos, sinDato,
|
suprimidos, sinDato,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
function mediana(data: IndicadorDatos, tema: Tema): Trazo {
|
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
|
||||||
const periodos = validar(data), unidad = unidadDe(data);
|
const periodos = validar(data), unidad = unidadDe(data);
|
||||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
|
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
|
||||||
const linea = c2Theme(tema).line;
|
const linea = c2Theme(tema).line;
|
||||||
@@ -105,11 +112,19 @@ function mediana(data: IndicadorDatos, tema: Tema): Trazo {
|
|||||||
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 },
|
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 },
|
||||||
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
|
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
|
||||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||||
], layout: ejes(data, periodos, suprimidos, tema, 'Días') },
|
], layout: (() => {
|
||||||
|
const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena);
|
||||||
|
return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout;
|
||||||
|
})() },
|
||||||
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de las ${unidad.plural}.`,
|
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de las ${unidad.plural}.`,
|
||||||
suprimidos, sinDato,
|
suprimidos, sinDato,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// What each count means, for the indicators that don't count the unit of the period.
|
||||||
|
const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
|
||||||
|
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
|
||||||
|
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
|
||||||
|
};
|
||||||
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||||
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
|
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
|
||||||
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
|
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
|
||||||
@@ -132,8 +147,8 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
|||||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
|
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
|
||||||
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
||||||
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||||
}), layout: { ...ejes(data, periodos, suprimidos, tema, unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
||||||
comoLeer: `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
comoLeer: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||||
suprimidos, sinDato,
|
suprimidos, sinDato,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -144,9 +159,31 @@ function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
|
|||||||
}
|
}
|
||||||
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
|
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
|
||||||
// and medians do not, so those two are never stacked.
|
// and medians do not, so those two are never stacked.
|
||||||
export function historicoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura {
|
||||||
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
|
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
|
||||||
: data.contrato === 'C3r' ? mediana(data, tema) : undefined;
|
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined;
|
||||||
if (!figura) throw new Error('Representación no soportada');
|
if (!figura) throw new Error('Representación no soportada');
|
||||||
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||||
}
|
}
|
||||||
|
// The share of cases still in process, from the case-status counts. Cases out of the protocol aren't in the base.
|
||||||
|
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
||||||
|
const periodos = validar(data);
|
||||||
|
const n = (periodo: string, categoria: string) => {
|
||||||
|
const valor = data.filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria)?.['n'];
|
||||||
|
return numero(valor) ? valor : null;
|
||||||
|
};
|
||||||
|
const puntos = periodos.map(periodo => {
|
||||||
|
const proceso = n(periodo, 'EN_PROCESO'), completo = n(periodo, 'COMPLETO');
|
||||||
|
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
|
||||||
|
});
|
||||||
|
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
|
||||||
|
return {
|
||||||
|
contrato: 'C1',
|
||||||
|
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
|
||||||
|
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} casos` : ''),
|
||||||
|
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
|
||||||
|
layout: { ...layout, showlegend: false, margin: { ...(layout.margin as object), b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...(layout.yaxis as object), range: [0, 100], ticksuffix: ' %' } } },
|
||||||
|
comoLeer: 'De los casos completos o en proceso al cierre de cada periodo, el porcentaje que seguía en proceso. Los que quedaron fuera del protocolo no cuentan.',
|
||||||
|
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -28,14 +28,14 @@ describe('Pestaña Histórico', () => {
|
|||||||
http.match(() => true);
|
http.match(() => true);
|
||||||
}
|
}
|
||||||
|
|
||||||
it('CaMa: Resumen, Histórico, Seguimiento y Datos y definiciones, en ese orden', () => {
|
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
|
||||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
|
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
|
||||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||||
});
|
});
|
||||||
it.each(['tea', 'cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
|
it.each(['cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
|
||||||
// Fails if CaMa's tab leaks into the other domains.
|
// Fails if the tab leaks into a domain without enough periods for a history (TEA and CaMa have it).
|
||||||
abrir(domain === 'tea' ? 'cacu' : 'cama', []);
|
abrir('cama', []);
|
||||||
abrir(domain, [item(domain + '_x', 'C2')]);
|
abrir(domain, [item(domain + '_x', 'C2')]);
|
||||||
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||||
expect(root().querySelector('#panel-historico')).toBeNull();
|
expect(root().querySelector('#panel-historico')).toBeNull();
|
||||||
|
|||||||
@@ -1,142 +1,235 @@
|
|||||||
// Covers CaMa's history tab: what it requests and when, the controls (interval, periods to show, custom
|
|
||||||
// periods), the pending panels for indicators the catalog does not publish, and error handling. Responses are
|
|
||||||
// synthetic, shaped like /cama/indicadores/<id>/periodos and /datos.
|
|
||||||
import { Component } from '@angular/core';
|
import { Component } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
|
||||||
import { MatDialog } from '@angular/material/dialog';
|
import { Subject } from 'rxjs';
|
||||||
import { of } from 'rxjs';
|
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { HISTORICO_CAMA, IndicadoresHistorico } from './indicadores-historico';
|
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||||
import { Indicador } from './indicadores.models';
|
import { IndicadoresHistorico } from './indicadores-historico';
|
||||||
|
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||||
|
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||||
|
|
||||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||||
class ChartStub { figure?: { data: { name?: string }[] }; label?: string; }
|
class ChartStub {}
|
||||||
|
const traza = (d: IndicadorDatos, i: number) => historicoFigura(d, 'claro').figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
|
||||||
|
const base = { id: 'i', tipo_periodo: 'mes' as const, periodos: ['2024-03', '2024-01', '2024-02'] };
|
||||||
|
const c1 = (periodo: string, valor: number | null, suprimido = 0) => ({ periodo, suprimido, valor, numerador: valor, denominador: valor === null ? null : 100,
|
||||||
|
ic_bajo: valor === null ? null : valor - 5, ic_alto: valor === null ? null : valor + 5 });
|
||||||
|
const c2 = (periodo: string, categoria: string, n: number | null, orden: number, suprimido = 0) => ({ periodo, categoria, n, orden, suprimido });
|
||||||
|
|
||||||
const MESES = ['2025-01', '2025-02', '2025-03', '2025-04', '2025-05', '2025-06', '2025-07'];
|
describe('Figuras de histórico', () => {
|
||||||
const SEMESTRES = ['2024-S2', '2025-S1'];
|
it('C2 apila conteos en orden cronológico, por categoría y con el color publicado', () => {
|
||||||
const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
const data: IndicadorDatos = { ...base, contrato: 'C2', categorias: { B: { etiqueta: 'Bé <b>', color: '#112233' } }, filas: base.periodos.flatMap(p => [c2(p, 'B', 2, 1), c2(p, 'A', 1, 0)]) };
|
||||||
// What 18080 publishes for CaMa, including biopsias, which the history does not draw.
|
const { figure, suprimidos, sinDato } = historicoFigura(data, 'claro');
|
||||||
const CATALOGO = [item('cama_biopsias', 'C2'), item('cama_birads_456_mastografia', 'C2'), item('cama_birads_456_paciente', 'C2'),
|
expect(figure.layout['barmode']).toBe('stack');
|
||||||
item('cama_confirmacion_birads45', 'C1'), item('cama_dias_toma_diagnostico', 'C3r'), item('cama_eu38a', 'C3r')];
|
expect(figure.data.map(t => t['name'])).toEqual(['A', 'Bé <b>']);
|
||||||
const PUBLICADOS = CATALOGO.filter(i => i.id !== 'cama_biopsias');
|
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024', 'mar 2024']);
|
||||||
|
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Mes y año');
|
||||||
function datos(id: string, contrato: string, tipo: string, periodos: string[]) {
|
expect((figure.data[1]['marker'] as { color: string }).color).toBe('#112233');
|
||||||
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
|
expect(suprimidos).toEqual([]); expect(sinDato).toEqual([]);
|
||||||
const filas = contrato === 'C2'
|
|
||||||
? periodos.flatMap(p => [fila(p, { categoria: 'B5', n: 7, orden: 0 }), fila(p, { categoria: 'B4', n: 5, orden: 1 })])
|
|
||||||
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 50, numerador: 5, denominador: 10, ic_bajo: 30, ic_alto: 70 }))
|
|
||||||
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
|
|
||||||
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' && id.includes('paciente') ? 'paciente' : 'examen', filas,
|
|
||||||
categorias: { B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, B4: { etiqueta: 'B4', color: null } } };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('Histórico de CaMa', () => {
|
|
||||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
|
||||||
const abrirDialogo = vi.fn();
|
|
||||||
function montar(catalog: Indicador[] = CATALOGO, active = false) {
|
|
||||||
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] });
|
|
||||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
|
||||||
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
|
||||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', catalog);
|
|
||||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
|
|
||||||
fixture.detectChanges();
|
|
||||||
}
|
|
||||||
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
|
|
||||||
// Answers in waves, because the shared request queue runs four at a time.
|
|
||||||
function responder(fallo?: (r: TestRequest) => boolean) {
|
|
||||||
const vistos: string[] = [];
|
|
||||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
|
||||||
for (const r of ola) {
|
|
||||||
const url = r.request.url; vistos.push(url + (r.request.params.get('periodos') ? '?' + r.request.params.get('periodos') : ''));
|
|
||||||
const id = url.split('/').at(-2)!, entrada = CATALOGO.find(i => i.id === id)!;
|
|
||||||
if (fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
|
|
||||||
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
|
||||||
else {
|
|
||||||
const periodos = r.request.params.get('periodos')!.split(',');
|
|
||||||
r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fixture.detectChanges();
|
|
||||||
}
|
|
||||||
return vistos;
|
|
||||||
}
|
|
||||||
const root = () => fixture.nativeElement as HTMLElement;
|
|
||||||
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
|
|
||||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
|
||||||
|
|
||||||
it('no pide nada hasta que la pestaña está activa, y entonces solo los indicadores de la lista que el catálogo publica', () => {
|
|
||||||
// Fails if the tab loads data while hidden, or if biopsias (not in the history) is requested.
|
|
||||||
montar();
|
|
||||||
http.expectNone(() => true);
|
|
||||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
|
||||||
const vistos = responder();
|
|
||||||
const ids = new Set(vistos.map(u => u.split('/').at(-2)));
|
|
||||||
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
|
|
||||||
expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false);
|
|
||||||
});
|
});
|
||||||
it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => {
|
it('C2 no dibuja como cero una celda suprimida y sombrea su periodo', () => {
|
||||||
montar(CATALOGO, true); responder();
|
const data: IndicadorDatos = { ...base, contrato: 'C2', filas: [c2('2024-01', 'A', 5, 0), c2('2024-02', 'A', null, 0, 1), c2('2024-03', 'A', 0, 0)] };
|
||||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
const { figure, suprimidos } = historicoFigura(data, 'claro');
|
||||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
expect(figure.data[0]['y']).toEqual([5, null, 0]);
|
||||||
expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
|
expect(suprimidos).toEqual(['feb 2024']);
|
||||||
expect(graficas()).toHaveLength(5);
|
expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]);
|
||||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
|
||||||
});
|
});
|
||||||
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
|
it('C1 es una línea que no cruza huecos y su banda tampoco', () => {
|
||||||
montar(CATALOGO, true); responder();
|
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] };
|
||||||
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
|
const { suprimidos, figure } = historicoFigura(data, 'claro');
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
expect(traza(data, 1).y).toEqual([40, null, 60]);
|
||||||
|
expect(traza(data, 0).x).toEqual(['ene 2024', 'ene 2024', null, 'mar 2024', 'mar 2024']);
|
||||||
|
expect(traza(data, 0).y).toEqual([45, 35, null, 65, 55]);
|
||||||
|
expect(suprimidos).toEqual(['feb 2024']);
|
||||||
|
expect(figure.layout['barmode']).toBeUndefined();
|
||||||
|
expect((figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 100]);
|
||||||
});
|
});
|
||||||
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
|
it('C3r muestra la mediana con la banda entre cuartiles y distingue sin dato de suprimido', () => {
|
||||||
montar(CATALOGO, true); responder();
|
const data: IndicadorDatos = { ...base, periodos: ['2024-01', '2024-02'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
|
||||||
const toggle = fixture.debugElement.query(By.css('mat-button-toggle-group'));
|
const { sinDato, suprimidos } = historicoFigura(data, 'claro');
|
||||||
toggle.triggerEventHandler('change', { value: 'semestre' }); fixture.detectChanges();
|
expect(traza(data, 1).y).toEqual([20, null]);
|
||||||
const semestrales = responder();
|
expect(traza(data, 0).y).toEqual([30, 10]);
|
||||||
expect(semestrales.length).toBeGreaterThan(0);
|
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
|
||||||
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
|
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
|
||||||
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
|
|
||||||
http.expectNone(() => true);
|
|
||||||
});
|
});
|
||||||
it('«Periodos a mostrar» ofrece pasos de cinco y «Todos»; elegir los últimos cinco recorta cada gráfica', () => {
|
it('las líneas usan el verde legible en cada tema', () => {
|
||||||
montar(CATALOGO, true); responder();
|
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
|
||||||
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
|
const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color;
|
||||||
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
|
expect(color('claro')).toBe('#6A8000'); expect(color('oscuro')).toBe('#A8C243');
|
||||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
|
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
|
||||||
});
|
});
|
||||||
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
|
it('escribe los periodos con mes y año', () => {
|
||||||
montar(CATALOGO, true); responder();
|
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
|
||||||
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(['2025-02', '2025-05']) });
|
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
|
||||||
fixture.componentInstance.elegirVentana(-1); fixture.detectChanges();
|
|
||||||
expect(abrirDialogo).toHaveBeenCalledTimes(1);
|
|
||||||
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
|
|
||||||
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
|
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
|
||||||
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
|
|
||||||
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
|
|
||||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
|
||||||
});
|
});
|
||||||
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
|
it('el porcentaje en proceso se calcula sobre completos y en proceso, sin los que quedaron fuera', () => {
|
||||||
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
|
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
|
||||||
montar(CATALOGO, true);
|
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
|
||||||
responder(r => r.request.url.includes('cama_eu38a/periodos'));
|
fila('2024-01', 'COMPLETO', 10), fila('2024-01', 'EN_PROCESO', 30), fila('2024-01', 'FUERA_PROTOCOLO', 99),
|
||||||
const panel = paneles().find(p => p.querySelector('h2')!.textContent === 'Días de la toma de la mastografía a su resultado')!;
|
fila('2024-02', 'COMPLETO', 30), fila('2024-02', 'EN_PROCESO', 10), fila('2024-02', 'FUERA_PROTOCOLO', 99)] }, 'claro');
|
||||||
expect(panel.querySelector('[role=alert]')).not.toBeNull();
|
expect(figure.data[0]['y']).toEqual([75, 25]);
|
||||||
expect(panel.textContent).not.toContain('private');
|
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
|
||||||
expect(graficas()).toHaveLength(4);
|
|
||||||
(panel.querySelector('[role=alert] button') as HTMLButtonElement).click(); fixture.detectChanges();
|
|
||||||
const nuevos = responder();
|
|
||||||
expect(nuevos.length).toBeGreaterThan(0);
|
|
||||||
expect(paneles().some(p => p.querySelector('[role=alert]'))).toBe(false);
|
|
||||||
expect(graficas()).toHaveLength(5);
|
|
||||||
});
|
});
|
||||||
it('sin ningún indicador de la lista en el catálogo no hay paneles ni consultas', () => {
|
it('una escala compartida fija el máximo de las medianas', () => {
|
||||||
montar([item('cama_biopsias', 'C2')], true);
|
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
|
||||||
http.expectNone(() => true);
|
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
|
||||||
expect(paneles()).toHaveLength(0);
|
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
|
||||||
|
});
|
||||||
|
it('M21 y M22 no usan verde en sus líneas', () => {
|
||||||
|
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
|
||||||
|
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
|
||||||
|
});
|
||||||
|
it('rechaza contratos sin representación y filas ambiguas', () => {
|
||||||
|
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
|
||||||
|
expect(() => historicoFigura({ ...base, contrato: 'C1', filas: [c1('2024-01', 1), c1('2024-01', 2)] }, 'claro')).toThrow('ambiguas');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Pestaña Histórico', () => {
|
||||||
|
let http: HttpTestingController;
|
||||||
|
let fixture: ComponentFixture<IndicadoresHistorico>;
|
||||||
|
const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||||
|
const periodos = { id: 'm1', version: '1', periodos: [
|
||||||
|
{ periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
|
||||||
|
{ periodo: '2024-02', tipo: 'mes', report_id: 2, periodo_inicio: '2024-02-01', periodo_fin: '2024-03-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' },
|
||||||
|
{ periodo: '2024-S1', tipo: 'semestre', report_id: 3, periodo_inicio: '2024-01-01', periodo_fin: '2024-07-01', fecha_corte: '2024-08-01', generado_en: '2024-08-01T00:00:00+00:00' },
|
||||||
|
] };
|
||||||
|
const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) });
|
||||||
|
const datosUrl = '/tea/indicadores/m1/datos';
|
||||||
|
const render = () => { TestBed.tick(); fixture.detectChanges(); };
|
||||||
|
const datos_ = (tipo: string, ps: string[]) => datos(tipo, ps);
|
||||||
|
const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); };
|
||||||
|
beforeEach(() => {
|
||||||
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||||
|
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
fixture = TestBed.createComponent(IndicadoresHistorico);
|
||||||
|
fixture.componentRef.setInput('dominio', 'tea');
|
||||||
|
fixture.componentRef.setInput('catalog', catalog);
|
||||||
|
fixture.componentRef.setInput('tema', 'claro');
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
afterEach(() => http.verify());
|
||||||
|
const abrir = () => {
|
||||||
|
fixture.componentRef.setInput('active', true); render();
|
||||||
|
http.expectOne('/tea/indicadores/m1/periodos').flush(periodos);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('no consulta hasta abrir la pestaña y entonces pide todos los periodos de una vez', () => {
|
||||||
|
http.expectNone(() => true);
|
||||||
|
abrir();
|
||||||
|
const request = http.expectOne(r => r.url === datosUrl);
|
||||||
|
expect(request.request.params.get('periodos')!.split(',').sort()).toEqual(['2024-01', '2024-02']);
|
||||||
|
request.flush(datos('mes', ['2024-01', '2024-02'])); render();
|
||||||
|
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a feb 2024 (2 meses)');
|
||||||
|
});
|
||||||
|
it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => {
|
||||||
|
abrir();
|
||||||
|
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
|
||||||
|
fixture.componentInstance.elegido.set('semestre'); render();
|
||||||
|
const semestre = http.expectOne(r => r.url === datosUrl);
|
||||||
|
expect(semestre.request.params.get('periodos')).toBe('2024-S1');
|
||||||
|
semestre.flush(datos('semestre', ['2024-S1'])); render();
|
||||||
|
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)');
|
||||||
|
fixture.componentInstance.elegido.set('mes'); render();
|
||||||
|
fixture.componentRef.setInput('tema', 'oscuro'); render();
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('el selector ofrece pasos de cinco en la unidad elegida y recorta a los periodos más recientes sin consultar', () => {
|
||||||
|
const c = fixture.componentInstance;
|
||||||
|
const meses = Array.from({ length: 12 }, (_, i) => '2024-' + String(i + 1).padStart(2, '0'));
|
||||||
|
const semestres = ['2020-S1', '2020-S2', '2021-S1', '2021-S2', '2022-S1', '2022-S2'];
|
||||||
|
fixture.componentRef.setInput('active', true); render();
|
||||||
|
http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||||
|
http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render();
|
||||||
|
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)', 'Personalizado…']);
|
||||||
|
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)');
|
||||||
|
c.elegirVentana(5); render();
|
||||||
|
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)');
|
||||||
|
http.expectNone(() => true);
|
||||||
|
c.elegido.set('semestre'); render();
|
||||||
|
expect(c.ventana()).toBe(0);
|
||||||
|
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render();
|
||||||
|
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']);
|
||||||
|
c.elegido.set('mes'); render();
|
||||||
|
expect(c.ventana()).toBe(5);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
|
||||||
|
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
|
||||||
|
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
|
||||||
|
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
|
||||||
|
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
|
||||||
|
for (const { id } of items) {
|
||||||
|
const c2 = id.startsWith('M28');
|
||||||
|
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
|
||||||
|
filas: c2 ? [{ periodo: '2024-01', categoria: 'COMPLETO', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'EN_PROCESO', n: 1, orden: 1, suprimido: 0 }]
|
||||||
|
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
|
||||||
|
}
|
||||||
|
render();
|
||||||
|
const paneles = fixture.componentInstance.paneles();
|
||||||
|
expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']);
|
||||||
|
const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||||
|
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
|
||||||
|
});
|
||||||
|
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
|
||||||
|
const c = fixture.componentInstance;
|
||||||
|
const cerrar = new Subject<string[] | undefined>();
|
||||||
|
const abrir = vi.spyOn(TestBed.inject(MatDialog), 'open').mockReturnValue({ afterClosed: () => cerrar } as never);
|
||||||
|
abrir_();
|
||||||
|
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado…');
|
||||||
|
c.elegirVentana(-1);
|
||||||
|
const datos = abrir.mock.calls[0][1]!.data as PeriodosDialogoDatos;
|
||||||
|
expect(datos).toEqual({ tipo: 'mes', periodos: ['2024-01', '2024-02'], elegidos: ['2024-01', '2024-02'] });
|
||||||
|
// Cancelling changes nothing.
|
||||||
|
cerrar.next(undefined); render();
|
||||||
|
expect(c.ventana()).toBe(0);
|
||||||
|
c.elegirVentana(-1);
|
||||||
|
cerrar.next(['2024-02']); render();
|
||||||
|
expect(c.ventana()).toBe(-1);
|
||||||
|
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)');
|
||||||
|
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)');
|
||||||
|
// The other granularity keeps its own choice.
|
||||||
|
c.elegido.set('semestre'); render();
|
||||||
|
expect(c.ventana()).toBe(0);
|
||||||
|
http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render();
|
||||||
|
c.elegido.set('mes'); render();
|
||||||
|
expect(c.ventana()).toBe(-1);
|
||||||
|
http.expectNone(() => true);
|
||||||
|
});
|
||||||
|
it('avisa del error sin perder la pestaña y reintenta', () => {
|
||||||
|
abrir();
|
||||||
|
http.expectOne(r => r.url === datosUrl).flush({}, { status: 500, statusText: 'Error' }); render();
|
||||||
|
expect(fixture.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||||
|
fixture.nativeElement.querySelector('[role="alert"] button').click(); render();
|
||||||
|
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
|
||||||
|
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
|
||||||
|
});
|
||||||
|
it('un indicador sin reportes del intervalo lo dice sin consultar sus datos', () => {
|
||||||
|
fixture.componentRef.setInput('active', true); render();
|
||||||
|
http.expectOne('/tea/indicadores/m1/periodos').flush({ ...periodos, periodos: [periodos.periodos[2]] }); render();
|
||||||
|
http.expectNone(r => r.url === datosUrl);
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Diálogo de periodos de Histórico', () => {
|
||||||
|
it('el diálogo agrupa por año, no aplica sin periodos y devuelve los elegidos en orden', () => {
|
||||||
|
const cierre = vi.fn();
|
||||||
|
TestBed.configureTestingModule({ providers: [{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'mes', periodos: ['2023-12', '2024-01', '2024-02'], elegidos: ['2024-02'] } }, { provide: MatDialogRef, useValue: { close: cierre } }] });
|
||||||
|
const dialogo = TestBed.createComponent(IndicadoresHistoricoPeriodos);
|
||||||
|
dialogo.detectChanges();
|
||||||
|
const root: HTMLElement = dialogo.nativeElement;
|
||||||
|
expect(Array.from(root.querySelectorAll('legend')).map(l => l.textContent)).toEqual(['2023', '2024']);
|
||||||
|
expect(root.textContent).toContain('dic 2023');
|
||||||
|
expect(root.querySelector('.cuenta')!.textContent).toBe('1 mes elegido');
|
||||||
|
const aplicar = Array.from(root.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Aplicar')!;
|
||||||
|
dialogo.componentInstance.elegidos.set([]); dialogo.detectChanges();
|
||||||
|
expect(aplicar.disabled).toBe(true);
|
||||||
|
dialogo.componentInstance.alternar('2024-01'); dialogo.componentInstance.alternar('2023-12'); dialogo.detectChanges();
|
||||||
|
aplicar.click();
|
||||||
|
expect(cierre).toHaveBeenCalledWith(['2023-12', '2024-01']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { MatSelect, MatSelectModule } from '@angular/material/select';
|
|||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
|
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
|
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||||
@@ -17,12 +17,14 @@ import { IndicadoresService } from './indicadores.service';
|
|||||||
|
|
||||||
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
||||||
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
||||||
type Panel = { id: string; titulo: string; rango?: string } & (
|
type Panel = { item: Pick<Indicador, 'id' | 'titulo' | 'contrato'>; rango?: string } & (
|
||||||
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura });
|
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||||
|
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||||
|
const CASOS = 'M28_casos_por_estado';
|
||||||
const PERSONALIZADO = -1;
|
const PERSONALIZADO = -1;
|
||||||
|
|
||||||
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
|
// CaMa's history, in the order of the mockup and with its titles. An indicator the catalog does not publish is
|
||||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
// drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico por categoría BI-RADS' },
|
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico por categoría BI-RADS' },
|
||||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
|
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
|
||||||
@@ -34,6 +36,26 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
|||||||
{ id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' },
|
{ id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||||
|
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
|
||||||
|
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
|
||||||
|
const listos = pasos.every(p => p?.estado === 'listo');
|
||||||
|
return paneles.flatMap((panel): Panel[] => {
|
||||||
|
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
|
||||||
|
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
|
||||||
|
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
|
||||||
|
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
|
||||||
|
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
|
||||||
|
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
|
||||||
|
}
|
||||||
|
if (listos && TIEMPOS.includes(panel.item.id)) return [];
|
||||||
|
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
|
||||||
|
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de casos en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||||
|
}
|
||||||
|
return [panel];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Evolution of each indicator: the granularity and how many of the latest periods to show.
|
// Evolution of each indicator: the granularity and how many of the latest periods to show.
|
||||||
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
||||||
@Component({
|
@Component({
|
||||||
@@ -55,24 +77,34 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
|||||||
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
|
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
|
||||||
</div>
|
</div>
|
||||||
<div class="paneles">
|
<div class="paneles">
|
||||||
@for (panel of paneles(); track panel.id) {
|
@for (panel of paneles(); track panel.item.id) {
|
||||||
<article class="panel" [attr.aria-busy]="panel.estado === 'cargando'">
|
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
||||||
<h2>{{ panel.titulo }}</h2>
|
<h2>{{ panel.item.titulo }}</h2>
|
||||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||||
@switch (panel.estado) {
|
@switch (panel.estado) {
|
||||||
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
|
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
|
||||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.titulo" /> }
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
|
||||||
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
|
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
|
||||||
@case ('error') {
|
@case ('error') {
|
||||||
<div role="alert"><p>{{ panel.mensaje }}</p>
|
<div role="alert"><p>{{ panel.mensaje }}</p>
|
||||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
||||||
}
|
}
|
||||||
@case ('listo') {
|
@case ('listo') {
|
||||||
|
@if (panel.pasos; as pasos) {
|
||||||
|
<div class="pasos">
|
||||||
|
@for (paso of pasos; track paso.titulo) {
|
||||||
|
<section><h3>{{ paso.titulo }}</h3>
|
||||||
|
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||||
[label]="'Histórico de ' + panel.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||||
|
}
|
||||||
<p class="nota">{{ panel.figura.comoLeer }}</p>
|
<p class="nota">{{ panel.figura.comoLeer }}</p>
|
||||||
@if (panel.figura.suprimidos.length) {
|
@if (panel.figura.suprimidos.length) {
|
||||||
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.figura.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
|
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
|
||||||
}
|
}
|
||||||
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
|
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
|
||||||
}
|
}
|
||||||
@@ -86,12 +118,17 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
|||||||
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
|
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
|
||||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||||
|
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
p { margin: var(--issste-space-3) 0 0; }
|
||||||
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||||
|
.panel.ancho { grid-column: 1 / -1; }
|
||||||
|
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||||
|
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||||
|
h3 { margin: 0; font: var(--mat-sys-title-small); }
|
||||||
mat-form-field { min-width: 18rem; }
|
mat-form-field { min-width: 18rem; }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
@@ -100,10 +137,8 @@ export class IndicadoresHistorico {
|
|||||||
readonly catalog = input.required<readonly Indicador[]>();
|
readonly catalog = input.required<readonly Indicador[]>();
|
||||||
readonly tema = input.required<Tema>();
|
readonly tema = input.required<Tema>();
|
||||||
readonly active = input(false);
|
readonly active = input(false);
|
||||||
// The indicators of the list the catalog publishes.
|
|
||||||
private readonly publicados = computed(() => HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)));
|
|
||||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
|
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.catalog().some(item => item.tipos_periodo.includes(tipo))));
|
||||||
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
|
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
|
||||||
readonly tipo = computed<TipoPeriodo>(() => {
|
readonly tipo = computed<TipoPeriodo>(() => {
|
||||||
const elegido = this.elegido(), tipos = this.tipos();
|
const elegido = this.elegido(), tipos = this.tipos();
|
||||||
@@ -123,7 +158,7 @@ export class IndicadoresHistorico {
|
|||||||
// The periods on screen, out of those an indicator publishes.
|
// The periods on screen, out of those an indicator publishes.
|
||||||
private recortar(periodos: readonly string[]) {
|
private recortar(periodos: readonly string[]) {
|
||||||
const orden = cronologico(periodos), ventana = this.ventana();
|
const orden = cronologico(periodos), ventana = this.ventana();
|
||||||
if (ventana !== PERSONALIZADO) return ventana ? orden.slice(-ventana) : orden;
|
if (ventana !== PERSONALIZADO) return orden.slice(-ventana);
|
||||||
const elegidos = this.personalizados()[this.tipo()] ?? [];
|
const elegidos = this.personalizados()[this.tipo()] ?? [];
|
||||||
return orden.filter(p => elegidos.includes(p));
|
return orden.filter(p => elegidos.includes(p));
|
||||||
}
|
}
|
||||||
@@ -146,27 +181,43 @@ export class IndicadoresHistorico {
|
|||||||
});
|
});
|
||||||
readonly paneles = computed<Panel[]>(() => {
|
readonly paneles = computed<Panel[]>(() => {
|
||||||
const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema();
|
const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema();
|
||||||
if (!this.publicados().length) return [];
|
// Top of the shared scale: the highest third quartile of the steps, in the periods on screen.
|
||||||
return HISTORICO_CAMA.map((entrada): Panel => {
|
const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => {
|
||||||
const item = this.catalog().find(i => i.id === entrada.id);
|
const carga = cargas?.[id];
|
||||||
if (!item) return { ...entrada, estado: 'pendiente' };
|
if (carga?.estado !== 'listo') return [];
|
||||||
if (!item.tipos_periodo.includes(tipo)) return { ...entrada, estado: 'vacio' };
|
const visibles = this.recortar(carga.datos.periodos);
|
||||||
|
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
|
||||||
|
})) * 1.05;
|
||||||
|
const base: (Panel & { datos?: IndicadorDatos })[] = this.elementos(tipo).map((item): Panel & { datos?: IndicadorDatos } => {
|
||||||
|
if (!item.tipos_periodo.length) return { item, estado: 'pendiente' };
|
||||||
const carga = cargas?.[item.id];
|
const carga = cargas?.[item.id];
|
||||||
if (!carga) return { ...entrada, estado: 'cargando' };
|
if (!carga) return { item, estado: 'cargando' };
|
||||||
if (carga.estado !== 'listo') return { ...entrada, ...carga };
|
if (carga.estado !== 'listo') return { item, ...carga };
|
||||||
const periodos = this.recortar(carga.datos.periodos);
|
const periodos = this.recortar(carga.datos.periodos);
|
||||||
if (!periodos.length) return { ...entrada, estado: 'vacio' };
|
if (!periodos.length) return { item, estado: 'vacio' };
|
||||||
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
|
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
|
||||||
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
|
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
|
||||||
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
|
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
|
||||||
try {
|
try {
|
||||||
return { ...entrada, rango, estado: 'listo', figura: historicoFigura(datos, tema) };
|
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { ...entrada, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
return agrupar(base, tema);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// What the tab draws: CaMa's fixed list, with pending panels where the catalog lacks the indicator; the catalog elsewhere.
|
||||||
|
private elementos(tipo: TipoPeriodo): Indicador[] {
|
||||||
|
const catalogo = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||||
|
// Without a catalog there is nothing to say is missing.
|
||||||
|
if (this.dominio() !== 'cama' || !this.catalog().length) return catalogo;
|
||||||
|
return HISTORICO_CAMA.flatMap(({ id, titulo }) => {
|
||||||
|
const item = this.catalog().find(i => i.id === id);
|
||||||
|
if (!item) return [{ id, titulo, contrato: '', figuras: [], tipos_periodo: [] }];
|
||||||
|
return item.tipos_periodo.includes(tipo) ? [{ ...item, titulo }] : [];
|
||||||
|
});
|
||||||
|
}
|
||||||
constructor() {
|
constructor() {
|
||||||
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
|
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
|
||||||
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
|
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
|
||||||
@@ -174,10 +225,10 @@ export class IndicadoresHistorico {
|
|||||||
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
|
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
|
||||||
});
|
});
|
||||||
effect(() => {
|
effect(() => {
|
||||||
const tipo = this.tipo(), items = this.publicados();
|
const tipo = this.tipo(), items = this.catalog();
|
||||||
if (!this.active() || !items.length) return;
|
if (!this.active() || !items.length) return;
|
||||||
untracked(() => {
|
untracked(() => {
|
||||||
if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; }
|
if (this.catalogoCargado !== items) { this.catalogoCargado = items; this.cargas.set({}); this.solicitada = undefined; }
|
||||||
if (this.cargas()[tipo] || this.solicitada === tipo) return;
|
if (this.cargas()[tipo] || this.solicitada === tipo) return;
|
||||||
this.solicitada = tipo;
|
this.solicitada = tipo;
|
||||||
this.solicitudes.next({ tipo, items });
|
this.solicitudes.next({ tipo, items });
|
||||||
@@ -199,7 +250,7 @@ export class IndicadoresHistorico {
|
|||||||
abrirPersonalizado() {
|
abrirPersonalizado() {
|
||||||
const tipo = this.tipo(), periodos = this.disponibles();
|
const tipo = this.tipo(), periodos = this.disponibles();
|
||||||
// Starts from what's on screen, so the user only adjusts it.
|
// Starts from what's on screen, so the user only adjusts it.
|
||||||
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos;
|
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : periodos.slice(-this.ventana());
|
||||||
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
|
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
|
||||||
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
|
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
|
||||||
.afterClosed().subscribe(resultado => {
|
.afterClosed().subscribe(resultado => {
|
||||||
@@ -215,6 +266,6 @@ export class IndicadoresHistorico {
|
|||||||
const tipo = this.tipo();
|
const tipo = this.tipo();
|
||||||
this.solicitada = tipo;
|
this.solicitada = tipo;
|
||||||
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
|
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
|
||||||
this.solicitudes.next({ tipo, items: this.publicados() });
|
this.solicitudes.next({ tipo, items: this.catalog() });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,10 +16,13 @@ import { Indicador } from './indicadores.models';
|
|||||||
|
|
||||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||||
class ChartStub {}
|
class ChartStub {}
|
||||||
|
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
|
||||||
|
// rules (indicador-kpi-panel.spec.ts covers all four).
|
||||||
|
const KPIS = { ...KPI_BY_DOMAIN, cama: KPI_BY_DOMAIN.cama.slice(0, 3) };
|
||||||
describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => {
|
describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => {
|
||||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage;
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage;
|
||||||
const periods = ['2026-S2', '2026-S1', '2025-S2'];
|
const periods = ['2026-S2', '2026-S1', '2025-S2'];
|
||||||
const definitions = KPI_BY_DOMAIN[domain];
|
const definitions = KPIS[domain];
|
||||||
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
|
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'] })),
|
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
|
||||||
// Two figures, so every domain keeps an ordinary card whose representation can change.
|
// Two figures, so every domain keeps an ordinary card whose representation can change.
|
||||||
@@ -33,14 +36,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
|||||||
http = TestBed.inject(HttpTestingController);
|
http = TestBed.inject(HttpTestingController);
|
||||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
||||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||||
// The anchor shares the catalog inventory request. The inventory runs four requests at a time,
|
// The anchor shares the catalog inventory request; availability runs four at a time.
|
||||||
// so a catalog of more than four indicators is answered in waves.
|
expect(flushPeriodos(() => [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })))).toBe(items.length);
|
||||||
let inventoried = 0;
|
|
||||||
for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) {
|
|
||||||
inventoried += wave.length;
|
|
||||||
wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
|
|
||||||
}
|
|
||||||
expect(inventoried).toBe(items.length);
|
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
});
|
});
|
||||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||||
@@ -50,6 +47,13 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
|||||||
periodo: period, grupo: d.contrato === 'C1' && 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' }] };
|
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
|
||||||
}
|
}
|
||||||
|
function flushPeriodos(periodos: () => unknown[]) {
|
||||||
|
let flushed = 0;
|
||||||
|
for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos'))) {
|
||||||
|
pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() })); flushed += pending.length;
|
||||||
|
}
|
||||||
|
return flushed;
|
||||||
|
}
|
||||||
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
|
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
|
||||||
// Regression assertions below target the original KPI contracts. The added lab
|
// Regression assertions below target the original KPI contracts. The added lab
|
||||||
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
// consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts.
|
||||||
@@ -65,11 +69,15 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
|||||||
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 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 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 editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||||
|
// The shared request queue runs four at a time: flushing a batch starts the next.
|
||||||
function flushPanels(period: string, expected = definitions.length - 1) {
|
function flushPanels(period: string, expected = definitions.length - 1) {
|
||||||
const requests = originalRequests();
|
let flushed = 0;
|
||||||
expect(requests).toHaveLength(expected);
|
for (let requests = originalRequests(); requests.length; requests = originalRequests()) {
|
||||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
|
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)); });
|
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
|
||||||
|
flushed += requests.length;
|
||||||
|
}
|
||||||
|
expect(flushed).toBe(expected);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
}
|
}
|
||||||
function choose() {
|
function choose() {
|
||||||
@@ -141,12 +149,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
|||||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
|
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);
|
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', () => {
|
it('aplicación manual posterior prevalece sin repetir la búsqueda', () => {
|
||||||
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
|
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
|
||||||
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
|
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
|
||||||
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
|
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
|
||||||
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
|
expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
|
||||||
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
|
|
||||||
});
|
});
|
||||||
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
|
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
|
||||||
choose(); const applied = page.filters!.applied;
|
choose(); const applied = page.filters!.applied;
|
||||||
@@ -220,13 +227,13 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
|||||||
const catalogs = new Map<string, typeof items>([[domain, items]]);
|
const catalogs = new Map<string, typeof items>([[domain, items]]);
|
||||||
for (const target of ['tea', 'cacu', 'cama'] as const) {
|
for (const target of ['tea', 'cacu', 'cama'] as const) {
|
||||||
if (target === domain) continue;
|
if (target === domain) continue;
|
||||||
const definitions = KPI_BY_DOMAIN[target];
|
const definitions = KPIS[target];
|
||||||
const period = own.size === 1 ? '2024-S2' : '2025-S1';
|
const period = own.size === 1 ? '2024-S2' : '2025-S1';
|
||||||
own.set(target, period);
|
own.set(target, period);
|
||||||
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
|
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
|
||||||
catalogs.set(target, catalog);
|
catalogs.set(target, catalog);
|
||||||
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges();
|
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' }] }));
|
flushPeriodos(() => [{ periodo: period, tipo: 'semestre' }]);
|
||||||
const payload = (index: number) => {
|
const payload = (index: number) => {
|
||||||
const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato;
|
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;
|
value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { TestBed } from '@angular/core/testing';
|
|||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
|
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
|
||||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
import { CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||||
import { AvailablePeriod } from './indicadores-periodos';
|
import { AvailablePeriod } from './indicadores-periodos';
|
||||||
import { TipoPeriodo } from './indicadores.models';
|
import { TipoPeriodo } from './indicadores.models';
|
||||||
|
|
||||||
@@ -48,7 +48,9 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
|
|||||||
if (domain === 'cama') {
|
if (domain === 'cama') {
|
||||||
expect(anchor.id).toBe('cama_birads_456_paciente');
|
expect(anchor.id).toBe('cama_birads_456_paciente');
|
||||||
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
|
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
|
||||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
|
// The strip's other cards are pending until the kit publishes them, so the anchor stays the patients' count.
|
||||||
|
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_tasa_deteccion_histopatologica',
|
||||||
|
'cama_eu38a', 'cama_dias_resultado_diagnostico']);
|
||||||
} else expect(anchor.id).toBe('cacu_eu7');
|
} else expect(anchor.id).toBe('cacu_eu7');
|
||||||
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
|
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
|
||||||
expect(run.selected()?.periodo).toBe(periods[0]);
|
expect(run.selected()?.periodo).toBe(periods[0]);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi';
|
import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||||
import { IndicadorDatos } from './indicadores.models';
|
import { IndicadorDatos } from './indicadores.models';
|
||||||
|
|
||||||
// /cama/indicadores/<id>/datos?periodos=2025-S2 as WebApi served it (oct 2026) over a CaMa base
|
// /cama/indicadores/<id>/datos?periodos=2025-S2 as WebApi served it (oct 2026) over a CaMa base
|
||||||
@@ -129,11 +129,15 @@ const DATOS_2025_S2: Record<string, IndicadorDatos> = {
|
|||||||
|
|
||||||
describe('KPI de CaMa con respuestas reales de WebApi', () => {
|
describe('KPI de CaMa con respuestas reales de WebApi', () => {
|
||||||
const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 };
|
const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 };
|
||||||
// The two cards CaMa's summary no longer draws; their real responses still have to read correctly (the history charts use them).
|
// The card of each real answer; confirmación and tamizaje a diagnóstico are no longer cards, so theirs is
|
||||||
const confirmacion: KpiDefinition = { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' };
|
// built from the answer, to keep checking the C1 and C3r rules on real data.
|
||||||
const tomaDiagnostico: KpiDefinition = { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' };
|
const ids = Object.keys(DATOS_2025_S2);
|
||||||
const definitions = [KPI_BY_DOMAIN.cama[0], confirmacion, tomaDiagnostico];
|
const result = (index: number) => {
|
||||||
const result = (index: number) => kpiResult(DATOS_2025_S2[definitions[index].id], definitions[index], 'cama', applied);
|
const data = DATOS_2025_S2[ids[index]];
|
||||||
|
const definition = KPI_BY_DOMAIN.cama.find(d => d.id === ids[index])
|
||||||
|
?? { id: data.id, title: data.id, contrato: data.contrato as 'C1' | 'C3r', unit: '' };
|
||||||
|
return kpiResult(data, definition, 'cama', applied);
|
||||||
|
};
|
||||||
|
|
||||||
it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => {
|
it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => {
|
||||||
expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 }));
|
expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 }));
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI, KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi';
|
import { CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi';
|
||||||
import { GlobalApplied } from './indicadores-memory';
|
import { GlobalApplied } from './indicadores-memory';
|
||||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
||||||
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 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.
|
// Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI.
|
||||||
// CaMa's C1 and C3r cards are the opportunity ones the catalog may not publish yet; the contract rules are the same.
|
|
||||||
const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0],
|
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]],
|
{ id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]],
|
||||||
cama: [KPI_BY_DOMAIN.cama[0], CAMA_TASA_DETECCION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI] };
|
// One card of each contract, in the C2, C1, C3r order the tests index by: CaMa's opportunity strip, pending cards included.
|
||||||
|
cama: CAMA_OPORTUNIDAD_KPIS.slice(0, 3) };
|
||||||
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
|
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
|
||||||
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 };
|
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 };
|
||||||
}
|
}
|
||||||
@@ -57,12 +57,16 @@ it('categorías incompletas nunca producen un total parcial', () => {
|
|||||||
expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined();
|
expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('TEA usa sus tres indicadores destacados y su grupo C1 es TOTAL', () => {
|
it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
|
||||||
expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([
|
expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([
|
||||||
['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r']]);
|
['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r'],
|
||||||
|
['M21_diagnosticados_con_eeg', 'C1'], ['M22_diagnosticados_sin_eeg', 'C1']]);
|
||||||
|
const eeg = data('tea', 3, [{ ...total, grupo: 'TOTAL', valor: 62.3, numerador: 71, denominador: 114 }]);
|
||||||
|
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con TEA positivo tienen un EEG ligado.');
|
||||||
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
|
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
|
||||||
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
|
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
|
||||||
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
|
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
|
||||||
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
|
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
|
||||||
.toBe('Selección no consolidable');
|
.toBe('Selección no consolidable');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -34,11 +34,21 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
|||||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
// 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
|
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||||
// cards read the `titulo` that the API already sends.
|
// cards read the `titulo` that the API already sends.
|
||||||
|
// What only TEA's summary paragraph needs: case status and the time of each screening step.
|
||||||
|
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||||
|
{ id: 'M28_casos_por_estado', title: 'Casos iniciados', contrato: 'C2', unit: 'casos' },
|
||||||
|
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
|
||||||
|
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||||
|
];
|
||||||
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||||
tea: [
|
tea: [
|
||||||
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
|
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
|
||||||
{ id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' },
|
{ id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' },
|
||||||
{ id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' },
|
{ id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' },
|
||||||
|
{ id: 'M21_diagnosticados_con_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unit: '%',
|
||||||
|
c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo tienen un EEG ligado.` },
|
||||||
|
{ id: 'M22_diagnosticados_sin_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1', unit: '%',
|
||||||
|
c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo no tienen ningún EEG ligado.` },
|
||||||
],
|
],
|
||||||
cacu: [
|
cacu: [
|
||||||
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
{ id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
||||||
@@ -85,7 +95,7 @@ const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> =
|
|||||||
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
|
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.`,
|
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[]; }
|
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; }
|
||||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||||
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
|
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
|
||||||
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
||||||
@@ -120,7 +130,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
|||||||
if (!rows.every(row => count(row['n']))) return empty;
|
if (!rows.every(row => count(row['n']))) return empty;
|
||||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||||
if (!count(value)) return empty;
|
if (!count(value)) return empty;
|
||||||
return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
||||||
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
||||||
}
|
}
|
||||||
if (definition.contrato === 'C1') {
|
if (definition.contrato === 'C1') {
|
||||||
|
|||||||
@@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason:
|
|||||||
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
|
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 (!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 (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
|
||||||
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de tiempo ' + applied.tipo + ' del filtro general.' };
|
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de análisis ' + (applied.tipo === 'mes' ? 'mensual' : 'semestral') + ' del filtro general.' };
|
||||||
const mode = applied.selection.mode;
|
const mode = applied.selection.mode;
|
||||||
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
|
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
|
||||||
? 'Todos con reporte requiere semestre como primer intervalo de tiempo publicado. Para meses elige periodos explícitos.'
|
? 'Todos con reporte requiere semestre como primer intervalo de análisis publicado. Para meses elige un periodo.'
|
||||||
: 'Los periodos del filtro general no son válidos para este intervalo de tiempo.' };
|
: 'Los periodos del filtro general no son válidos para este intervalo de análisis.' };
|
||||||
return { compatible: true };
|
return { compatible: true };
|
||||||
}
|
}
|
||||||
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
||||||
|
|||||||
@@ -1,433 +0,0 @@
|
|||||||
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')); }
|
|
||||||
|
|
||||||
// CaMa follows the mockup and has no floating navigation (indicadores-cama-resumen-clinico.spec.ts).
|
|
||||||
it.each(['tea', 'cacu'] 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, 'cacu');
|
|
||||||
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('cacu', '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('cacu');
|
|
||||||
http.expectOne('/cacu/indicadores').flush([item('b', 'CaCu')]); 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');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
: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; }
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
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,8 +44,8 @@ describe('UX-04 navegación Angular', () => {
|
|||||||
const harness = await setup();
|
const harness = await setup();
|
||||||
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||||
load(domain, harness); harness.detectChanges();
|
load(domain, harness); harness.detectChanges();
|
||||||
// The domain links are in the shell's header selector (app-encabezado.spec.ts); the page has none of its own.
|
// Domain switching lives in the App header (app.spec.ts); the page must not add a second one.
|
||||||
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav')).toHaveLength(0);
|
expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(0);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
|
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
|
||||||
@@ -53,7 +53,7 @@ describe('UX-04 navegación Angular', () => {
|
|||||||
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||||
load('tea', harness); harness.detectChanges();
|
load('tea', harness); harness.detectChanges();
|
||||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||||
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
|
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
|
||||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||||
control.year = '2025'; control.unit = 'S2'; control.add();
|
control.year = '2025'; control.unit = 'S2'; control.add();
|
||||||
@@ -62,7 +62,7 @@ describe('UX-04 navegación Angular', () => {
|
|||||||
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||||
const req = load('tea', harness);
|
const req = load('tea', harness);
|
||||||
expect(req.request.params.get('periodos')).toBe('2025-S1');
|
expect(req.request.params.get('periodos')).toBe('2025-S1');
|
||||||
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
|
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] });
|
||||||
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
||||||
});
|
});
|
||||||
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
|
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<section class="dashboard" aria-labelledby="dashboard-title">
|
<section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||||
<header>
|
<header>
|
||||||
@if (fichaPacienteAbierta()) {
|
@if (fichaPacienteAbierta()) {
|
||||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||||
<p>Consulta individual de seguimiento de cáncer cervicouterino</p>
|
<p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
|
||||||
} @else {
|
} @else {
|
||||||
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
|
<span class="domain">{{ domainTitles[dominio] }}, investigación</span>
|
||||||
<h1 id="dashboard-title">Indicadores</h1>
|
<h1 id="dashboard-title">Indicadores</h1>
|
||||||
@@ -18,33 +18,12 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</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'">
|
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
|
||||||
@if (!catalogLoading() && filters; as state) {
|
@if (!catalogLoading() && filters; as state) {
|
||||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
<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>
|
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
|
||||||
<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.' : dominio === 'cama' ? 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
|
<p class="section-description">{{ dominio === 'tea' ? 'Se aplica a las figuras y los indicadores destacados.' : 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' }}</p>
|
||||||
<app-indicador-period-filters [state]="state" [compact]="dominio === 'cama'" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
<app-indicador-period-filters [state]="state" [compact]="dominio === 'cama'" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
|
||||||
(retryAvailability)="retryAvailability()"
|
(retryAvailability)="retryAvailability()"
|
||||||
(edited)="editFilters()" (apply)="applyFilters()" />
|
(edited)="editFilters()" (apply)="applyFilters()" />
|
||||||
@@ -68,8 +47,11 @@
|
|||||||
@let kpis = kpiCards;
|
@let kpis = kpiCards;
|
||||||
@if (kpis.length && !initialPeriodBlocked) {
|
@if (kpis.length && !initialPeriodBlocked) {
|
||||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
|
@let resumen = teaResumenPeriodo;
|
||||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
<h2 id="kpi-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||||
|
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||||
|
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||||
|
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||||
@for (card of kpis; track dominio + ':' + card.definition.id) {
|
@for (card of kpis; track dominio + ':' + card.definition.id) {
|
||||||
@if (card.pending) {
|
@if (card.pending) {
|
||||||
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
||||||
@@ -89,9 +71,9 @@
|
|||||||
|
|
||||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||||
<div class="catalog-heading">
|
<div class="catalog-heading">
|
||||||
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
<h2 id="graphic-section-title" class="section-title">{{ dominio !== 'tea' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
||||||
@if (!catalogLoading() && !catalogError() && catalog().length) {
|
@if (!catalogLoading() && !catalogError() && catalog().length) {
|
||||||
<p class="catalog-count" role="status">{{ shownIndicators }} {{ shownIndicators === 1 ? 'indicador publicado' : 'indicadores publicados' }}</p>
|
<p class="catalog-count" role="status">{{ catalogOrder().length }} {{ catalogOrder().length === 1 ? 'indicador publicado' : 'indicadores publicados' }}</p>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
@if (catalogLoading()) {
|
@if (catalogLoading()) {
|
||||||
@@ -108,28 +90,35 @@
|
|||||||
<div class="catalog-search">
|
<div class="catalog-search">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
<mat-label>Buscar indicadores</mat-label>
|
<mat-label>Buscar indicadores</mat-label>
|
||||||
<input #searchInput matInput type="search" [ngModel]="searchQuery()" (ngModelChange)="changeSearchQuery($event)"
|
<mat-select #indicatorSelect multiple panelClass="indicator-select-panel" [ngModel]="selectedIndicators()" (ngModelChange)="changeIndicatorSelection($event)" aria-describedby="catalog-search-result">
|
||||||
placeholder="Título o identificador" aria-describedby="catalog-search-help catalog-search-result" />
|
<mat-select-trigger><span class="select-value">{{ selectionSummary() }}</span></mat-select-trigger>
|
||||||
<button mat-icon-button matIconSuffix type="button" (click)="clearSearch()" [disabled]="!searchQuery()"
|
@for (item of catalogOrder(); track item.id) {
|
||||||
aria-label="Limpiar búsqueda"><mat-icon aria-hidden="true">close</mat-icon></button>
|
<mat-option [value]="item.id"><span class="option-row"><span class="option-title">{{ item.titulo }}</span>
|
||||||
<mat-hint id="catalog-search-help">Las coincidencias aparecen primero; todos los indicadores siguen visibles.</mat-hint>
|
<a class="option-go" [href]="'#' + cardElementId(item)" (click)="goToIndicator(item.id, $event)"
|
||||||
|
[attr.aria-label]="'Ir a ' + item.titulo">Ir</a></span></mat-option>
|
||||||
|
}
|
||||||
|
</mat-select>
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
|
<button mat-stroked-button type="button" (click)="showAllIndicators()" [disabled]="indicatorSelection() === null">Mostrar todos</button>
|
||||||
</div>
|
</div>
|
||||||
<p id="catalog-search-result" class="search-result">
|
<p id="catalog-search-result" class="search-result" role="status">
|
||||||
@if (searchResults().active) {
|
Mostrando {{ searchResults().items.length }} de {{ catalogOrder().length }} indicadores.
|
||||||
@if (searchResults().count) {
|
|
||||||
{{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles.
|
|
||||||
} @else {
|
|
||||||
No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</p>
|
</p>
|
||||||
}
|
}
|
||||||
|
@if (!searchResults().items.length) {
|
||||||
|
<p class="state" role="status">No hay indicadores seleccionados. Elige al menos uno en «Buscar indicadores».</p>
|
||||||
|
}
|
||||||
|
@if (dominio === 'tea') {
|
||||||
|
<div class="reporte-acciones">
|
||||||
|
<button mat-stroked-button type="button" [disabled]="preparandoReporte()" (click)="descargarReporte()">{{ preparandoReporte() ? 'Preparando reporte…' : 'Descargar reporte' }}</button>
|
||||||
|
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
<div class="catalog-grid">
|
<div class="catalog-grid">
|
||||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
<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)" />
|
[pinned]="isPinned(item)" [fijable]="searchVisible()" (pinChanged)="togglePinned(item)" />
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@@ -142,8 +131,14 @@
|
|||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@if (conAnalisis) {
|
||||||
|
<section id="panel-analisis" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-analisis" tabindex="0" [hidden]="activeSection() !== 'analisis'">
|
||||||
|
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" (verPacientes)="verPacientes($event)" />
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
<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'">
|
<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'"
|
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'" [seleccion]="seleccionSeguimiento()"
|
||||||
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
|
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|||||||
@@ -17,16 +17,18 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
|||||||
.kpi-section, .graphic-section { min-width: 0; }
|
.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); }
|
.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); }
|
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||||
|
// Every card of a row of cards is as tall as the tallest one.
|
||||||
|
.kpi-grid { grid-auto-rows: 1fr; }
|
||||||
|
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
|
||||||
.catalog-grid { align-items: stretch; }
|
.catalog-grid { align-items: stretch; }
|
||||||
|
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
|
||||||
|
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||||
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
|
.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-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
|
||||||
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||||
.catalog-search { display: flex; justify-content: flex-end; margin-top: var(--issste-space-4); }
|
.catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); }
|
||||||
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
|
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
|
||||||
.catalog-search button { width: 48px; height: 48px; }
|
.catalog-search button { min-height: 48px; }
|
||||||
.catalog-search button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: -3px; }
|
|
||||||
// Keep search semantics; Material supplies the single accessible clear control.
|
|
||||||
.catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
|
|
||||||
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right;
|
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right;
|
||||||
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
||||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||||
@@ -36,7 +38,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
|||||||
h1 { font-size: 1.5rem; }
|
h1 { font-size: 1.5rem; }
|
||||||
}
|
}
|
||||||
|
|
||||||
.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; }
|
.global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||||
|
.global-filters .section-title { font-size: 1rem; }
|
||||||
|
.global-filters .section-description { margin: var(--issste-space-1) 0 var(--issste-space-2); font: var(--mat-sys-body-small); }
|
||||||
|
|
||||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||||
|
|
||||||
@@ -49,6 +53,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
|||||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
}
|
}
|
||||||
|
// Cáncer de mama's four cards: one size, four in a row on wide screens and two by two below.
|
||||||
|
@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
|
@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
|
||||||
|
|
||||||
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
|
.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);
|
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
|
||||||
@@ -67,8 +74,3 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
|||||||
.section-panel { padding-block: var(--issste-space-6); }
|
.section-panel { padding-block: var(--issste-space-6); }
|
||||||
.section-panel[hidden] { display: none; }
|
.section-panel[hidden] { display: none; }
|
||||||
@media (max-width: 550px) { .section-tabs button { flex: 1 1 auto; padding-inline: .65rem; } }
|
@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; }
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -55,15 +55,15 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
|
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
|
||||||
load();
|
load();
|
||||||
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
|
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
|
||||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
|
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.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.textContent).toContain('Consulta individual de seguimiento de TEA');
|
||||||
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
|
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
|
||||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
|
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
|
||||||
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
|
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.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
|
||||||
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(3);
|
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
|
||||||
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
|
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
|
||||||
expect(page.activeSection()).toBe('resumen');
|
expect(page.activeSection()).toBe('resumen');
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
@@ -101,22 +101,29 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true);
|
expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => {
|
it('D.3.A muestra identidad y skeleton sin control de expansión ni HTTP', () => {
|
||||||
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
|
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
|
||||||
expect(host.querySelector('h2').textContent).toBe('Uno');
|
expect(host.querySelector('h2').textContent).toBe('Uno');
|
||||||
expect(host.querySelector('header button')).toBeNull();
|
expect(host.querySelector('header button')).toBeNull();
|
||||||
expect(host.querySelector('mat-select')).toBeTruthy();
|
expect(host.querySelector('mat-select')).toBeNull();
|
||||||
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
|
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
|
||||||
expect(host.textContent).not.toContain('Contrato C1');
|
expect(host.textContent).not.toContain('Contrato C1');
|
||||||
expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
|
expect(host.textContent).not.toContain('figuras publicadas');
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
|
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
|
||||||
|
load([item, { ...second, vistas: ['historico'] }]);
|
||||||
|
expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]);
|
||||||
|
expect(fixture.nativeElement.querySelector('.catalog-count').textContent).toContain('1 indicador publicado');
|
||||||
|
expect(page.catalog()).toHaveLength(2);
|
||||||
|
http.expectNone(r => r.url.endsWith('/figuras/f1'));
|
||||||
|
});
|
||||||
it('D.3.A conserva encabezado y contenido al salir del viewport', () => {
|
it('D.3.A conserva encabezado y contenido al salir del viewport', () => {
|
||||||
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
|
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
|
||||||
const header = host.querySelector('header'); toggle(); flushAll();
|
const header = host.querySelector('header'); toggle(); flushAll();
|
||||||
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
|
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
|
||||||
expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel);
|
expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel);
|
||||||
expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true);
|
expect(host.querySelector('.catalog-content')).toBeTruthy(); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('UX-06C: conserva título largo completo y el control separado de la identidad', () => {
|
it('UX-06C: conserva título largo completo y el control separado de la identidad', () => {
|
||||||
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
|
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
|
||||||
@@ -125,14 +132,14 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
expect(header.querySelector('h2')?.textContent).toBe(title);
|
expect(header.querySelector('h2')?.textContent).toBe(title);
|
||||||
expect(header.querySelector('.card-identity button')).toBeNull();
|
expect(header.querySelector('.card-identity button')).toBeNull();
|
||||||
expect(header.querySelector('button')).toBeNull();
|
expect(header.querySelector('button')).toBeNull();
|
||||||
expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title);
|
// Two cards: no pin button (it shows from MIN_BUSQUEDA indicators, see indicadores-pinning.spec.ts).
|
||||||
|
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('UX-06B la navegación entre dominios es la del encabezado: la página no la duplica', () => {
|
it('UX-06B mantiene una sola navegación entre dominios, sin duplicar botones', () => {
|
||||||
// The selector is in the shell's header (app-encabezado.spec.ts); a second set of buttons on the page would duplicate it.
|
// The App header owns the domain menu (app.spec.ts); fails if the page brings back its own links.
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(0);
|
expect(fixture.nativeElement.querySelectorAll('nav.domain-nav')).toHaveLength(0);
|
||||||
expect(fixture.nativeElement.querySelectorAll('a[href^="/indicadores/"]')).toHaveLength(0);
|
|
||||||
expect(cards()).toHaveLength(0);
|
expect(cards()).toHaveLength(0);
|
||||||
// Constructing the page legitimately initializes its domain catalog.
|
// Constructing the page legitimately initializes its domain catalog.
|
||||||
const catalogRequest = http.expectOne('/tea/indicadores');
|
const catalogRequest = http.expectOne('/tea/indicadores');
|
||||||
@@ -202,7 +209,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
|
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
|
||||||
load([item]); toggle(); flushAll(); const a = control();
|
load([item]); toggle(); flushAll(); const a = control();
|
||||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||||
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
a.select([]); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||||
page.applyFilters(); fixture.detectChanges();
|
page.applyFilters(); fixture.detectChanges();
|
||||||
const appliedA = request('f1');
|
const appliedA = request('f1');
|
||||||
expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
|
expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
|
||||||
@@ -210,14 +217,14 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
page.changeTema('oscuro'); fixture.detectChanges();
|
page.changeTema('oscuro'); fixture.detectChanges();
|
||||||
const themedA = request('f1');
|
const themedA = request('f1');
|
||||||
expect(themedA.request.params.get('periodos')).toBe('2025-S1');
|
expect(themedA.request.params.get('periodos')).toBe('2025-S1');
|
||||||
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S2']);
|
||||||
themedA.flush({ data: [], layout: {} });
|
themedA.flush({ data: [], layout: {} });
|
||||||
});
|
});
|
||||||
it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => {
|
it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => {
|
||||||
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
|
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
|
||||||
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||||
const filters = control();
|
const filters = control();
|
||||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||||
const result = panel.result();
|
const result = panel.result();
|
||||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||||
@@ -235,10 +242,10 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => {
|
it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => {
|
||||||
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
|
load([item]); toggle(); flushAll(); const a = control(); a.select([]); a.year = '2025'; a.unit = 'S1'; a.add();
|
||||||
page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add();
|
page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add();
|
||||||
cards()[0].setVisible(false); fixture.detectChanges(); toggle();
|
cards()[0].setVisible(false); fixture.detectChanges(); toggle();
|
||||||
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S2']);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => {
|
it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => {
|
||||||
@@ -258,7 +265,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
|
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
|
||||||
});
|
});
|
||||||
it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => {
|
it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => {
|
||||||
load(); toggle(); flushAll(); control().changeMode('manual');
|
load(); toggle(); flushAll(); control().select([]);
|
||||||
page.changeTema('oscuro'); fixture.detectChanges(); flushAll();
|
page.changeTema('oscuro'); fixture.detectChanges(); flushAll();
|
||||||
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll();
|
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll();
|
||||||
toggle(); page.changeDominio('tea'); fixture.detectChanges(); load();
|
toggle(); page.changeDominio('tea'); fixture.detectChanges(); load();
|
||||||
@@ -312,7 +319,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
load(syntheticCatalogs.tea);
|
load(syntheticCatalogs.tea);
|
||||||
const index = cards().findIndex(c => c.indicador.id === id);
|
const index = cards().findIndex(c => c.indicador.id === id);
|
||||||
toggle(index); flushAll();
|
toggle(index); flushAll();
|
||||||
const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable();
|
const c = control(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||||
expect(c.canApply).toBe(false); http.expectNone(() => true);
|
expect(c.canApply).toBe(false); http.expectNone(() => true);
|
||||||
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||||
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
|
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
|
||||||
@@ -338,9 +345,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
|
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
|
||||||
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
|
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
|
||||||
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
|
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
|
||||||
const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf<HTMLElement>;
|
|
||||||
expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
|
expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
|
||||||
expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1);
|
|
||||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
|
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,17 +8,19 @@ import { MatCardModule } from '@angular/material/card';
|
|||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatInputModule } from '@angular/material/input';
|
import { MatInputModule } from '@angular/material/input';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { ConnectedPosition, Overlay, OverlayModule } from '@angular/cdk/overlay';
|
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
|
||||||
import { catchError, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
|
|
||||||
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
|
import { Dominio, isDominio, Indicador, Tema } from './indicadores.models';
|
||||||
|
import { vistaEscenario } from './indicadores-eu7-escenario';
|
||||||
|
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||||
import { IndicadoresService } from './indicadores.service';
|
import { IndicadoresService } from './indicadores.service';
|
||||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
||||||
import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||||
|
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||||
@@ -29,37 +31,46 @@ import { IndicadoresInitialPeriod } from './indicadores-initial-period';
|
|||||||
import { IndicadoresDefinitions } from './indicadores-definitions';
|
import { IndicadoresDefinitions } from './indicadores-definitions';
|
||||||
import { IndicadoresTracking } from './indicadores-tracking';
|
import { IndicadoresTracking } from './indicadores-tracking';
|
||||||
import { IndicadoresHistorico } from './indicadores-historico';
|
import { IndicadoresHistorico } from './indicadores-historico';
|
||||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||||
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
|
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||||
|
|
||||||
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
|
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||||
|
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||||
const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
|
|
||||||
{ id: 'resumen', label: 'Resumen' },
|
{ id: 'resumen', label: 'Resumen' },
|
||||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||||
{ id: 'datos', label: 'Datos y definiciones' },
|
{ id: 'datos', label: 'Datos y definiciones' },
|
||||||
];
|
];
|
||||||
const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]];
|
// Domains with enough periods for their history to say anything.
|
||||||
|
const CON_HISTORICO: readonly Dominio[] = ['tea', 'cama'];
|
||||||
|
const MIN_BUSQUEDA = 5;
|
||||||
|
const HISTORICO_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||||
|
// Domains whose cohort has an exploratory outcomes analysis.
|
||||||
|
const CON_ANALISIS: readonly Dominio[] = ['cama'];
|
||||||
|
const ANALISIS_SECTIONS: readonly { id: DashboardSection; label: string }[] = [...HISTORICO_SECTIONS.slice(0, 2), { id: 'analisis', label: 'Análisis epidemiológico' }, ...HISTORICO_SECTIONS.slice(2)];
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicadores-page',
|
selector: 'app-indicadores-page',
|
||||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico],
|
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, IndicadoresAnalisis, TeaResumenPeriodo],
|
||||||
templateUrl: './indicadores-page.html',
|
templateUrl: './indicadores-page.html',
|
||||||
styleUrl: './indicadores-page.scss',
|
styleUrl: './indicadores-page.scss',
|
||||||
})
|
})
|
||||||
export class IndicadoresPage {
|
export class IndicadoresPage {
|
||||||
// The history tab is CaMa's; the other domains keep their three sections.
|
get sections() { return this.conAnalisis ? ANALISIS_SECTIONS : this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
|
||||||
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
|
get conHistorico() { return CON_HISTORICO.includes(this.dominio); }
|
||||||
get conHistorico() { return this.dominio === 'cama'; }
|
get conAnalisis() { return CON_ANALISIS.includes(this.dominio); }
|
||||||
readonly activeSection = signal<DashboardSection>('resumen');
|
readonly activeSection = signal<DashboardSection>('resumen');
|
||||||
readonly fichaPacienteAbierta = signal(false);
|
readonly fichaPacienteAbierta = signal(false);
|
||||||
|
// The patients of a curve or a heatmap cell, opened in Seguimiento; the id makes a repeated click apply again.
|
||||||
|
readonly seleccionSeguimiento = signal<SeleccionSeguimiento | undefined>(undefined);
|
||||||
|
verPacientes(seleccion: SeleccionPacientes) {
|
||||||
|
this.seleccionSeguimiento.set({ ...seleccion, id: (this.seleccionSeguimiento()?.id ?? 0) + 1 });
|
||||||
|
this.changeSection('seguimiento');
|
||||||
|
}
|
||||||
setFichaPacienteAbierta(open: boolean) {
|
setFichaPacienteAbierta(open: boolean) {
|
||||||
this.fichaPacienteAbierta.set(open);
|
this.fichaPacienteAbierta.set(open);
|
||||||
if (open) this.closeGraphicNavigation(false, false);
|
|
||||||
}
|
}
|
||||||
changeSection(section: DashboardSection) {
|
changeSection(section: DashboardSection) {
|
||||||
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
|
if (!this.sections.some(item => item.id === section) || this.activeSection() === section) return;
|
||||||
if (section !== 'resumen') this.closeGraphicNavigation(false, false);
|
|
||||||
this.activeSection.set(section);
|
this.activeSection.set(section);
|
||||||
// Retain views, filters and Plotly hosts; only visible regions authorize loading.
|
// Retain views, filters and Plotly hosts; only visible regions authorize loading.
|
||||||
if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false);
|
if (section !== 'resumen') for (const card of this.graphicCards()) card.setVisible(false);
|
||||||
@@ -79,28 +90,9 @@ export class IndicadoresPage {
|
|||||||
private readonly document = inject(DOCUMENT);
|
private readonly document = inject(DOCUMENT);
|
||||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||||
private readonly injector = inject(Injector);
|
private readonly injector = inject(Injector);
|
||||||
private readonly searchInput = viewChild<ElementRef<HTMLInputElement>>('searchInput');
|
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
|
||||||
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 graphicCards = viewChildren(IndicadorCatalogCard);
|
||||||
|
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
|
||||||
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
|
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
|
||||||
private renderedCards: readonly IndicadorCatalogCard[] = [];
|
private renderedCards: readonly IndicadorCatalogCard[] = [];
|
||||||
private visibilityObserver?: IntersectionObserver;
|
private visibilityObserver?: IntersectionObserver;
|
||||||
@@ -186,7 +178,26 @@ export class IndicadoresPage {
|
|||||||
this.visibilityObserver = observer;
|
this.visibilityObserver = observer;
|
||||||
for (const region of this.observedRegions.keys()) observer.observe(region);
|
for (const region of this.observedRegions.keys()) observer.observe(region);
|
||||||
}
|
}
|
||||||
|
// Report: every selected chart has to be drawn, narrow enough for a page, before opening the print dialog.
|
||||||
|
readonly preparandoReporte = signal(false);
|
||||||
|
async descargarReporte() {
|
||||||
|
const browser = this.document.defaultView;
|
||||||
|
if (!browser || this.preparandoReporte()) return;
|
||||||
|
this.preparandoReporte.set(true);
|
||||||
|
for (const card of this.graphicCards()) card.setVisible(true);
|
||||||
|
this.changeDetector.markForCheck();
|
||||||
|
const espera = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
const pendiente = () => this.element.nativeElement.querySelector('#panel-resumen mat-progress-bar, #panel-resumen .figure-skeleton');
|
||||||
|
await espera(100);
|
||||||
|
for (let i = 0; pendiente() && i < 150; i++) await espera(100);
|
||||||
|
// Charts resize to the page width on their next frames.
|
||||||
|
await espera(500);
|
||||||
|
const terminar = () => { this.preparandoReporte.set(false); this.changeDetector.markForCheck(); this.visibilityChanged(); };
|
||||||
|
browser.addEventListener('afterprint', terminar, { once: true });
|
||||||
|
browser.print();
|
||||||
|
}
|
||||||
private evaluateVisibility() {
|
private evaluateVisibility() {
|
||||||
|
if (this.preparandoReporte()) return;
|
||||||
const browser = this.document.defaultView;
|
const browser = this.document.defaultView;
|
||||||
if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return;
|
if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return;
|
||||||
if (this.activeSection() !== 'resumen') return;
|
if (this.activeSection() !== 'resumen') return;
|
||||||
@@ -203,14 +214,12 @@ export class IndicadoresPage {
|
|||||||
}
|
}
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
clearSearch() {
|
changeIndicatorSelection(ids: string[]) {
|
||||||
this.changeSearchQuery('');
|
|
||||||
this.searchInput()?.nativeElement.focus({ preventScroll: true });
|
|
||||||
}
|
|
||||||
changeSearchQuery(query: string) {
|
|
||||||
this.preserveCardFocus();
|
this.preserveCardFocus();
|
||||||
this.searchQuery.set(query);
|
// Every indicator checked is the same as no filter, so later catalog additions also show.
|
||||||
|
this.indicatorSelection.set(ids.length === this.catalogOrder().length ? null : ids);
|
||||||
}
|
}
|
||||||
|
showAllIndicators() { this.changeIndicatorSelection(this.catalogOrder().map(item => item.id)); }
|
||||||
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
|
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
|
||||||
togglePinned(item: Indicador) {
|
togglePinned(item: Indicador) {
|
||||||
this.preserveCardFocus();
|
this.preserveCardFocus();
|
||||||
@@ -278,7 +287,9 @@ export class IndicadoresPage {
|
|||||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
|
||||||
// At the start of the header line.
|
// At the start of the header line.
|
||||||
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
|
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
|
||||||
readonly kpisByDomain = KPI_BY_DOMAIN;
|
// Short form for the domain-switcher buttons (our shell's own nav, see the
|
||||||
|
// template comment above it) -- `domainLabels`/`domainTitles` are prose-length.
|
||||||
|
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
|
||||||
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
||||||
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
||||||
kpiIndicator(id: string) {
|
kpiIndicator(id: string) {
|
||||||
@@ -293,21 +304,12 @@ export class IndicadoresPage {
|
|||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// CaMa's summary: without the indicators it does not draw, and with the patients' counts on the exams' card.
|
|
||||||
private cardsDeCama(catalog: Indicador[]) {
|
|
||||||
const ids = catalog.map(item => item.id);
|
|
||||||
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
|
||||||
// The histopathology card keeps its place, first, whether pending or published.
|
|
||||||
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
|
||||||
}
|
|
||||||
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
|
||||||
get histopatologiaPendiente() {
|
|
||||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
|
||||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
|
||||||
}
|
|
||||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
|
||||||
get shownIndicators() { return this.dominio === 'cama' ? this.searchResults().items.length : this.catalog().length; }
|
|
||||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||||
|
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||||
|
get teaResumenPeriodo(): string | undefined {
|
||||||
|
const selection = this.filters?.applied.selection;
|
||||||
|
return this.dominio === 'tea' && selection?.mode === 'explicit' && selection.periodos.length === 1 ? selection.periodos[0] : undefined;
|
||||||
|
}
|
||||||
get opportunityKpis() {
|
get opportunityKpis() {
|
||||||
const definitions = this.availableKpis;
|
const definitions = this.availableKpis;
|
||||||
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
|
if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions;
|
||||||
@@ -321,37 +323,46 @@ export class IndicadoresPage {
|
|||||||
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
|
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
|
||||||
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||||
}
|
}
|
||||||
|
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
||||||
|
get histopatologiaPendiente() {
|
||||||
|
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||||
|
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||||
|
}
|
||||||
private readonly catalogRequests = new Subject<void>();
|
private readonly catalogRequests = new Subject<void>();
|
||||||
readonly catalog = signal<Indicador[]>([]);
|
readonly catalog = signal<Indicador[]>([]);
|
||||||
readonly searchQuery = signal('');
|
// Ids of the indicators to render; null shows the whole catalog.
|
||||||
// CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws.
|
readonly indicatorSelection = signal<string[] | null>(null);
|
||||||
// The catalog is read first: `dominio` is not a signal, so a short-circuit before the read would leave this
|
// With a few indicators every card is in view; the selector only pays off from MIN_BUSQUEDA on. CaMa follows its
|
||||||
// computed without dependencies, and it would never change after a visit to CaMa.
|
// mockup: no search and no pins. The catalog is read first: `dominio` is not a signal, so a short-circuit before
|
||||||
readonly searchVisible = computed(() => { const total = this.catalog().length; return this.dominio !== 'cama' && total >= 5; });
|
// the read would leave this computed without dependencies, and it would never change after a visit to CaMa.
|
||||||
readonly searchResults = computed(() => {
|
readonly searchVisible = computed(() => { const total = this.catalogOrder().length; return this.dominio !== 'cama' && total >= MIN_BUSQUEDA; });
|
||||||
|
// Stable presentation priority; pins still take precedence in the grid.
|
||||||
|
readonly catalogOrder = computed(() => {
|
||||||
const catalog = this.catalog();
|
const catalog = this.catalog();
|
||||||
// Stable presentation priority; search matches and pins still take precedence.
|
// The interactive views go first.
|
||||||
const items = this.dominio === 'cacu'
|
// A paired partner is drawn on its pair's card, not on one of its own.
|
||||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
|
const ids = catalog.map(item => item.id);
|
||||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog) : catalog;
|
// CaMa's summary leaves out the indicators drawn as KPI cards or only in Histórico.
|
||||||
if (this.dominio === 'cama') return { items, active: false, count: 0 };
|
const fuera = (item: Indicador) => this.dominio === 'cama' && CAMA_FUERA_DEL_RESUMEN.includes(item.id);
|
||||||
const query = this.normalizeSearch(this.searchQuery());
|
const resumen = catalog.filter(item => (!item.vistas || item.vistas.includes('resumen')) && !esSocioConteos(this.dominio, item.id, ids) && !fuera(item));
|
||||||
const prioritize = (group: Indicador[]) => [
|
// CaMa's histopathology card keeps its place, first, whether pending or published.
|
||||||
...group.filter(item => this.isPinned(item)),
|
const primero = (item: Indicador) => !!vistaEscenario(this.dominio, item) || item.id === ID_HISTOPATOLOGIA_CAMA;
|
||||||
...group.filter(item => !this.isPinned(item)),
|
return [...resumen.filter(primero), ...resumen.filter(item => !primero(item))];
|
||||||
];
|
});
|
||||||
if (!query) return { items: prioritize(items), active: false, count: 0 };
|
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||||
const matches: Indicador[] = [];
|
readonly selectionSummary = computed(() => {
|
||||||
const remaining: Indicador[] = [];
|
const selected = this.selectedIndicators();
|
||||||
for (const item of items) {
|
if (this.indicatorSelection() === null) return 'Todos los indicadores';
|
||||||
const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query));
|
if (selected.length === 1) return this.catalog().find(item => item.id === selected[0])?.titulo ?? selected[0];
|
||||||
(matchesQuery ? matches : remaining).push(item);
|
return selected.length + ' indicadores';
|
||||||
}
|
});
|
||||||
return { items: [...prioritize(matches), ...prioritize(remaining)], active: true, count: matches.length };
|
readonly searchResults = computed(() => {
|
||||||
|
const selected = new Set(this.selectedIndicators());
|
||||||
|
const items = this.catalogOrder().filter(item => selected.has(item.id));
|
||||||
|
// Below MIN_BUSQUEDA there are no pin buttons, so saved pins don't reorder the cards either.
|
||||||
|
if (!this.searchVisible()) return { items };
|
||||||
|
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
|
||||||
});
|
});
|
||||||
private normalizeSearch(value: string) {
|
|
||||||
return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim();
|
|
||||||
}
|
|
||||||
readonly catalogLoading = signal(true);
|
readonly catalogLoading = signal(true);
|
||||||
readonly catalogError = signal('');
|
readonly catalogError = signal('');
|
||||||
tema: Tema = 'claro';
|
tema: Tema = 'claro';
|
||||||
@@ -381,115 +392,56 @@ export class IndicadoresPage {
|
|||||||
}
|
}
|
||||||
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
||||||
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
|
cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); }
|
||||||
get showGraphicNavigation() {
|
// «Ir» in the indicator selector: show the indicator if it was filtered out, then scroll to its card.
|
||||||
return this.dominio !== 'cama' && this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading()
|
goToIndicator(id: string, event?: Event) {
|
||||||
&& !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0;
|
// The link sits inside a mat-option: it must not toggle the option's selection.
|
||||||
}
|
event?.preventDefault(); event?.stopPropagation();
|
||||||
toggleGraphicNavigation(event?: MouseEvent) {
|
if (!this.catalog().some(item => item.id === id)) return;
|
||||||
if (!this.showGraphicNavigation) return;
|
const selection = this.indicatorSelection();
|
||||||
if (this.navigationOpen()) this.closeGraphicNavigation(false);
|
if (selection && !selection.includes(id)) this.indicatorSelection.set([...selection, id]);
|
||||||
else this.openGraphicNavigation(event?.detail === 0);
|
const key = indicatorIdentity(this.dominio, id), select = this.indicatorSelect();
|
||||||
}
|
const scroll = () => afterNextRender(() => this.scrollToIndicator(key), { injector: this.injector });
|
||||||
private openGraphicNavigation(keyboard = false) {
|
// Closing the panel returns focus to the selector, which would cancel a scroll started before it ends.
|
||||||
if (!this.showGraphicNavigation) return;
|
if (select?.panelOpen) { select.openedChange.pipe(first(open => !open)).subscribe(scroll); select.close(); }
|
||||||
this.clearNavigationTimers();
|
else scroll();
|
||||||
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) {
|
private scrollToIndicator(key: string) {
|
||||||
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()
|
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return;
|
||||||
|| !this.navigationItems().some(item => item.key === key)) return;
|
|
||||||
const target = this.document.getElementById(identityElementId(key));
|
const target = this.document.getElementById(identityElementId(key));
|
||||||
const grid = this.element.nativeElement.querySelector('.catalog-grid');
|
const grid = this.element.nativeElement.querySelector('.catalog-grid');
|
||||||
if (!target || !grid?.contains(target)) return;
|
if (!target || !grid?.contains(target)) return;
|
||||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||||
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
|
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
|
||||||
target.querySelector('h2')?.focus({ preventScroll: true });
|
target.querySelector('h2')?.focus({ preventScroll: true });
|
||||||
|
this.keepAligned(target, grid);
|
||||||
|
}
|
||||||
|
// Figures above the card load as the scroll passes them and grow taller than their placeholders,
|
||||||
|
// pushing the card down. For a short while, put it back in place whenever the grid resizes;
|
||||||
|
// any scrolling by the user ends this.
|
||||||
|
private stopAligning?: () => void;
|
||||||
|
private keepAligned(target: HTMLElement, grid: Element) {
|
||||||
|
this.stopAligning?.();
|
||||||
|
const browser = this.document.defaultView;
|
||||||
|
if (!browser || typeof ResizeObserver === 'undefined') return;
|
||||||
|
const host = this.element.nativeElement;
|
||||||
|
const userInput = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const;
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
const offset = target.getBoundingClientRect().top - host.getBoundingClientRect().top - parseFloat(browser.getComputedStyle(target).scrollMarginTop || '0');
|
||||||
|
if (Math.abs(offset) > 2) target.scrollIntoView({ behavior: 'instant', block: 'start' });
|
||||||
|
});
|
||||||
|
const timer = setTimeout(() => this.stopAligning?.(), 2500);
|
||||||
|
const stop = () => {
|
||||||
|
observer.disconnect(); clearTimeout(timer);
|
||||||
|
for (const type of userInput) host.removeEventListener(type, stop);
|
||||||
|
if (this.stopAligning === stop) this.stopAligning = undefined;
|
||||||
|
};
|
||||||
|
this.stopAligning = stop;
|
||||||
|
observer.observe(grid);
|
||||||
|
for (const type of userInput) host.addEventListener(type, stop, { passive: true });
|
||||||
}
|
}
|
||||||
constructor() {
|
constructor() {
|
||||||
afterEveryRender(() => {
|
afterEveryRender(() => {
|
||||||
this.syncVisibility();
|
this.syncVisibility();
|
||||||
if (!this.showGraphicNavigation && (this.navigationAttached() || this.navigationHoverTimer !== undefined)) this.closeGraphicNavigation(false, false);
|
|
||||||
});
|
});
|
||||||
const browser = this.document.defaultView;
|
const browser = this.document.defaultView;
|
||||||
if (typeof IntersectionObserver !== 'undefined') {
|
if (typeof IntersectionObserver !== 'undefined') {
|
||||||
@@ -497,9 +449,9 @@ export class IndicadoresPage {
|
|||||||
browser?.addEventListener('resize', this.viewportChanged);
|
browser?.addEventListener('resize', this.viewportChanged);
|
||||||
}
|
}
|
||||||
this.destroyRef.onDestroy(() => {
|
this.destroyRef.onDestroy(() => {
|
||||||
|
this.stopAligning?.();
|
||||||
this.filtersEdited();
|
this.filtersEdited();
|
||||||
this.visibilityDestroyed = true;
|
this.visibilityDestroyed = true;
|
||||||
this.closeGraphicNavigation(false, false);
|
|
||||||
this.clearVisibility();
|
this.clearVisibility();
|
||||||
this.sizeObserver?.disconnect();
|
this.sizeObserver?.disconnect();
|
||||||
this.sizeTargets.clear();
|
this.sizeTargets.clear();
|
||||||
@@ -514,7 +466,6 @@ export class IndicadoresPage {
|
|||||||
return this.periodService.dominio(this.dominio, this.catalog());
|
return this.periodService.dominio(this.dominio, this.catalog());
|
||||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state));
|
}), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state));
|
||||||
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
|
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
|
||||||
this.closeGraphicNavigation(false, false);
|
|
||||||
this.cancelInitialPeriod.next();
|
this.cancelInitialPeriod.next();
|
||||||
this.initialPeriodState.set('ready');
|
this.initialPeriodState.set('ready');
|
||||||
this.clearVisibility();
|
this.clearVisibility();
|
||||||
@@ -536,9 +487,8 @@ export class IndicadoresPage {
|
|||||||
}
|
}
|
||||||
changeDominio(dominio: Dominio) {
|
changeDominio(dominio: Dominio) {
|
||||||
if (!isDominio(dominio) || dominio === this.dominio) return;
|
if (!isDominio(dominio) || dominio === this.dominio) return;
|
||||||
this.closeGraphicNavigation(false, false);
|
|
||||||
this.activeSection.set('resumen');
|
this.activeSection.set('resumen');
|
||||||
this.searchQuery.set('');
|
this.indicatorSelection.set(null);
|
||||||
this.filtersEdited();
|
this.filtersEdited();
|
||||||
this.filters = undefined;
|
this.filters = undefined;
|
||||||
this.dominio = dominio;
|
this.dominio = dominio;
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import { By } from '@angular/platform-browser';
|
|||||||
import { IndicadoresPage } from './indicadores-page';
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
import { CACU_RESULTADO_KPI, CAMA_OPORTUNIDAD_KPIS, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||||
|
|
||||||
|
// The period and anchor rules are pinned on CaMa's first three cards (C2, C1, C3r); the fourth follows the same
|
||||||
|
// rules (indicador-kpi-panel.spec.ts covers all four).
|
||||||
|
const KPIS = { ...KPI_BY_DOMAIN, cama: CAMA_OPORTUNIDAD_KPIS.slice(0, 3) };
|
||||||
describe('P0.1 selección publicada y último periodo por KPI', () => {
|
describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -21,12 +24,12 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) });
|
const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) });
|
||||||
function catalog(domain: Dominio) {
|
function catalog(domain: Dominio) {
|
||||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
http.expectOne('/' + domain + '/indicadores').flush(KPIS[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
return http.match(r => r.url.endsWith('/periodos'));
|
return http.match(r => r.url.endsWith('/periodos'));
|
||||||
}
|
}
|
||||||
function load(domain: Dominio, periods: string[][]) {
|
function load(domain: Dominio, periods: string[][]) {
|
||||||
catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i])));
|
catalog(domain).forEach((r, i) => r.flush(payload(KPIS[domain][i].id, periods[i])));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
}
|
}
|
||||||
// Regression assertions below target the original KPI contracts. The added lab
|
// Regression assertions below target the original KPI contracts. The added lab
|
||||||
@@ -43,7 +46,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
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 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 editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||||
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
|
function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos {
|
||||||
const d = KPI_BY_DOMAIN[domain][index];
|
const d = KPIS[domain][index];
|
||||||
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{
|
return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{
|
||||||
periodo: period, grupo: d.contrato === 'C1' ? '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,
|
n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0,
|
||||||
@@ -56,7 +59,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
if (!requests.length) return resolved;
|
if (!requests.length) return resolved;
|
||||||
resolved.push(...requests);
|
resolved.push(...requests);
|
||||||
requests.forEach(r => {
|
requests.forEach(r => {
|
||||||
const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
const index = KPIS[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
||||||
r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed));
|
r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed));
|
||||||
});
|
});
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
@@ -64,12 +67,13 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
}
|
}
|
||||||
it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => {
|
it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => {
|
||||||
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]);
|
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]);
|
||||||
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos'));
|
const anchor = http.expectOne(r => r.url.endsWith('/' + KPIS[domain][0].id + '/datos'));
|
||||||
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
|
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
|
||||||
const requests = flushDatos(domain);
|
const requests = flushDatos(domain);
|
||||||
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1'));
|
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPIS[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.temporalReference)).toEqual(KPIS[domain].map(() => '2026-S1'));
|
||||||
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, undefined]); // CaMa's second card is a median over n = 0, which is no value
|
// CaMa's time to result is a median over observations: with none it is no value, not zero days.
|
||||||
|
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', undefined]);
|
||||||
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
|
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
|
||||||
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
|
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
|
||||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||||
@@ -85,14 +89,14 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true);
|
expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => {
|
it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => {
|
||||||
load('cama', [[], ['2025-S2']]);
|
load('cama', [[], ['2025-S2'], ['2025-S1']]);
|
||||||
expect(fixture.componentInstance.initialPeriodState()).toBe('empty'); expect(panels()).toHaveLength(0);
|
expect(fixture.componentInstance.initialPeriodState()).toBe('empty'); expect(panels()).toHaveLength(0);
|
||||||
http.expectNone(r => r.url.endsWith('/datos'));
|
http.expectNone(r => r.url.endsWith('/datos'));
|
||||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const requests = flushDatos('cama');
|
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const requests = flushDatos('cama');
|
||||||
expect(requests).toHaveLength(1); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
|
expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
|
||||||
expect(panels()[0].result().value).toBeUndefined();
|
expect(panels()[0].result().value).toBeUndefined();
|
||||||
});
|
});
|
||||||
it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => {
|
it('selección mensual edita sin HTTP; un periodo consulta y no se pueden elegir varios', async () => {
|
||||||
load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu');
|
load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu');
|
||||||
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
|
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
|
||||||
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
|
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
|
||||||
@@ -103,23 +107,22 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
|
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
|
||||||
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
|
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
|
||||||
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
|
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
|
||||||
|
expect(control.selectedPeriods).toEqual(['2025-10']);
|
||||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||||
expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true);
|
expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
|
||||||
http.expectNone(() => true);
|
|
||||||
control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
await fixture.whenStable();
|
await fixture.whenStable();
|
||||||
});
|
});
|
||||||
it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => {
|
it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => {
|
||||||
const requests = catalog('cacu');
|
const requests = catalog('cacu');
|
||||||
requests[0].flush('private', { status: 503, statusText: 'Unavailable' });
|
requests[0].flush('private', { status: 503, statusText: 'Unavailable' });
|
||||||
requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2'])));
|
requests.slice(1).forEach((r, i) => r.flush(payload(KPIS.cacu[i + 1].id, ['2025-S2'])));
|
||||||
fixture.detectChanges(); flushDatos('cacu');
|
fixture.detectChanges(); flushDatos('cacu');
|
||||||
expect(fixture.componentInstance.initialPeriodState()).toBe('error');
|
expect(fixture.componentInstance.initialPeriodState()).toBe('error');
|
||||||
expect(panels()).toHaveLength(0);
|
expect(panels()).toHaveLength(0);
|
||||||
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de cáncer cervicouterino');
|
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de cáncer cervicouterino');
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||||
const control = editor(); control.changeMode('manual'); control.select(['2025-S2']);
|
const control = editor(); control.select([]); control.select(['2025-S2']);
|
||||||
expect(control.canApply).toBe(false);
|
expect(control.canApply).toBe(false);
|
||||||
fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges();
|
fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges();
|
||||||
const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos');
|
const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos');
|
||||||
@@ -131,7 +134,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
|||||||
const outgoing = catalog('cacu'); const incoming = catalog('cama');
|
const outgoing = catalog('cacu'); const incoming = catalog('cama');
|
||||||
expect(outgoing.every(r => r.cancelled)).toBe(true);
|
expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||||
expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow();
|
expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow();
|
||||||
incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1'])));
|
incoming.forEach((r, i) => r.flush(payload(KPIS.cama[i].id, ['2025-S1'])));
|
||||||
fixture.detectChanges(); const requests = flushDatos('cama');
|
fixture.detectChanges(); const requests = flushDatos('cama');
|
||||||
expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||||
expect(editor().options).toEqual(['2025-S1']);
|
expect(editor().options).toEqual(['2025-S1']);
|
||||||
|
|||||||
@@ -63,25 +63,22 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
|||||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => {
|
it('la selección de indicadores conserva la prioridad de los fijados', async () => {
|
||||||
await pin('i3'); await pin('i4');
|
await pin('i3'); await pin('i4');
|
||||||
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle();
|
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
|
||||||
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']);
|
expect(ids()).toEqual(['i3', 'i4', 'i1']);
|
||||||
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true);
|
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
|
||||||
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']);
|
expect(cards()).toHaveLength(3); http.expectNone(() => true);
|
||||||
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
|
|
||||||
});
|
});
|
||||||
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => {
|
it('Mostrar todos restaura el catálogo con los fijados primero', async () => {
|
||||||
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle();
|
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
|
||||||
expect(ids()[0]).toBe('i0');
|
expect(ids()).toEqual(['i0']);
|
||||||
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
|
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
|
||||||
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
|
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
|
||||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
|
|
||||||
});
|
});
|
||||||
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => {
|
it('un fijado sin seleccionar no se muestra', async () => {
|
||||||
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle();
|
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
|
||||||
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0);
|
expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true);
|
||||||
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true);
|
|
||||||
});
|
});
|
||||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||||
|
|||||||
@@ -4,15 +4,11 @@ import { provideHttpClient } from '@angular/common/http';
|
|||||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { NgModel } from '@angular/forms';
|
|
||||||
import { MatSelect } from '@angular/material/select';
|
import { MatSelect } from '@angular/material/select';
|
||||||
import { IndicadoresPage } from './indicadores-page';
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
|
||||||
import { IndicadoresMemory } from './indicadores-memory';
|
|
||||||
import { Indicador } from './indicadores.models';
|
import { Indicador } from './indicadores.models';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
||||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||||
|
|
||||||
const items: Indicador[] = [
|
const items: Indicador[] = [
|
||||||
@@ -23,16 +19,15 @@ const items: Indicador[] = [
|
|||||||
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
{ id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] },
|
||||||
];
|
];
|
||||||
|
|
||||||
describe('UX-05C búsqueda local y partición estable', () => {
|
describe('Selección de indicadores gráficos', () => {
|
||||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||||
let page: IndicadoresPage;
|
let page: IndicadoresPage;
|
||||||
let http: HttpTestingController;
|
let http: HttpTestingController;
|
||||||
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
||||||
const disconnect = vi.fn();
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||||
vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
|
vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
|
||||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; });
|
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
|
||||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||||
@@ -43,184 +38,89 @@ describe('UX-05C búsqueda local y partición estable', () => {
|
|||||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||||
}
|
}
|
||||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
|
function ids() { return cards().map(c => c.indicador.id); }
|
||||||
function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); }
|
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
|
||||||
function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); }
|
function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
|
||||||
function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); }
|
function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
|
||||||
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
|
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
|
||||||
async function search(value: string) {
|
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
|
||||||
input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle();
|
|
||||||
}
|
|
||||||
function respond() {
|
|
||||||
http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges();
|
|
||||||
}
|
|
||||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
|
|
||||||
|
|
||||||
it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => {
|
it.each([0, 1, 4, 5, 6])('muestra el selector desde cinco indicadores: catálogo de %i', count => {
|
||||||
|
// Fails if the selector shows for a handful of cards, or stops showing for a long catalog.
|
||||||
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
|
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
|
||||||
expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count);
|
expect(!!select()).toBe(count >= 5); expect(cards()).toHaveLength(count);
|
||||||
expect(cards().every(c => !c.visible)).toBe(true);
|
|
||||||
http.expectNone(() => true);
|
|
||||||
if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
|
|
||||||
});
|
|
||||||
it.each([
|
|
||||||
['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
|
|
||||||
['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
|
|
||||||
['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
|
|
||||||
['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1],
|
|
||||||
['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
|
|
||||||
[' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2],
|
|
||||||
['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
|
|
||||||
['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
|
|
||||||
[' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0],
|
|
||||||
])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => {
|
|
||||||
load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards();
|
|
||||||
await search(query as string);
|
|
||||||
expect(cards().map(c => c.indicador.id)).toEqual(ids);
|
|
||||||
expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim());
|
|
||||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot);
|
|
||||||
for (const card of cards()) {
|
|
||||||
expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id));
|
|
||||||
expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false);
|
|
||||||
}
|
|
||||||
if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible');
|
|
||||||
if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe('');
|
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => {
|
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
|
||||||
load(); await settle();
|
load();
|
||||||
const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'));
|
expect(select()!.multiple).toBe(true);
|
||||||
const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement;
|
expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
|
||||||
const clear = field.querySelector('button')!;
|
expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
|
||||||
expect(clear.hasAttribute('matIconSuffix')).toBe(true);
|
expect(page.selectionSummary()).toBe('Todos los indicadores');
|
||||||
expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy();
|
expect(result()).toBe('Mostrando 5 de 5 indicadores.');
|
||||||
expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1);
|
expect(showAll().disabled).toBe(true);
|
||||||
expect(input().type).toBe('search');
|
http.expectNone(() => true);
|
||||||
for (const query of ['sexo', 'Indicador destacado', '']) {
|
});
|
||||||
await search(query);
|
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
|
||||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
|
load(); const before = cards(), original = page.catalog();
|
||||||
|
choose(['B02', 'E05']);
|
||||||
|
expect(ids()).toEqual(['B02', 'E05']);
|
||||||
|
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
|
||||||
|
expect(page.selectionSummary()).toBe('2 indicadores');
|
||||||
|
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
|
||||||
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
|
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
|
||||||
expect(cards()).toHaveLength(5);
|
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||||
}
|
expect(page.catalog()).toBe(original);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => {
|
it('sin selección no muestra tarjetas y Mostrar todos restaura el catálogo', () => {
|
||||||
load(); await settle(); const field = input(); field.focus(); await search('sexo');
|
load(); choose([]);
|
||||||
expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo');
|
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
|
||||||
field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2);
|
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
|
||||||
expect(field.labels?.[0].textContent).toContain('Buscar indicadores');
|
expect(showAll().disabled).toBe(false);
|
||||||
for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy();
|
showAll().click(); fixture.detectChanges();
|
||||||
expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull();
|
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
|
||||||
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
|
|
||||||
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); clear.click(); fixture.detectChanges(); await settle();
|
|
||||||
expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
|
|
||||||
expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field);
|
|
||||||
await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2);
|
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => {
|
it('marcar todos equivale a no filtrar', () => {
|
||||||
load(); await settle();
|
load(); choose(['A01']); choose(items.map(i => i.id));
|
||||||
const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement;
|
expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores');
|
||||||
expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true);
|
});
|
||||||
expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda');
|
it('los indicadores destacados no dependen de la selección', () => {
|
||||||
const icon = clear.querySelector('mat-icon')!;
|
load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'));
|
||||||
expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true');
|
choose(['A01']);
|
||||||
expect(clear.textContent).not.toContain('Limpiar');
|
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
|
||||||
expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px');
|
});
|
||||||
await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0);
|
it('«Ir» lleva a la tarjeta sin alternar la opción y muestra el indicador si estaba oculto', async () => {
|
||||||
// jsdom does not synthesize native keyboard activation. Verify that keys remain
|
const scroll = vi.fn();
|
||||||
// available to the browser; Enter/Space activation is a Chrome acceptance check.
|
Element.prototype.scrollIntoView = scroll;
|
||||||
for (const key of ['Enter', ' ']) {
|
load(); choose(['A01']);
|
||||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||||
clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go'))
|
||||||
}
|
.find(a => a.closest('mat-option')!.textContent!.includes(items.find(i => i.id === id)!.titulo))!;
|
||||||
clear.focus(); clear.click(); fixture.detectChanges(); await settle();
|
expect(go('D04').getAttribute('aria-label')).toBe('Ir a Seguimiento');
|
||||||
expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true);
|
// The scroll waits until the panel has finished closing.
|
||||||
|
const settle = (calls: number) => vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(calls); });
|
||||||
|
go('D04').click(); fixture.detectChanges(); await fixture.whenStable();
|
||||||
|
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||||
|
expect(select()!.panelOpen).toBe(false);
|
||||||
|
await settle(1);
|
||||||
|
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
|
||||||
|
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||||
|
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
|
||||||
|
// Already visible: the selection is untouched.
|
||||||
|
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
|
||||||
|
await settle(2);
|
||||||
|
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
|
||||||
|
});
|
||||||
|
it('no muestra el botón flotante de navegación por indicadores', () => {
|
||||||
|
load();
|
||||||
|
expect(fixture.nativeElement.querySelector('.graphic-navigation-trigger')).toBeNull();
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => {
|
it('cambiar de dominio restablece la selección', () => {
|
||||||
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle();
|
load(); choose(['A01']);
|
||||||
const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts();
|
page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull();
|
||||||
const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add();
|
load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||||
page.applyFilters(); fixture.detectChanges(); respond(); await settle();
|
|
||||||
c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026';
|
|
||||||
fixture.detectChanges(); await settle();
|
|
||||||
const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result());
|
|
||||||
const titleIds = beforePanels.map(p => p.titleId);
|
|
||||||
expect(new Set(titleIds).size).toBe(beforePanels.length);
|
|
||||||
const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement);
|
|
||||||
const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple);
|
|
||||||
const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue'));
|
|
||||||
const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal');
|
|
||||||
const reacts = runtime.react.mock.calls.length;
|
|
||||||
const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[];
|
|
||||||
expect(helps).toHaveLength(5);
|
|
||||||
const helpIds = helps.map(button => button.getAttribute('aria-controls')!);
|
|
||||||
expect(new Set(helpIds).size).toBe(5);
|
|
||||||
for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true);
|
|
||||||
helps[0].click(); fixture.detectChanges();
|
|
||||||
http.expectOne(r => r.url.endsWith('/metadatos')).flush({});
|
|
||||||
fixture.detectChanges(); await settle();
|
|
||||||
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
|
|
||||||
expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]);
|
|
||||||
for (const query of ['sexo', 'evaluacion', '']) {
|
|
||||||
if (query) await search(query);
|
|
||||||
else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); }
|
|
||||||
for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card);
|
|
||||||
for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel);
|
|
||||||
beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c));
|
|
||||||
beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c));
|
|
||||||
}
|
|
||||||
expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true);
|
|
||||||
for (const button of helps) expect(button.isConnected).toBe(true);
|
|
||||||
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
|
|
||||||
helps[0].click(); fixture.detectChanges(); await settle();
|
|
||||||
expect(document.getElementById(helpIds[0])?.hidden).toBe(true);
|
|
||||||
expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts);
|
|
||||||
expect(beforePanels.map(p => p.titleId)).toEqual(titleIds);
|
|
||||||
for (const id of titleIds) {
|
|
||||||
const heading = document.getElementById(id)!;
|
|
||||||
expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id);
|
|
||||||
}
|
|
||||||
beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); });
|
|
||||||
beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i]));
|
|
||||||
expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
|
||||||
for (const write of writes) expect(write).not.toHaveBeenCalled();
|
|
||||||
expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled();
|
|
||||||
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
|
||||||
http.expectNone(() => true);
|
|
||||||
});
|
|
||||||
it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => {
|
|
||||||
load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges();
|
|
||||||
const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo');
|
|
||||||
b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
|
||||||
await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error');
|
|
||||||
expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true);
|
|
||||||
a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]);
|
|
||||||
const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} });
|
|
||||||
expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true);
|
|
||||||
});
|
|
||||||
it('reordenar el catálogo conserva foco en el selector global existente', async () => {
|
|
||||||
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
|
|
||||||
filters()[0].changeMode('manual'); fixture.detectChanges(); await settle();
|
|
||||||
const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf<HTMLElement>).at(-1)!;
|
|
||||||
field.focus(); expect(document.activeElement).toBe(field);
|
|
||||||
page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle();
|
|
||||||
expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true);
|
|
||||||
page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field);
|
|
||||||
http.expectNone(() => true);
|
|
||||||
});
|
|
||||||
it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => {
|
|
||||||
load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle();
|
|
||||||
filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add();
|
|
||||||
await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe('');
|
|
||||||
load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false);
|
|
||||||
page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe('');
|
|
||||||
expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]);
|
|
||||||
http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges();
|
|
||||||
const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} });
|
|
||||||
expect(filters()[0].selectedPeriods).toEqual(['2025-S1']);
|
|
||||||
await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond();
|
|
||||||
expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -37,12 +37,13 @@ describe('Secciones compartidas por dominio', () => {
|
|||||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||||
const root = harness.routeNativeElement!;
|
const root = harness.routeNativeElement!;
|
||||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||||
// CaMa also has Histórico, between Resumen and Seguimiento.
|
// Breast cancer adds the exploratory analysis of its BI-RADS 4+ cohort after its history.
|
||||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
|
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']
|
||||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
|
||||||
|
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||||
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
|
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
|
||||||
// Domain switching lives in the shell's header (app.html), not on the page.
|
// The App header switches domains (see app.html); the page has no switcher of its own.
|
||||||
expect(root.querySelector('nav.domain-nav')).toBeNull();
|
expect(root.querySelector('nav.domain-nav')).toBeNull();
|
||||||
for (const tab of tabs) {
|
for (const tab of tabs) {
|
||||||
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
|
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
|
||||||
@@ -50,35 +51,18 @@ describe('Secciones compartidas por dominio', () => {
|
|||||||
expect(panel.hidden).toBe(tab.id !== 'tab-resumen');
|
expect(panel.hidden).toBe(tab.id !== 'tab-resumen');
|
||||||
}
|
}
|
||||||
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
|
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
|
||||||
// By id, since CaMa has one more tab.
|
tab('seguimiento').click(); harness.detectChanges();
|
||||||
const pestana = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
|
||||||
pestana('seguimiento').click(); harness.detectChanges();
|
|
||||||
// CaCu and CaMa request their own follow-up when the tab opens; the lab WebApi has neither yet (404).
|
|
||||||
if (domain !== 'tea') {
|
|
||||||
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
|
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
|
||||||
harness.detectChanges();
|
harness.detectChanges();
|
||||||
}
|
|
||||||
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
||||||
expect(tracking.hidden).toBe(false);
|
expect(tracking.hidden).toBe(false);
|
||||||
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
|
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
|
||||||
if (domain === 'cacu') {
|
// Every domain queries its list; until it is published there is no table, only the form.
|
||||||
expect(tracking.querySelector('tbody')).toBeNull();
|
expect(tracking.querySelector('tbody')).toBeNull();
|
||||||
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
|
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
|
||||||
} else if (domain === 'cama') {
|
tab('datos').click(); harness.detectChanges();
|
||||||
// Pending integration: the form is gone with no table, and the retry is offered.
|
|
||||||
expect(tracking.textContent).toContain('Funcionalidad pendiente de publicación');
|
|
||||||
expect(tracking.querySelector('table')).toBeNull();
|
|
||||||
expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull();
|
|
||||||
expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento');
|
|
||||||
} else {
|
|
||||||
expect(tracking.querySelectorAll('thead th')).toHaveLength(6);
|
|
||||||
expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1);
|
|
||||||
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
|
|
||||||
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
|
|
||||||
}
|
|
||||||
pestana('datos').click(); harness.detectChanges();
|
|
||||||
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
|
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
|
||||||
tabs[0].click(); harness.detectChanges();
|
tab('resumen').click(); harness.detectChanges();
|
||||||
expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards);
|
expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards);
|
||||||
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
|
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
|
||||||
});
|
});
|
||||||
@@ -100,15 +84,15 @@ describe('Secciones compartidas por dominio', () => {
|
|||||||
const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||||
http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
|
http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
|
||||||
const tabs = Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
const tabs = Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||||
expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1]);
|
expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1, -1]);
|
||||||
const focus = tabs.map(tab => vi.spyOn(tab, 'focus'));
|
const focus = tabs.map(tab => vi.spyOn(tab, 'focus'));
|
||||||
function key(index: number, key: string, target: number) {
|
function key(index: number, key: string, target: number) {
|
||||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||||
tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true);
|
tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true);
|
||||||
expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen');
|
expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen');
|
||||||
}
|
}
|
||||||
key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 2); key(1, 'Home', 0); key(0, 'End', 2);
|
key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 3); key(1, 'Home', 0); key(0, 'End', 3);
|
||||||
tabs[2].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, 0]);
|
tabs[3].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, -1, 0]);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Covers CaMa's follow-up table: when it asks, what it sends, how it draws the answer and each state (loading,
|
// Covers CaMa's follow-up table: when it asks, what it sends, how it draws the answer and each state (loading,
|
||||||
// empty, pending, error, retry). The answers are fixtures (fixtures/cama_seguimiento.json and variations of it):
|
// empty, pending, error, retry). The answers are fixtures (fixtures/cama_seguimiento.json and variations of it):
|
||||||
// synthetic records, used by tests only; the view never reads them in normal use.
|
// synthetic records, used by tests only; the view never reads them in normal use. It also covers the selection that
|
||||||
|
// the epidemiological analysis sends (a curve or a heatmap cell): the whole cohort with that selection's filters.
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
@@ -76,11 +77,28 @@ describe('Seguimiento de CaMa (tabla)', () => {
|
|||||||
expect(conBiopsia[4]).toMatch(/^Carcinoma invasor Fecha de biopsia: 20\d\d-\d\d-\d\d$/);
|
expect(conBiopsia[4]).toMatch(/^Carcinoma invasor Fecha de biopsia: 20\d\d-\d\d-\d\d$/);
|
||||||
expect(conBiopsia[5]).toMatch(/^[0-9]+$/);
|
expect(conBiopsia[5]).toMatch(/^[0-9]+$/);
|
||||||
});
|
});
|
||||||
|
it('una selección del análisis pide toda la cohorte con sus filtros, lo anuncia, y Quitar selección vuelve a la ventana de 3 meses', async () => {
|
||||||
|
// Fails if a curve or a cell opens a list cut by a time window, without its filters, or that cannot be undone.
|
||||||
|
fixture.componentRef.setInput('seleccion', { filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio IV', id: 1 });
|
||||||
|
abrir();
|
||||||
|
let r = solicitud();
|
||||||
|
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', resultado: 'INVASOR', estadio: 'IV' });
|
||||||
|
r.flush(pagina(1, 50, { ventana: { meses: 0, desde: '2023-01-02', hasta: '2026-10-20' } })); await asentar();
|
||||||
|
expect(root().querySelector('.seleccion')?.textContent).toContain('Supervivencia: Estadio IV');
|
||||||
|
boton('Quitar selección').click(); fixture.detectChanges();
|
||||||
|
r = solicitud();
|
||||||
|
expect(parametros(r)).toEqual({ corte: '2026-10-20', meses: '3', page: '1', page_size: '50' });
|
||||||
|
r.flush(pagina(1, 50)); await asentar();
|
||||||
|
expect(root().querySelector('.seleccion')).toBeNull();
|
||||||
|
// The same selection again (a new click) applies again.
|
||||||
|
fixture.componentRef.setInput('seleccion', { filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio IV', id: 2 }); fixture.detectChanges();
|
||||||
|
solicitud().flush(pagina(1, 50, { ventana: { meses: 0, desde: '2023-01-02', hasta: '2026-10-20' } }));
|
||||||
|
});
|
||||||
it('el formulario muestra el corte que devolvió el servidor, la ventana, los cuatro filtros anunciados y el tamaño', async () => {
|
it('el formulario muestra el corte que devolvió el servidor, la ventana, los cuatro filtros anunciados y el tamaño', async () => {
|
||||||
await cargado();
|
await cargado();
|
||||||
expect((campo('Fecha de corte').querySelector('input') as HTMLInputElement).value).toBe('2026-10-20');
|
expect((campo('Fecha de corte').querySelector('input') as HTMLInputElement).value).toBe('2026-10-20');
|
||||||
expect((campo('Ventana de meses').querySelector('select') as HTMLSelectElement).selectedOptions[0].text.trim()).toBe('3 meses');
|
expect((campo('Ventana de meses').querySelector('select') as HTMLSelectElement).selectedOptions[0].text.trim()).toBe('3 meses');
|
||||||
expect([...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
|
expect([...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
|
||||||
const etiquetas = [...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim());
|
const etiquetas = [...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim());
|
||||||
expect(etiquetas).toEqual(['Fecha de corte', 'Ventana de meses', 'Estatus de seguimiento', 'Categoría BI-RADS', 'Grupo de edad', 'Prioridad', 'Registros por página']);
|
expect(etiquetas).toEqual(['Fecha de corte', 'Ventana de meses', 'Estatus de seguimiento', 'Categoría BI-RADS', 'Grupo de edad', 'Prioridad', 'Registros por página']);
|
||||||
expect([...campo('Estatus de seguimiento').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
|
expect([...campo('Estatus de seguimiento').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
|
||||||
|
|||||||
@@ -5,13 +5,16 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|||||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||||
import { Dominio } from './indicadores.models';
|
import { Dominio } from './indicadores.models';
|
||||||
import {
|
import {
|
||||||
MESES_VENTANA, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse,
|
MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse,
|
||||||
SeguimientoTablaService, SeguimientoValor,
|
SeguimientoTablaService, SeguimientoValor,
|
||||||
} from './seguimiento-tabla.service';
|
} from './seguimiento-tabla.service';
|
||||||
|
|
||||||
type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error';
|
type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error';
|
||||||
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string };
|
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string };
|
||||||
interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; filtros: Record<string, string | undefined>; }
|
// What the analysis sends: the list's filters, how to name them, and an id that changes with each click.
|
||||||
|
export interface SeleccionSeguimiento { filtros: Record<string, string>; etiqueta: string; id: number; }
|
||||||
|
|
||||||
|
interface Borrador { corte?: string; meses: MesesVentana; page_size: number; filtros: Record<string, string | undefined>; }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Follow-up list of a domain, drawn from what `GET /<dominio>/seguimiento` announces: the filters, the columns
|
* Follow-up list of a domain, drawn from what `GET /<dominio>/seguimiento` announces: the filters, the columns
|
||||||
@@ -21,10 +24,16 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
|
|||||||
selector: 'app-seguimiento-tabla',
|
selector: 'app-seguimiento-tabla',
|
||||||
imports: [FormsModule],
|
imports: [FormsModule],
|
||||||
template: `
|
template: `
|
||||||
|
@if (seleccionMostrada(); as sel) {
|
||||||
|
<div class="seleccion" role="status">
|
||||||
|
<span>Pacientes de la selección del análisis epidemiológico: <strong>{{ sel }}</strong>. Toda la cohorte, sin ventana de tiempo.</span>
|
||||||
|
<button type="button" (click)="quitarSeleccion()">Quitar selección</button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
<form (ngSubmit)="aplicar()">
|
<form (ngSubmit)="aplicar()">
|
||||||
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
||||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||||
@for (m of ventanas; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
@for (m of ventanas; track m) { <option [ngValue]="m">{{ m === 0 ? 'Toda la cohorte' : m + (m === 1 ? ' mes' : ' meses') }}</option> }
|
||||||
</select></label>
|
</select></label>
|
||||||
@for (filtro of filtros(); track filtro.clave) {
|
@for (filtro of filtros(); track filtro.clave) {
|
||||||
<label>{{ filtro.etiqueta }} <select [name]="'filtro-' + filtro.clave" [(ngModel)]="draft.filtros[filtro.clave]">
|
<label>{{ filtro.etiqueta }} <select [name]="'filtro-' + filtro.clave" [(ngModel)]="draft.filtros[filtro.clave]">
|
||||||
@@ -86,11 +95,17 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
|
|||||||
th { background: var(--issste-background); font-weight: 600; }
|
th { background: var(--issste-background); font-weight: 600; }
|
||||||
small { display: block; margin-top: .35rem; }
|
small { display: block; margin-top: .35rem; }
|
||||||
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
|
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
|
||||||
|
.seleccion { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-bottom: 1rem; padding: .5rem .75rem;
|
||||||
|
border-left: 4px solid var(--issste-accent); background: var(--issste-surface); }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class IndicadoresSeguimientoTabla implements OnChanges {
|
export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||||
@Input({ required: true }) dominio!: Dominio;
|
@Input({ required: true }) dominio!: Dominio;
|
||||||
@Input() active = false;
|
@Input() active = false;
|
||||||
|
// The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again.
|
||||||
|
@Input() seleccion?: SeleccionSeguimiento;
|
||||||
|
readonly seleccionMostrada = signal<string | undefined>(undefined);
|
||||||
|
private seleccionAplicada?: number;
|
||||||
private readonly service = inject(SeguimientoTablaService);
|
private readonly service = inject(SeguimientoTablaService);
|
||||||
private readonly consultas = new Subject<SeguimientoTablaQuery | null>();
|
private readonly consultas = new Subject<SeguimientoTablaQuery | null>();
|
||||||
readonly ventanas = MESES_VENTANA;
|
readonly ventanas = MESES_VENTANA;
|
||||||
@@ -131,8 +146,19 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
|||||||
this.previo = this.dominio; this.iniciado = false; this.consultas.next(null);
|
this.previo = this.dominio; this.iniciado = false; this.consultas.next(null);
|
||||||
this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 };
|
this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 };
|
||||||
}
|
}
|
||||||
|
const sel = this.seleccion;
|
||||||
|
if (this.active && sel && sel.id !== this.seleccionAplicada) {
|
||||||
|
this.seleccionAplicada = sel.id; this.iniciado = true;
|
||||||
|
this.draft = { ...this.draft, meses: 0, filtros: { ...sel.filtros } };
|
||||||
|
this.aplicar(sel.etiqueta);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(this.applied); }
|
if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(this.applied); }
|
||||||
}
|
}
|
||||||
|
quitarSeleccion() {
|
||||||
|
this.draft = { ...this.draft, meses: 3, filtros: {} };
|
||||||
|
this.aplicar();
|
||||||
|
}
|
||||||
|
|
||||||
private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado {
|
private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado {
|
||||||
// A first page that does not exist yet is the list's own pending state; a later page that fails is an error.
|
// A first page that does not exist yet is the list's own pending state; a later page that fails is an error.
|
||||||
@@ -150,7 +176,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
|||||||
filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) };
|
filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) };
|
||||||
this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size;
|
this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size;
|
||||||
}
|
}
|
||||||
aplicar() {
|
// From the form the banner goes away: the list is no longer the analysis' selection.
|
||||||
|
aplicar(seleccion?: string) {
|
||||||
|
this.seleccionMostrada.set(seleccion);
|
||||||
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
|
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
|
||||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros };
|
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros };
|
||||||
this.applied = q;
|
this.applied = q;
|
||||||
|
|||||||
@@ -48,7 +48,9 @@ describe('Barras estratificadas: activación y caché',()=>{
|
|||||||
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
|
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
|
||||||
expect(fixture.componentInstance.dimension).toBe('grupo_edad');
|
expect(fixture.componentInstance.dimension).toBe('grupo_edad');
|
||||||
expect(toggle[1].getAttribute('aria-checked')).toBe('true');
|
expect(toggle[1].getAttribute('aria-checked')).toBe('true');
|
||||||
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2);
|
// The dimensions, apart from the counts or percentage toggle that follows them.
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2);
|
||||||
|
expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2);
|
||||||
for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); }
|
for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); }
|
||||||
});
|
});
|
||||||
it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
|
it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json';
|
import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json';
|
||||||
import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json';
|
import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json';
|
||||||
import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified';
|
import { etiquetaDimension, stratifiedBars, stratifiedCapabilities } from './indicadores-stratified';
|
||||||
import { DimensionEstrato, Indicador } from './indicadores.models';
|
import { DimensionEstrato, Indicador } from './indicadores.models';
|
||||||
|
|
||||||
const age = { ...ageJson, tipo_periodo: 'semestre' as const };
|
const age = { ...ageJson, tipo_periodo: 'semestre' as const };
|
||||||
@@ -61,3 +61,33 @@ describe('Contratos simulados de estratificación de los analistas', () => {
|
|||||||
expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow();
|
expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total.
|
||||||
|
const porEtapa = () => ({
|
||||||
|
id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa',
|
||||||
|
valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' },
|
||||||
|
grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } },
|
||||||
|
totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 },
|
||||||
|
{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }],
|
||||||
|
filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]]
|
||||||
|
.map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })),
|
||||||
|
});
|
||||||
|
describe('Porcentaje en cada estrato', () => {
|
||||||
|
it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => {
|
||||||
|
// Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total.
|
||||||
|
const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje');
|
||||||
|
expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]);
|
||||||
|
expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]);
|
||||||
|
expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato');
|
||||||
|
expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]);
|
||||||
|
});
|
||||||
|
it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => {
|
||||||
|
// Fails if a new stratifier is offered without its published label, or CaCu's wording changes.
|
||||||
|
const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'],
|
||||||
|
filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] },
|
||||||
|
{ estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] };
|
||||||
|
expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']);
|
||||||
|
expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)');
|
||||||
|
expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -4,14 +4,25 @@ import { c2Color, c2Theme } from './indicadores-c2-palette';
|
|||||||
|
|
||||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut.
|
||||||
|
const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'clasificacion', 'estadio', 'tamano', 'etapa'];
|
||||||
|
/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */
|
||||||
|
export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string {
|
||||||
|
if (d === 'grupo_edad') return 'Por grupo de edad';
|
||||||
|
if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento';
|
||||||
|
const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta;
|
||||||
|
return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d);
|
||||||
|
}
|
||||||
|
export type MedidaEstrato = 'conteo' | 'porcentaje';
|
||||||
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
||||||
return item.contrato === 'C2' && Array.isArray(item.filtros)
|
return item.contrato === 'C2' && Array.isArray(item.filtros)
|
||||||
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
|
? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d
|
||||||
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
||||||
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
||||||
}
|
}
|
||||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
// `percent`: the cell's share of its stratum, when the stratum's total is known.
|
||||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||||
|
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo'): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||||
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
||||||
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|
||||||
|| Object.keys(data['grupos']).length !== 1
|
|| Object.keys(data['grupos']).length !== 1
|
||||||
@@ -43,21 +54,38 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
|||||||
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
||||||
const cells: StratifiedCell[] = [];
|
const cells: StratifiedCell[] = [];
|
||||||
const theme = c2Theme(tema);
|
const theme = c2Theme(tema);
|
||||||
|
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is
|
||||||
|
// only drawn over a known total; a suppressed or missing total leaves the stratum without percentages.
|
||||||
|
const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record<string, unknown>[] : [];
|
||||||
|
const totalDe = (s: string): number | null => {
|
||||||
|
const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup);
|
||||||
|
if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null;
|
||||||
|
const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s])));
|
||||||
|
if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null;
|
||||||
|
const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0);
|
||||||
|
return suma > 0 ? suma : null;
|
||||||
|
};
|
||||||
|
const porcentaje = medida === 'porcentaje';
|
||||||
const figure: PlotlyFigure = { data: strata.map((s, series) => {
|
const figure: PlotlyFigure = { data: strata.map((s, series) => {
|
||||||
const selected = categories.map(([id, c]) => {
|
const selected = categories.map(([id, c]) => {
|
||||||
const row = rows.get(JSON.stringify([id, s]));
|
const row = rows.get(JSON.stringify([id, s]));
|
||||||
const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible';
|
const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible';
|
||||||
const value = status === 'Publicado' ? row!['n'] as number : null;
|
const value = status === 'Publicado' ? row!['n'] as number : null;
|
||||||
cells.push({ category: c.label, stratum: labels[s] as string, value, status });
|
const total = totalDe(s);
|
||||||
return value;
|
const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null;
|
||||||
|
cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status });
|
||||||
|
return { value, percent, total };
|
||||||
});
|
});
|
||||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
|
const x = selected.map(v => porcentaje ? v.percent : v.value);
|
||||||
|
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)),
|
||||||
|
customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']),
|
||||||
marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
|
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>' };
|
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||||
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
|
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : '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,
|
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 },
|
font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 },
|
||||||
xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid }
|
||||||
|
: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid },
|
||||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true },
|
yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true },
|
||||||
legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } };
|
legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } };
|
||||||
return { figure, cells };
|
return { figure, cells };
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { C2Distribution } from './indicadores-c2-adapter';
|
||||||
|
import { highlightFigure } from './indicadores-highlight';
|
||||||
|
import { teaC2Donut } from './indicadores-tea-c2';
|
||||||
|
|
||||||
|
const categoria = (id: string, label: string, value: number, color: string, parentId?: string) => ({ id, label, value, color, parentId });
|
||||||
|
const modelo = (extra: object = {}) => ({ period: '2025-S2', unit: 'paciente', title: 'T', total: 380, notes: [], nodes: [], parents: [],
|
||||||
|
categories: [categoria('CONFIRMADO', 'Diagnóstico confirmado', 338, '#A8C243'), categoria('EN_PROCESO', 'En proceso', 42, '#B8433A')], ...extra }) as unknown as C2Distribution;
|
||||||
|
|
||||||
|
describe('Dona C2 de TEA', () => {
|
||||||
|
it('sin grupos dibuja un anillo con rótulos, el total al centro y un botón por categoría', () => {
|
||||||
|
const { figure, highlight } = teaC2Donut(modelo(), 'claro', { text: 'T' })!;
|
||||||
|
expect(figure.data).toHaveLength(1);
|
||||||
|
expect(figure.data[0]).toMatchObject({ type: 'pie', values: [338, 42], labels: ['Diagnóstico confirmado', 'En proceso'] });
|
||||||
|
expect(figure.data[0]['text']).toEqual(['Diagnóstico confirmado<br>88.9 %', 'En proceso<br>11.1 %']);
|
||||||
|
expect((figure.layout['annotations'] as { text: string }[])[0].text).toBe('<b>380</b><br>TOTAL');
|
||||||
|
expect(highlight.groups).toEqual([]);
|
||||||
|
expect(highlight.items.map(i => [i.label, i.color])).toEqual([['Diagnóstico confirmado', '#A8C243'], ['En proceso', '#B8433A']]);
|
||||||
|
});
|
||||||
|
it('al elegir una categoría atenúa la otra y muestra su número al centro', () => {
|
||||||
|
const { figure, highlight } = teaC2Donut(modelo(), 'claro', { text: 'T' })!;
|
||||||
|
const elegida = highlightFigure(figure, highlight, { item: 'EN_PROCESO' });
|
||||||
|
expect((elegida.data[0]['marker'] as { colors: string[] }).colors).toEqual(['rgba(168, 194, 67, 0.3)', 'rgba(184,67,58,1)']);
|
||||||
|
expect((elegida.layout['annotations'] as { text: string }[])[0].text).toBe('<b>42</b><br>En proceso');
|
||||||
|
});
|
||||||
|
it('sin pacientes no dibuja nada', () => {
|
||||||
|
expect(teaC2Donut(modelo({ total: 0 }), 'claro', {})).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { C2Distribution } from './indicadores-c2-adapter';
|
||||||
|
import { c2Color, c2Theme } from './indicadores-c2-palette';
|
||||||
|
import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario';
|
||||||
|
import { donaHighlight, FigureHighlight } from './indicadores-highlight';
|
||||||
|
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||||
|
|
||||||
|
// TEA (mock): C2 distributions with groups are drawn like CaCu's «Distribución de resultados
|
||||||
|
// citológicos», both rings at once with highlight buttons, instead of the drill-down donut.
|
||||||
|
const average = (colors: string[]) => '#' + [1, 3, 5].map(i => Math.round(colors.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colors.length)
|
||||||
|
.toString(16).padStart(2, '0')).join('').toUpperCase();
|
||||||
|
const hex = (c: string | undefined, i: number) => { const v = c2Color(c, i); return /^#[0-9a-f]{6}$/i.test(v) ? v : c2Color(undefined, i); };
|
||||||
|
|
||||||
|
export function teaC2Donut(model: C2Distribution, tema: Tema, title: unknown): { figure: PlotlyFigure; highlight: FigureHighlight } | undefined {
|
||||||
|
if (model.total === 0) return undefined;
|
||||||
|
const unAnillo = !model.parents.length;
|
||||||
|
const categorias: Categoria[] = model.categories.map((c, i) => ({ id: c.id, etiqueta: c.label, color: hex(c.color, i), grupo: unAnillo ? 'total' : 'group:' + c.parentId }));
|
||||||
|
// A group takes the average colour of its categories, as in CaCu.
|
||||||
|
const padres = unAnillo ? [{ id: 'total', label: 'TOTAL' }] : model.parents;
|
||||||
|
const grupos: Grupo[] = padres.map(p => ({ id: p.id, etiqueta: p.label, color: average(categorias.filter(c => c.grupo === p.id).map(c => c.color)) }));
|
||||||
|
const celdas: Modelo['celdas'] = Object.fromEntries(model.categories.map(c => [c.id, { n: c.value, estado: 'Publicado' as const }]));
|
||||||
|
const modelo: Modelo = { periodo: model.period, categorias, grupos, celdas, total: model.total, sinDato: { n: 0, estado: 'Publicado' },
|
||||||
|
escenarios: [], vacio: false, notas: [...model.notes], sinDatoEtiqueta: '' };
|
||||||
|
const figure = dona(modelo, {}, tema);
|
||||||
|
const unit = model.unit.endsWith('s') ? model.unit : model.unit + 's';
|
||||||
|
for (const trace of figure.data.slice(1)) trace['hovertemplate'] = '%{label}<br>%{customdata[0]} ' + unit + ', %{customdata[1]} % de ' + model.total + '<extra></extra>';
|
||||||
|
figure.layout = { ...figure.layout, title };
|
||||||
|
if (unAnillo) {
|
||||||
|
// Without groups, only the categories' ring around the total, like M21's donut.
|
||||||
|
figure.data = [{ ...figure.data[2], hole: .6 }];
|
||||||
|
figure.layout = { ...figure.layout, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||||
|
text: '<b>' + model.total.toLocaleString('es-MX') + '</b><br>TOTAL', font: { size: 20, color: c2Theme(tema).text } }] };
|
||||||
|
return { figure, highlight: { groups: [], traces: [0], center: { annotation: 0 }, allLabel: 'TOTAL',
|
||||||
|
items: categorias.map((c, i) => ({ id: c.id, label: c.etiqueta, color: c.color, points: [{ trace: 0, index: i }],
|
||||||
|
center: '<b>' + celdas[c.id].n!.toLocaleString('es-MX') + '</b><br>' + c.etiqueta })) } };
|
||||||
|
}
|
||||||
|
return { figure, highlight: donaHighlight(modelo) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buttons for the C2 bars: one per category (bar), and its group highlights all of its bars.
|
||||||
|
export function c2BarsHighlight(model: C2Distribution): FigureHighlight {
|
||||||
|
const items = model.categories.map((c, i) => ({ id: c.id, label: c.label, color: hex(c.color, i),
|
||||||
|
group: c.parentId ? 'group:' + c.parentId : undefined, points: [{ trace: 0, index: i }] }));
|
||||||
|
const groups = model.parents.map(p => {
|
||||||
|
const children = items.filter(c => c.group === p.id);
|
||||||
|
return { id: p.id, label: p.label, color: average(children.map(c => c.color)), points: children.flatMap(c => c.points) };
|
||||||
|
});
|
||||||
|
return { groups, items, traces: [0], allLabel: 'Todas las categorías' };
|
||||||
|
}
|
||||||
@@ -6,28 +6,41 @@
|
|||||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||||
@if (dominio === 'cama') {
|
@if (dominio === 'cama') {
|
||||||
<app-seguimiento-tabla [dominio]="dominio" [active]="active" />
|
<app-seguimiento-tabla [dominio]="dominio" [active]="active" [seleccion]="seleccion" />
|
||||||
} @else if (dominio !== 'cacu') {
|
|
||||||
<p>El seguimiento aún no está disponible.</p>
|
|
||||||
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
|
|
||||||
<table>
|
|
||||||
<thead><tr><th scope="col">Paciente / identificación</th><th scope="col">Proceso o etapa</th><th scope="col">Estado</th><th scope="col">Fecha de referencia</th><th scope="col">Responsable</th><th scope="col">Acciones</th></tr></thead>
|
|
||||||
<tbody><tr><td colspan="6">No hay registros de seguimiento disponibles.</td></tr></tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
} @else {
|
} @else {
|
||||||
<form (ngSubmit)="apply()">
|
<form (ngSubmit)="apply()">
|
||||||
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
||||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||||
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||||
</select></label>
|
</select></label>
|
||||||
<label>Estatus de seguimiento <select name="estatus" [(ngModel)]="draft.estatus">
|
@if (propio) {
|
||||||
<option [ngValue]="undefined">Todos</option>
|
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||||
|
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
|
||||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||||
</select></label>
|
</select></label>
|
||||||
<label>Ordenar por prioridad <select name="prioridad" disabled>
|
}
|
||||||
<option>No disponible</option>
|
@if (dominio === 'tea') {
|
||||||
|
<label>Grupo de edad <select name="grupo_edad" [(ngModel)]="draft.grupo_edad">
|
||||||
|
<option [ngValue]="undefined">Todos</option>
|
||||||
|
@for (g of gruposEdad; track g) { <option [value]="g">{{ g }}</option> }
|
||||||
</select></label>
|
</select></label>
|
||||||
|
<label>Puntaje M-CHAT <select name="mchat" [(ngModel)]="draft.mchat">
|
||||||
|
<option [ngValue]="undefined">Todos</option>
|
||||||
|
@for (r of rangosMchat; track r.codigo) { <option [value]="r.codigo">{{ r.etiqueta }}</option> }
|
||||||
|
</select></label>
|
||||||
|
<label>CSS ADOS-2 <select name="css" [(ngModel)]="draft.css">
|
||||||
|
<option [ngValue]="undefined">Todos</option>
|
||||||
|
@for (r of rangosCss; track r.codigo) { <option [value]="r.codigo">{{ r.etiqueta }}</option> }
|
||||||
|
</select></label>
|
||||||
|
<label>Estado del caso <select name="estado_caso" [(ngModel)]="draft.estado_caso">
|
||||||
|
<option [ngValue]="undefined">Todos</option>
|
||||||
|
@for (e of estadosCaso; track e.codigo) { <option [value]="e.codigo">{{ e.etiqueta }}</option> }
|
||||||
|
</select></label>
|
||||||
|
<label>Tipo de alteración <select name="alteracion" [(ngModel)]="draft.alteracion">
|
||||||
|
<option [ngValue]="undefined">Todas</option>
|
||||||
|
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||||
|
</select></label>
|
||||||
|
}
|
||||||
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></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>
|
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -35,8 +48,47 @@
|
|||||||
@if (status === 'pending') { <p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p> }
|
@if (status === 'pending') { <p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p> }
|
||||||
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
|
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
|
||||||
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
|
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
|
||||||
@if (data; as response) {
|
@if (response; as response) {
|
||||||
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
|
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
|
||||||
|
}
|
||||||
|
@if (teaData; as response) {
|
||||||
|
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
|
||||||
|
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
|
||||||
|
<dl>
|
||||||
|
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
|
||||||
|
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
|
||||||
|
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
|
||||||
|
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
|
||||||
|
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
|
||||||
|
</section>
|
||||||
|
<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 scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estado del caso</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Alteraciones EEG</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@for (item of response.items; track item.id_seudonimo) {
|
||||||
|
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||||
|
<td><button class="row-toggle" type="button" [attr.aria-expanded]="teaAbierto === item.id_seudonimo" [attr.aria-controls]="'tea-detalle-' + item.id_seudonimo"
|
||||||
|
[attr.aria-label]="(teaAbierto === item.id_seudonimo ? 'Ocultar' : 'Ver') + ' resumen del paciente ' + item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||||
|
<span class="chevron" aria-hidden="true"></span>{{ item.id_seudonimo }}</button></td>
|
||||||
|
<td>{{ item.grupo_edad }}</td>
|
||||||
|
<td><span class="estado-caso" [attr.data-estado]="item.estado_caso">{{ etiquetaEstado[item.estado_caso] }}</span>
|
||||||
|
@if (item.pendientes.length) { <small>Falta: {{ item.pendientes.join(', ') }}</small> }</td>
|
||||||
|
<td>{{ item.ultimo_eeg ?? 'No disponible' }}</td>
|
||||||
|
<td>{{ item.mchat ?? 'No disponible' }}</td>
|
||||||
|
<td>{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { <small>Módulo {{ item.modulo_ados2 }}</small> }</td>
|
||||||
|
<td>@if (item.alteraciones_eeg; as eeg) { <span class="eeg" [class.eeg-anormal]="eeg === 'anormal'">{{ eeg === 'anormal' ? 'Anormal' : 'Normal' }}</span> } @else { No disponible }</td></tr>
|
||||||
|
@if (teaAbierto === item.id_seudonimo) {
|
||||||
|
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
|
||||||
|
}
|
||||||
|
} @empty { <tr><td colspan="7">No hay registros para los filtros aplicados.</td></tr> }
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
} @else if (data; as response) {
|
||||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||||
<table>
|
<table>
|
||||||
<caption>Resultados disponibles por paciente</caption>
|
<caption>Resultados disponibles por paciente</caption>
|
||||||
@@ -53,6 +105,8 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
@if (response; as response) {
|
||||||
<nav aria-label="Paginación de seguimiento">
|
<nav aria-label="Paginación de seguimiento">
|
||||||
<button type="button" [disabled]="response.paginacion.page <= 1" (click)="navigate(response.paginacion.page - 1)">Anterior</button>
|
<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>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
|
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
|
||||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
h2 { font-size: 1.5rem; margin-top: 0; }
|
h2 { font-size: 1.25rem; font-weight: 500; margin-top: 0; }
|
||||||
p { color: var(--issste-text-secondary); }
|
p { color: var(--issste-text-secondary); }
|
||||||
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
|
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
|
||||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||||
@@ -15,9 +15,30 @@ caption { text-align: start; padding: 1rem; }
|
|||||||
th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px solid var(--issste-border); }
|
th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px solid var(--issste-border); }
|
||||||
th { background: var(--issste-background); font-weight: 600; }
|
th { background: var(--issste-background); font-weight: 600; }
|
||||||
small { display: block; margin-top: .35rem; }
|
small { display: block; margin-top: .35rem; }
|
||||||
|
.resumen-eeg { margin-bottom: 1rem; padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
|
.resumen-eeg h3 { margin: 0 0 .75rem; font-size: 1.1rem; }
|
||||||
|
.resumen-eeg dl { display: flex; flex-wrap: wrap; gap: 1rem 2rem; margin: 0; }
|
||||||
|
.resumen-eeg dt { color: var(--issste-text-secondary); font-size: .9rem; }
|
||||||
|
.resumen-eeg dd { margin: .2rem 0 0; font-size: 1.5rem; font-weight: 700; }
|
||||||
|
.resumen-eeg .tipo dd { font-size: 1.15rem; font-weight: 600; }
|
||||||
|
.resumen-eeg p { margin: .75rem 0 0; font-size: .85rem; }
|
||||||
|
.estado-caso { font-weight: 600; }
|
||||||
|
.estado-caso[data-estado=en_proceso] { color: #B26A00; }
|
||||||
|
.estado-caso[data-estado=fuera_protocolo] { color: var(--issste-text-secondary); }
|
||||||
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
|
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] { 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]: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; }
|
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 { 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; }
|
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||||
|
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: var(--issste-radius); border: 1px solid var(--issste-border); font-weight: 600; }
|
||||||
|
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
|
||||||
|
tbody tr.tea-row { cursor: pointer; transition: background-color 120ms ease; }
|
||||||
|
tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||||
|
.row-toggle { display: inline-flex; align-items: center; gap: .5rem; min-height: 44px; padding: .35rem .5rem; border: 0; background: transparent;
|
||||||
|
color: var(--issste-text); font: inherit; font-weight: 600; text-align: left; cursor: pointer; }
|
||||||
|
.chevron { width: .5rem; height: .5rem; border-right: 2px solid currentColor; border-bottom: 2px solid currentColor; transform: rotate(-45deg); transition: transform 150ms ease; }
|
||||||
|
.row-toggle[aria-expanded=true] .chevron { transform: rotate(45deg); }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } }
|
||||||
|
tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); }
|
||||||
|
// TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page.
|
||||||
|
|||||||
@@ -7,14 +7,16 @@ import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimient
|
|||||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||||
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
|
|
||||||
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
|
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
|
||||||
import { Dominio } from './indicadores.models';
|
import { Dominio } from './indicadores.models';
|
||||||
import { IndicadoresService } from './indicadores.service';
|
import { IndicadoresService } from './indicadores.service';
|
||||||
|
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||||
|
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||||
|
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicadores-tracking',
|
selector: 'app-indicadores-tracking',
|
||||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, IndicadoresSeguimientoTabla],
|
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla],
|
||||||
providers: [PacienteDetalleState],
|
providers: [PacienteDetalleState],
|
||||||
templateUrl: './indicadores-tracking.html',
|
templateUrl: './indicadores-tracking.html',
|
||||||
styleUrl: './indicadores-tracking.scss',
|
styleUrl: './indicadores-tracking.scss',
|
||||||
@@ -23,8 +25,11 @@ export class IndicadoresTracking implements OnChanges {
|
|||||||
@Input({ required: true }) domainLabel = '';
|
@Input({ required: true }) domainLabel = '';
|
||||||
@Input() dominio: Dominio = 'tea';
|
@Input() dominio: Dominio = 'tea';
|
||||||
@Input() active = false;
|
@Input() active = false;
|
||||||
|
// CaMa: the patients of a curve or a heatmap cell of the analysis, for its follow-up list.
|
||||||
|
@Input() seleccion?: SeleccionSeguimiento;
|
||||||
private readonly service = inject(CacuSeguimientoService);
|
private readonly service = inject(CacuSeguimientoService);
|
||||||
private readonly indicators = inject(IndicadoresService);
|
private readonly indicators = inject(IndicadoresService);
|
||||||
|
private readonly teaService = inject(TeaSeguimientoService);
|
||||||
private readonly destroy = inject(DestroyRef);
|
private readonly destroy = inject(DestroyRef);
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
private readonly injector = inject(Injector);
|
private readonly injector = inject(Injector);
|
||||||
@@ -32,24 +37,38 @@ export class IndicadoresTracking implements OnChanges {
|
|||||||
readonly fichaPacienteAbierta = output<boolean>();
|
readonly fichaPacienteAbierta = output<boolean>();
|
||||||
private controlPaciente?: HTMLElement;
|
private controlPaciente?: HTMLElement;
|
||||||
private readonly requests = new Subject<SeguimientoQuery | null>();
|
private readonly requests = new Subject<SeguimientoQuery | null>();
|
||||||
|
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
|
||||||
private initialized = false;
|
private initialized = false;
|
||||||
private previousDomain?: Dominio;
|
private previousDomain?: Dominio;
|
||||||
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
||||||
message = '';
|
message = '';
|
||||||
data?: SeguimientoResponse;
|
data?: SeguimientoResponse;
|
||||||
|
teaData?: TeaSeguimientoResponse;
|
||||||
|
// One open summary at a time, like an accordion.
|
||||||
|
teaAbierto?: string;
|
||||||
statuses: SeguimientoStatus[] = [];
|
statuses: SeguimientoStatus[] = [];
|
||||||
private metadataLoaded = false;
|
private metadataLoaded = false;
|
||||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
|
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50, filtros: {} };
|
||||||
private applied: SeguimientoQuery = { ...this.draft };
|
private applied: SeguimientoQuery = { ...this.draft };
|
||||||
readonly latestStudy = latestStudy;
|
readonly latestStudy = latestStudy;
|
||||||
|
readonly gruposEdad = GRUPOS_EDAD_TEA;
|
||||||
|
readonly rangosMchat = RANGOS_MCHAT;
|
||||||
|
readonly rangosCss = RANGOS_CSS;
|
||||||
|
readonly etiquetaEstado = ESTADOS_CASO;
|
||||||
|
readonly estadosCaso = Object.entries(ESTADOS_CASO).map(([codigo, etiqueta]) => ({ codigo, etiqueta }));
|
||||||
|
// Kept from the last answer, so the filter doesn't empty while a query is running.
|
||||||
|
tiposAlteracion: { codigo: string; etiqueta: string }[] = [];
|
||||||
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
|
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
|
||||||
|
get response() { return this.dominio === 'tea' ? this.teaData : this.dominio === 'cacu' ? this.data : undefined; }
|
||||||
|
// CaMa's list announces its own filters and columns and is drawn by IndicadoresSeguimientoTabla.
|
||||||
|
get propio() { return this.dominio === 'cacu' || this.dominio === 'tea'; }
|
||||||
constructor() {
|
constructor() {
|
||||||
this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe(
|
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
|
||||||
map(data => ({ data, message: '', status: 'ready' as const })),
|
|
||||||
catchError(error => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
|
|
||||||
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
|
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
|
||||||
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' }))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' });
|
||||||
|
this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe(
|
||||||
|
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
this.status = result.status; this.data = result.data; this.message = result.message;
|
this.status = result.status; this.data = result.data; this.message = result.message;
|
||||||
@@ -67,25 +86,40 @@ export class IndicadoresTracking implements OnChanges {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
this.teaRequests.pipe(switchMap(q => q ? defer(() => this.teaService.consultar(q)).pipe(
|
||||||
|
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||||
|
if (!result) return;
|
||||||
|
this.changeDetector.markForCheck();
|
||||||
|
this.status = result.status; this.teaData = result.data; this.message = result.message; this.teaAbierto = undefined;
|
||||||
|
if (result.data) {
|
||||||
|
const data = result.data;
|
||||||
|
this.tiposAlteracion = data.tipos_alteracion;
|
||||||
|
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||||
|
this.draft = { ...this.applied };
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
ngOnChanges() {
|
ngOnChanges() {
|
||||||
if (this.previousDomain !== this.dominio) {
|
if (this.previousDomain !== this.dominio) {
|
||||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
|
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
|
||||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||||
this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined;
|
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null);
|
||||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
this.data = undefined; this.teaData = undefined;
|
||||||
|
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50, filtros: {} }; this.applied = { ...this.draft };
|
||||||
}
|
}
|
||||||
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
||||||
|
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
|
||||||
}
|
}
|
||||||
private load(q: SeguimientoQuery) {
|
private load(q: SeguimientoQuery) {
|
||||||
if (this.dominio !== 'cacu') return;
|
|
||||||
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
|
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
|
||||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.applied = { ...q }; this.requests.next(q);
|
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||||
|
if (this.dominio === 'tea') this.teaRequests.next(q);
|
||||||
|
else if (this.dominio === 'cacu') this.requests.next(q);
|
||||||
}
|
}
|
||||||
apply() { this.load({ ...this.draft, page: 1 }); }
|
apply() { this.load({ ...this.draft, filtros: Object.fromEntries(Object.entries(this.draft.filtros ?? {}).filter(([, v]) => v)), page: 1 }); }
|
||||||
retry() { this.load(this.applied); }
|
retry() { this.load(this.applied); }
|
||||||
navigate(page: number) {
|
navigate(page: number) {
|
||||||
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
|
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||||
this.load({ ...this.applied, page });
|
this.load({ ...this.applied, page });
|
||||||
}
|
}
|
||||||
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
|
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
|
||||||
@@ -101,6 +135,12 @@ export class IndicadoresTracking implements OnChanges {
|
|||||||
this.pacienteDetalle.abrir(paciente, this.data.corte);
|
this.pacienteDetalle.abrir(paciente, this.data.corte);
|
||||||
this.fichaPacienteAbierta.emit(true);
|
this.fichaPacienteAbierta.emit(true);
|
||||||
}
|
}
|
||||||
|
alternarTea(id: string, evento: Event) {
|
||||||
|
evento.stopPropagation();
|
||||||
|
// Row clicks that land on a control are left to that control.
|
||||||
|
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||||
|
this.teaAbierto = this.teaAbierto === id ? undefined : id;
|
||||||
|
}
|
||||||
volverASeguimiento() {
|
volverASeguimiento() {
|
||||||
this.pacienteDetalle.cerrar();
|
this.pacienteDetalle.cerrar();
|
||||||
this.fichaPacienteAbierta.emit(false);
|
this.fichaPacienteAbierta.emit(false);
|
||||||
|
|||||||
@@ -137,6 +137,8 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
|||||||
const before = cards(), panel = panels()[0], result = panel.result();
|
const before = cards(), panel = panels()[0], result = panel.result();
|
||||||
for (const section of ['seguimiento', 'datos'] as const) {
|
for (const section of ['seguimiento', 'datos'] as const) {
|
||||||
page.changeSection(section); await render();
|
page.changeSection(section); await render();
|
||||||
|
// TEA's Seguimiento loads its patient list; that request is unrelated to the cards.
|
||||||
|
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||||
// Even stale geometry/observer notifications cannot activate hidden cards.
|
// Even stale geometry/observer notifications cannot activate hidden cards.
|
||||||
positions(cards().map(() => [200, 0])); notify(1); await idle();
|
positions(cards().map(() => [200, 0])); notify(1); await idle();
|
||||||
expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true);
|
expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true);
|
||||||
@@ -152,13 +154,13 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
|||||||
const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart');
|
const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||||
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle();
|
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle();
|
||||||
const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
|
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
|
||||||
filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle();
|
filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle();
|
||||||
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
|
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
|
||||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
|
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
|
||||||
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
|
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
|
||||||
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
|
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
|
||||||
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
|
expect(request.request.params.get('periodos')).toBe('2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
|
||||||
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
|
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
|
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
|
||||||
@@ -179,15 +181,16 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
|||||||
cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred');
|
cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred');
|
||||||
positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} });
|
positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} });
|
||||||
});
|
});
|
||||||
it('fijación y búsqueda conservan componentes y descartan callbacks con geometría antigua', async () => {
|
it('fijación y selección conservan componentes y descartan callbacks con geometría antigua', async () => {
|
||||||
await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
|
await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
|
||||||
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
|
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
|
||||||
page.changeSearchQuery('Indicador 3'); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
|
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
|
||||||
observer().emit(target); await idle(); http.expectNone(() => true);
|
observer().emit(target); await idle(); http.expectNone(() => true);
|
||||||
expect(cards()[0]).toBe(before[3]); expect(cards()[1]).toBe(before[4]); expect(cards().every(c => before.includes(c))).toBe(true);
|
// The pinned indicator leads; the other selected one keeps its component.
|
||||||
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
|
expect(cards()).toEqual([before[4], before[3]]);
|
||||||
|
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
|
||||||
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
|
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
|
||||||
expect(cards()[0].selectedFigure).toBe('f');
|
expect(cards()[1].selectedFigure).toBe('f');
|
||||||
});
|
});
|
||||||
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
|
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
|
||||||
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
|
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
|
||||||
@@ -233,6 +236,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
|||||||
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
|
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
|
||||||
for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
|
for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
|
||||||
page.changeSection(section); await idle();
|
page.changeSection(section); await idle();
|
||||||
|
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||||
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
|
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
|
||||||
expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true);
|
expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,8 +16,18 @@ export interface Indicador {
|
|||||||
figuras: string[];
|
figuras: string[];
|
||||||
tipos_periodo: TipoPeriodo[];
|
tipos_periodo: TipoPeriodo[];
|
||||||
filtros?: IndicadorFiltro[];
|
filtros?: IndicadorFiltro[];
|
||||||
|
// Tabs that show it; without this field, all of them.
|
||||||
|
vistas?: string[];
|
||||||
|
// Interactive donut and bars by one stratum, like CaCu's EU7.
|
||||||
|
escenario?: VistaEscenario;
|
||||||
|
// How the breakdown by stratum opens: counts, or each category's share of its stratum.
|
||||||
|
medida_estrato?: 'conteo' | 'porcentaje';
|
||||||
}
|
}
|
||||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
|
// CaMa's stratifiers (brca, clasificacion, estadio, tamano, etapa) break down its quantities of interest.
|
||||||
|
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'clasificacion' | 'estadio' | 'tamano' | 'etapa';
|
||||||
|
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'clasificacion', 'estadio', 'tamano', 'etapa'];
|
||||||
|
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
|
||||||
|
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
|
||||||
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
||||||
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
||||||
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { inject, Injectable } from '@angular/core';
|
import { inject, Injectable } from '@angular/core';
|
||||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
import { map } from 'rxjs';
|
import { map } from 'rxjs';
|
||||||
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
|
import { DatosScope, DIMENSIONES_ESTRATO, DimensionEstrato, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
|
||||||
|
|
||||||
function record(value: unknown): value is Record<string, unknown> {
|
function record(value: unknown): value is Record<string, unknown> {
|
||||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||||
@@ -20,7 +20,9 @@ export class IndicadoresService {
|
|||||||
&& new Set(item['figuras']).size === item['figuras'].length
|
&& new Set(item['figuras']).size === item['figuras'].length
|
||||||
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
|
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
|
||||||
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
|
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
|
||||||
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
|
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length
|
||||||
|
&& (item['escenario'] === undefined || record(item['escenario']) && typeof item['escenario']['etiqueta'] === 'string'
|
||||||
|
&& DIMENSIONES_ESTRATO.includes(item['escenario']['estrato'] as DimensionEstrato)))) {
|
||||||
throw new Error('Respuesta de catálogo inválida');
|
throw new Error('Respuesta de catálogo inválida');
|
||||||
}
|
}
|
||||||
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
|
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
|
||||||
@@ -66,7 +68,7 @@ export class IndicadoresService {
|
|||||||
}
|
}
|
||||||
let params = new HttpParams();
|
let params = new HttpParams();
|
||||||
if (scope.estrato) {
|
if (scope.estrato) {
|
||||||
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
if (!DIMENSIONES_ESTRATO.includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||||
params = params.set('estrato', scope.estrato);
|
params = params.set('estrato', scope.estrato);
|
||||||
}
|
}
|
||||||
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
||||||
|
|||||||
@@ -284,6 +284,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
|
|||||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||||
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
||||||
expect(root.querySelector('tbody button')).toBeNull();
|
expect(root.querySelector('tbody button')).toBeNull();
|
||||||
|
// TEA loads its own list, which has no patient-detail buttons.
|
||||||
|
http.expectOne(r => r.url === '/tea/seguimiento');
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -12,14 +12,14 @@ export interface SeguimientoOpcion { codigo: string; etiqueta: string; }
|
|||||||
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[]; }
|
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[]; }
|
||||||
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoOpcion[]; }
|
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoOpcion[]; }
|
||||||
export interface SeguimientoTablaQuery {
|
export interface SeguimientoTablaQuery {
|
||||||
corte?: string; meses: 1 | 3 | 6 | 12; page: number; page_size: number;
|
corte?: string; meses: MesesVentana; page: number; page_size: number;
|
||||||
// The filters the list announces in `filtros_disponibles`, by key; an empty value is no filter.
|
// The filters the list announces in `filtros_disponibles`, by key; an empty value is no filter.
|
||||||
filtros?: Record<string, string | undefined>;
|
filtros?: Record<string, string | undefined>;
|
||||||
}
|
}
|
||||||
export interface SeguimientoTablaResponse {
|
export interface SeguimientoTablaResponse {
|
||||||
simulado: true;
|
simulado: true;
|
||||||
corte: string;
|
corte: string;
|
||||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
ventana: { meses: MesesVentana; desde: string; hasta: string };
|
||||||
filtros: Record<string, string | null>;
|
filtros: Record<string, string | null>;
|
||||||
filtros_disponibles: SeguimientoFiltro[];
|
filtros_disponibles: SeguimientoFiltro[];
|
||||||
columnas: SeguimientoColumna[];
|
columnas: SeguimientoColumna[];
|
||||||
@@ -29,7 +29,9 @@ export interface SeguimientoTablaResponse {
|
|||||||
}
|
}
|
||||||
export class SeguimientoInvalido extends Error {}
|
export class SeguimientoInvalido extends Error {}
|
||||||
|
|
||||||
export const MESES_VENTANA = [1, 3, 6, 12] as const;
|
// 0 is the whole list, without a time window: what a curve or a heatmap cell of the analysis opens.
|
||||||
|
export const MESES_VENTANA = [1, 3, 6, 12, 0] as const;
|
||||||
|
export type MesesVentana = typeof MESES_VENTANA[number];
|
||||||
export const PAGE_SIZE_MAX = 200;
|
export const PAGE_SIZE_MAX = 200;
|
||||||
const RESERVADAS = ['meses', 'page', 'page_size', 'corte'];
|
const RESERVADAS = ['meses', 'page', 'page_size', 'corte'];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
@if (status() === 'loading') { <p role="status">Cargando resumen del paciente…</p> }
|
||||||
|
@if (status() === 'error') {
|
||||||
|
<p role="alert">No se pudo cargar el resumen del paciente.</p>
|
||||||
|
<button type="button" (click)="load()">Reintentar resumen</button>
|
||||||
|
}
|
||||||
|
@if (status() === 'ready' && detalle(); as d) {
|
||||||
|
<div class="resumen" [class.sin-eeg]="!d.eeg">
|
||||||
|
<section class="panel ados" aria-label="Resumen ADOS-2">
|
||||||
|
<h3>ADOS-2</h3>
|
||||||
|
@if (d.ados2; as a) {
|
||||||
|
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||||
|
<div class="headline">
|
||||||
|
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
|
||||||
|
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||||
|
</div>
|
||||||
|
@for (dom of a.dominios; track dom.codigo) {
|
||||||
|
<div class="dominio">
|
||||||
|
<span>{{ dom.etiqueta }} ({{ dom.codigo }})</span><span>{{ dom.puntaje }} / {{ dom.maximo }}</span>
|
||||||
|
<span class="bar" aria-hidden="true"><span [style.width.%]="pct(dom.puntaje, dom.maximo)"></span></span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<details>
|
||||||
|
<summary>Puntajes por reactivo</summary>
|
||||||
|
<table class="reactivos">
|
||||||
|
<thead><tr><th scope="col">Reactivo</th><th scope="col">Puntaje</th><th scope="col">Algoritmo</th></tr></thead>
|
||||||
|
@for (dom of a.dominios; track dom.codigo) {
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="rowgroup" colspan="3">{{ dom.etiqueta }}</th></tr>
|
||||||
|
@for (r of dom.reactivos; track r.codigo) {
|
||||||
|
<tr><td>{{ r.codigo }} · {{ r.etiqueta }}</td><td>{{ r.puntaje }}</td><td>{{ r.puntaje_algoritmo }}</td></tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
}
|
||||||
|
</table>
|
||||||
|
</details>
|
||||||
|
} @else { <p>Sin evaluación ADOS-2 registrada.</p> }
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel calidad" aria-label="Calidad del EEG">
|
||||||
|
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3>
|
||||||
|
@if (d.eeg; as e) {
|
||||||
|
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
|
||||||
|
<div class="headline">
|
||||||
|
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
|
||||||
|
<small>La calificación general es la peor de sus criterios.</small>
|
||||||
|
</div>
|
||||||
|
<dl>
|
||||||
|
@for (c of e.criterios_calidad; track c.codigo) {
|
||||||
|
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
} @else { <p>Sin EEG registrado.</p> }
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (d.eeg; as e) {
|
||||||
|
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
|
||||||
|
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
|
||||||
|
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||||
|
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
|
||||||
|
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||||
|
<ul class="metricas">
|
||||||
|
@for (m of e.alteraciones; track m.codigo) {
|
||||||
|
<li [attr.data-estado]="m.estado">
|
||||||
|
<div class="metrica">
|
||||||
|
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
|
||||||
|
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||||
|
<span class="estado">{{ estado[m.estado] }}</span>
|
||||||
|
</div>
|
||||||
|
@if (m.valor !== null) {
|
||||||
|
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
|
||||||
|
} @else {
|
||||||
|
<p class="valor">Sin registro de sueño en el estudio.</p>
|
||||||
|
}
|
||||||
|
@if (m.efectos.length) {
|
||||||
|
<p class="efectos-titulo">Posibles efectos asociados</p>
|
||||||
|
<ul class="efectos">
|
||||||
|
@for (efecto of m.efectos; track efecto) { <li>{{ efecto }}</li> }
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@if (mapaActual(e); as mapa) {
|
||||||
|
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
|
||||||
|
<h3>Zonas más afectadas</h3>
|
||||||
|
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||||
|
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||||
|
@if (figura) {
|
||||||
|
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'260px'"
|
||||||
|
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
|
||||||
|
}
|
||||||
|
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
|
||||||
|
@for (r of mapa.regiones; track r.codigo) {
|
||||||
|
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
</section></div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
:host { display: block; container-type: inline-size; }
|
||||||
|
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; }
|
||||||
|
.panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); }
|
||||||
|
h3 { margin: 0 0 .15rem; font-size: 1rem; }
|
||||||
|
.meta { margin: 0 0 .5rem; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||||
|
.headline { display: flex; align-items: center; gap: .75rem; margin-bottom: .5rem; font-size: .9rem; }
|
||||||
|
.headline small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); }
|
||||||
|
.css { display: inline-flex; flex-direction: column; align-items: center; justify-content: center; min-width: 3.75rem; padding: .3rem .4rem;
|
||||||
|
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; }
|
||||||
|
.css small { margin: 0; font-size: .7rem; font-weight: 400; }
|
||||||
|
.css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; }
|
||||||
|
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; }
|
||||||
|
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); }
|
||||||
|
.css[data-calidad] { flex: none; white-space: nowrap; }
|
||||||
|
dd[data-calidad=malo] { color: #B3261E; }
|
||||||
|
// The button's area covers its whole card, so the card is clickable without nesting the effects list in a button.
|
||||||
|
button.nombre { margin: 0; min-height: 0; padding: 0; border: 0; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; }
|
||||||
|
button.nombre::after { content: ''; position: absolute; inset: 0; border-radius: inherit; }
|
||||||
|
button.nombre:disabled { cursor: default; }
|
||||||
|
button.nombre:focus-visible { outline: none; }
|
||||||
|
button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
|
.leyenda-mapa { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; margin: .25rem 0; font-size: .8rem; }
|
||||||
|
.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; }
|
||||||
|
.leyenda-mapa .azul { background: #2166AC; }
|
||||||
|
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
|
||||||
|
dd[data-calidad=aceptable] { color: #B26A00; }
|
||||||
|
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
|
||||||
|
.bar { grid-column: 1 / -1; height: .375rem; border-radius: var(--issste-radius); background: var(--issste-border); overflow: hidden; }
|
||||||
|
.bar span { display: block; height: 100%; background: var(--issste-text); }
|
||||||
|
details { margin-top: .5rem; }
|
||||||
|
summary { cursor: pointer; font-weight: 600; font-size: .9rem; min-height: 44px; display: flex; align-items: center; gap: .5rem; list-style: none; }
|
||||||
|
summary::-webkit-details-marker { display: none; }
|
||||||
|
// A right-pointing triangle that turns down when the details are open.
|
||||||
|
summary::before { content: ''; flex: none; border-block: .35rem solid transparent; border-inline-start: .5rem solid currentColor; transition: transform 150ms ease; }
|
||||||
|
details[open] > summary::before { transform: rotate(90deg); }
|
||||||
|
@media (prefers-reduced-motion: reduce) { summary::before { transition: none; } }
|
||||||
|
.reactivos { width: 100%; min-width: 0; font-size: .85rem; border-collapse: collapse; }
|
||||||
|
.reactivos th, .reactivos td { padding: .25rem .4rem; border-top: 1px solid var(--issste-border); text-align: start; }
|
||||||
|
.reactivos td:not(:first-child), .reactivos thead th:not(:first-child) { text-align: end; white-space: nowrap; }
|
||||||
|
.reactivos tbody th { background: var(--issste-background); }
|
||||||
|
dl { display: grid; grid-template-columns: 1fr auto; gap: .25rem 1rem; margin: 0; font-size: .85rem; }
|
||||||
|
dt { color: var(--issste-text-secondary); } dd { margin: 0; text-align: end; font-weight: 600; }
|
||||||
|
.regiones { margin: .25rem 0 0; padding-inline-start: 1.25rem; font-size: .85rem; }
|
||||||
|
.regiones li { padding: .1rem 0; }
|
||||||
|
.regiones li span:last-child { float: inline-end; font-variant-numeric: tabular-nums; }
|
||||||
|
.regiones .destacada { font-weight: 700; }
|
||||||
|
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: var(--issste-radius);
|
||||||
|
font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; }
|
||||||
|
.sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; }
|
||||||
|
.metricas, .efectos { margin: 0; padding: 0; list-style: none; }
|
||||||
|
// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it.
|
||||||
|
.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; }
|
||||||
|
.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; }
|
||||||
|
.marco-mapa { min-width: 0; overflow: hidden; }
|
||||||
|
.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; }
|
||||||
|
.mapa h3 { margin-top: 0; }
|
||||||
|
@keyframes aparecer { from { opacity: 0; } }
|
||||||
|
@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } }
|
||||||
|
@container zona (max-width: 42rem) { .mapa { width: 100cqw; } }
|
||||||
|
@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } }
|
||||||
|
.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; }
|
||||||
|
.metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; }
|
||||||
|
.metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); }
|
||||||
|
.metricas > li:has(button[aria-expanded=true]) { border-color: var(--issste-accent); background: color-mix(in srgb, var(--issste-accent) 12%, transparent); }
|
||||||
|
.metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; }
|
||||||
|
.metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; }
|
||||||
|
li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; }
|
||||||
|
li[data-estado=normal] .estado { color: var(--issste-text-secondary); font-weight: 400; }
|
||||||
|
li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font-weight: 400; font-style: italic; }
|
||||||
|
.valor { margin: .1rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); font-variant-numeric: tabular-nums; }
|
||||||
|
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
|
||||||
|
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; }
|
||||||
|
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core';
|
||||||
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { PlotlyFigure } from './indicadores.models';
|
||||||
|
import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||||
|
|
||||||
|
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
|
||||||
|
// ADOS-2 calibrated severity score ranges.
|
||||||
|
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
|
||||||
|
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Bueno', aceptable: 'Aceptable', malo: 'Malo' };
|
||||||
|
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
|
||||||
|
const INK = '#081839';
|
||||||
|
|
||||||
|
// Shape paths have no arcs: the hole is a polygon, wound against the frame so it stays empty under either fill rule.
|
||||||
|
const HOLE = Array.from({ length: 96 }, (_, i) => -2 * Math.PI * i / 96)
|
||||||
|
.map((a, i) => `${i ? 'L' : 'M'} ${Math.cos(a).toFixed(4)} ${Math.sin(a).toFixed(4)}`).join(' ');
|
||||||
|
// A frame with a round hole hides the map outside the head, in the colour behind the map; then the head outline, nose and ears.
|
||||||
|
const headShapes = (fondo: string) => [
|
||||||
|
{ type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: fondo, line: { width: 0 } },
|
||||||
|
{ type: 'circle', xref: 'x', yref: 'y', x0: -1, y0: -1, x1: 1, y1: 1, line: { color: INK, width: 2 } },
|
||||||
|
{ type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line: { color: INK, width: 2 } },
|
||||||
|
{ type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line: { color: INK, width: 2 } },
|
||||||
|
{ type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line: { color: INK, width: 2 } },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): PlotlyFigure {
|
||||||
|
const m = { ...eeg.ejes_mapa, z: mapa.z };
|
||||||
|
return {
|
||||||
|
data: [
|
||||||
|
{ type: 'contour', x: m.x, y: m.y, z: m.z, zmin: -3, zmax: 3, zmid: 0, colorscale: 'RdBu', connectgaps: false,
|
||||||
|
contours: { coloring: 'heatmap', showlines: true }, line: { width: .5, color: 'rgba(8,24,57,.3)' },
|
||||||
|
colorbar: { title: { text: 'z', side: 'top' }, thickness: 12, len: .8 }, hovertemplate: 'z = %{z:.2f}<extra></extra>' },
|
||||||
|
{ type: 'scatter', mode: 'markers+text', x: m.electrodos.map(e => e.x), y: m.electrodos.map(e => e.y), text: m.electrodos.map(e => e.nombre),
|
||||||
|
textposition: 'top center', textfont: { size: 9, color: INK }, marker: { size: 5, color: INK }, hoverinfo: 'text', showlegend: false },
|
||||||
|
],
|
||||||
|
layout: {
|
||||||
|
margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: headShapes(fondo),
|
||||||
|
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
|
||||||
|
xaxis: { visible: false, range: [-1.2, 1.2], fixedrange: true },
|
||||||
|
yaxis: { visible: false, range: [-1.15, 1.2], scaleanchor: 'x', fixedrange: true },
|
||||||
|
},
|
||||||
|
config: { displayModeBar: false },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-tea-paciente-resumen',
|
||||||
|
imports: [PlotlyChart],
|
||||||
|
templateUrl: './tea-paciente-resumen.html',
|
||||||
|
styleUrl: './tea-paciente-resumen.scss',
|
||||||
|
})
|
||||||
|
export class TeaPacienteResumen implements OnInit {
|
||||||
|
@Input({ required: true }) id = '';
|
||||||
|
private readonly service = inject(TeaSeguimientoService);
|
||||||
|
private readonly destroy = inject(DestroyRef);
|
||||||
|
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||||
|
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
|
||||||
|
figura?: PlotlyFigure;
|
||||||
|
private mapaElegido?: string;
|
||||||
|
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||||
|
// The first solid background around this component: the map has no box of its own.
|
||||||
|
private fondo() {
|
||||||
|
for (let e: HTMLElement | null = this.elemento.nativeElement; e; e = e.parentElement) {
|
||||||
|
const color = getComputedStyle(e).backgroundColor;
|
||||||
|
if (/^rgb\(/.test(color)) return color;
|
||||||
|
}
|
||||||
|
return '#FFFFFF';
|
||||||
|
}
|
||||||
|
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||||||
|
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||||
|
// The chosen card closes the map again, and the cards take the whole space back.
|
||||||
|
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo);
|
||||||
|
this.mapaElegido = mapa?.codigo;
|
||||||
|
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||||
|
}
|
||||||
|
readonly clasificacion = CLASIFICACION;
|
||||||
|
readonly nivelCss = NIVEL_CSS;
|
||||||
|
readonly calidad = CALIDAD;
|
||||||
|
readonly estado = ESTADO;
|
||||||
|
ngOnInit() { this.load(); }
|
||||||
|
load() {
|
||||||
|
this.status.set('loading');
|
||||||
|
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||||
|
next: d => {
|
||||||
|
// Opens on the first altered metric, or on the first one if none is altered.
|
||||||
|
const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0];
|
||||||
|
this.mapaElegido = inicial?.codigo;
|
||||||
|
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined;
|
||||||
|
this.detalle.set(d); this.status.set('ready');
|
||||||
|
},
|
||||||
|
error: () => this.status.set('error'),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
|
||||||
|
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { signal } from '@angular/core';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||||
|
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||||
|
|
||||||
|
type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record<string, number> };
|
||||||
|
function panel(id: string, result: Result) {
|
||||||
|
return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType<typeof signal<Result>>; retry: ReturnType<typeof vi.fn> };
|
||||||
|
}
|
||||||
|
const listo = (value: string | number, period = '2025-S2'): Result => ({ state: 'Disponible', value, period });
|
||||||
|
|
||||||
|
describe('Resumen TEA por periodo', () => {
|
||||||
|
function render(paneles: IndicadorKpiPanel[]) {
|
||||||
|
const fixture = TestBed.createComponent(TeaResumenPeriodo);
|
||||||
|
fixture.componentRef.setInput('periodo', '2025-S2'); fixture.componentRef.setInput('paneles', paneles);
|
||||||
|
fixture.detectChanges();
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { COMPLETO: 60, EN_PROCESO: 25, FUERA_PROTOCOLO: 15 } }), panel('M24_confirmacion_diagnostico', listo('86.5')),
|
||||||
|
panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')),
|
||||||
|
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))];
|
||||||
|
|
||||||
|
it('redacta el párrafo con cada población y resalta los valores', () => {
|
||||||
|
const root: HTMLElement = render(completos()).nativeElement;
|
||||||
|
const text = root.textContent!.replace(/\s+/g, ' ');
|
||||||
|
expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 casos iniciados hasta entonces, 60 están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG), 25 siguen en proceso y 15 quedaron fuera del protocolo.');
|
||||||
|
expect(text).toContain('De los pacientes con nota médica, 86.5 % tuvo diagnóstico positivo de TEA (CIE-10 F84.0).');
|
||||||
|
expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.');
|
||||||
|
expect(text).toContain('De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), 71.9 % tenían EEG y 28.1 % no lo tenían.');
|
||||||
|
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||||
|
.toEqual(['2025-S2', '100', '60', '25', '15', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']);
|
||||||
|
expect(root.querySelector('button')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||||
|
const paneles = completos();
|
||||||
|
paneles[1].result.set({ state: 'Dato oculto por tamaño' });
|
||||||
|
paneles[2].result.set(listo(30, '2025-S1'));
|
||||||
|
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M22_diagnosticados_sin_eeg')).nativeElement;
|
||||||
|
const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato'));
|
||||||
|
expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']);
|
||||||
|
expect(root.textContent).not.toContain('30 días');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||||
|
const paneles = completos();
|
||||||
|
paneles[0].result.set({ state: 'Cargando…', loading: true });
|
||||||
|
paneles[3].result.set({ state: 'Error de consulta' });
|
||||||
|
const fixture = render(paneles);
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(root.querySelector('article')!.getAttribute('aria-busy')).toBe('true');
|
||||||
|
root.querySelector<HTMLButtonElement>('button')!.click();
|
||||||
|
expect(paneles[3].retry).toHaveBeenCalledOnce();
|
||||||
|
expect(paneles[0].retry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { NgTemplateOutlet } from '@angular/common';
|
||||||
|
import { Component, Input } from '@angular/core';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||||
|
|
||||||
|
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
|
||||||
|
|
||||||
|
// TEA summary for one explicit period. It reads the results of the (hidden) KPI panels, so the
|
||||||
|
// requests, contract checks and suppression rules stay those of the cards. Each sentence names
|
||||||
|
// its own population: M28, M24, M25 and M21/M22 do not count the same patients.
|
||||||
|
@Component({
|
||||||
|
selector: 'app-tea-resumen-periodo',
|
||||||
|
imports: [MatButtonModule, NgTemplateOutlet],
|
||||||
|
template: `
|
||||||
|
<article class="resumen" [attr.aria-busy]="cargando">
|
||||||
|
<p>
|
||||||
|
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, de los <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> casos iniciados hasta entonces,
|
||||||
|
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso('COMPLETO') }" /> están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG),
|
||||||
|
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso('EN_PROCESO') }" /> siguen en proceso y <ng-container *ngTemplateOutlet="dato; context: { $implicit: caso('FUERA_PROTOCOLO') }" /> quedaron fuera del protocolo.
|
||||||
|
De los pacientes con nota médica, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
|
||||||
|
tuvo diagnóstico positivo de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" />, de ADOS-2 a diagnóstico, de
|
||||||
|
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" />, y en total, de M-CHAT a diagnóstico, de
|
||||||
|
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||||
|
De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M21_diagnosticados_con_eeg', ' %') }" />
|
||||||
|
tenían EEG y <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M22_diagnosticados_sin_eeg', ' %') }" /> no lo tenían.
|
||||||
|
</p>
|
||||||
|
@if (conError.length) {
|
||||||
|
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||||
|
}
|
||||||
|
</article>
|
||||||
|
<ng-template #dato let-v>
|
||||||
|
<span class="dato" [class.listo]="v.estado === 'listo'" [class.sin-dato]="v.estado === 'sin_dato'" [attr.title]="v.detalle ?? null">{{ v.texto }}@if (v.detalle) {<span class="visually-hidden"> ({{ v.detalle }})</span>}</span>
|
||||||
|
</ng-template>
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host { display: block; min-width: 0; }
|
||||||
|
.resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||||
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
|
p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; }
|
||||||
|
.dato { display: inline-block; padding: 0 .5em; border-radius: var(--issste-radius); line-height: 1.6; font-weight: 700; white-space: nowrap;
|
||||||
|
background: var(--issste-background); border: 1px dashed var(--issste-border); color: var(--issste-text-secondary); }
|
||||||
|
.dato.listo { background: color-mix(in srgb, var(--issste-accent) 22%, var(--issste-surface)); border: 1px solid var(--issste-accent); color: var(--issste-text); }
|
||||||
|
.dato.sin-dato { font-weight: 400; font-style: italic; }
|
||||||
|
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||||
|
button { margin-top: var(--issste-space-4); }
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class TeaResumenPeriodo {
|
||||||
|
@Input({ required: true }) periodo!: string;
|
||||||
|
@Input({ required: true }) paneles: readonly IndicadorKpiPanel[] = [];
|
||||||
|
// Panels render after this paragraph, so on their first pass their inputs are not set yet.
|
||||||
|
private panel(id: string) { return this.paneles.find(p => p.definition?.id === id); }
|
||||||
|
valor(id: string, sufijo: string): Valor {
|
||||||
|
const result = this.panel(id)?.result();
|
||||||
|
if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' };
|
||||||
|
if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' };
|
||||||
|
// Never show a value from another period in a sentence about this one.
|
||||||
|
if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo)
|
||||||
|
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
|
||||||
|
return { texto: result.value + sufijo, estado: 'listo' };
|
||||||
|
}
|
||||||
|
// One status of M28, under the same rules as valor().
|
||||||
|
caso(categoria: string): Valor {
|
||||||
|
const base = this.valor('M28_casos_por_estado', '');
|
||||||
|
if (base.estado !== 'listo') return base;
|
||||||
|
const n = this.panel('M28_casos_por_estado')?.result().categorias?.[categoria];
|
||||||
|
return n === undefined ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Estado no publicado' } : { texto: String(n), estado: 'listo' };
|
||||||
|
}
|
||||||
|
get cargando() { return this.paneles.some(p => p.result().loading); }
|
||||||
|
get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); }
|
||||||
|
reintentar() { this.conError.forEach(p => p.retry()); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import { inject, Injectable } from '@angular/core';
|
||||||
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
|
import { map } from 'rxjs';
|
||||||
|
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||||
|
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||||
|
|
||||||
|
export type AlteracionesEeg = 'normal' | 'anormal';
|
||||||
|
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
|
||||||
|
export interface TeaSeguimientoPaciente {
|
||||||
|
id_seudonimo: string;
|
||||||
|
grupo_edad: string;
|
||||||
|
ultimo_eeg: string | null;
|
||||||
|
mchat: number | null;
|
||||||
|
css_ados2: number | null;
|
||||||
|
alteraciones_eeg: AlteracionesEeg | null;
|
||||||
|
modulo_ados2: string | null;
|
||||||
|
estado_caso: EstadoCaso;
|
||||||
|
// What a case in process still lacks.
|
||||||
|
pendientes: string[];
|
||||||
|
// Codes of the alterations found.
|
||||||
|
alteraciones: string[];
|
||||||
|
}
|
||||||
|
export interface TeaResumenEeg {
|
||||||
|
normales: number; anormales: number; sin_eeg: number;
|
||||||
|
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
|
||||||
|
}
|
||||||
|
export interface TeaSeguimientoResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
|
||||||
|
filtros: { alteraciones_eeg: AlteracionesEeg | null };
|
||||||
|
items: TeaSeguimientoPaciente[];
|
||||||
|
tipos_alteracion: { codigo: string; etiqueta: string }[];
|
||||||
|
// Of every patient that matches the filters, not only this page's.
|
||||||
|
resumen_eeg: TeaResumenEeg;
|
||||||
|
}
|
||||||
|
export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: number; puntaje_algoritmo: number }
|
||||||
|
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
|
||||||
|
export interface TeaAdos2 {
|
||||||
|
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
|
||||||
|
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||||
|
}
|
||||||
|
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||||||
|
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
|
||||||
|
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo';
|
||||||
|
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
|
||||||
|
export interface TeaEegAlteracion {
|
||||||
|
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number };
|
||||||
|
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
|
||||||
|
}
|
||||||
|
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
|
||||||
|
export interface TeaEeg {
|
||||||
|
fecha: string; duracion_min: number; canales: number;
|
||||||
|
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers.
|
||||||
|
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[];
|
||||||
|
alteraciones: TeaEegAlteracion[];
|
||||||
|
// One map per alteration that could be evaluated, on shared axes.
|
||||||
|
mapas: TeaEegMapa[];
|
||||||
|
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
|
||||||
|
}
|
||||||
|
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
|
||||||
|
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
|
||||||
|
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
|
||||||
|
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
|
||||||
|
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
|
||||||
|
export const RANGOS_MCHAT = [
|
||||||
|
{ codigo: 'bajo', etiqueta: 'Riesgo bajo (0–2)', min: 0, max: 2 },
|
||||||
|
{ codigo: 'medio', etiqueta: 'Riesgo medio (3–7)', min: 3, max: 7 },
|
||||||
|
{ codigo: 'alto', etiqueta: 'Riesgo alto (8–20)', min: 8, max: 20 },
|
||||||
|
];
|
||||||
|
export const RANGOS_CSS = [
|
||||||
|
{ codigo: 'minimo', etiqueta: 'Evidencia mínima o nula (1–2)', min: 1, max: 2 },
|
||||||
|
{ codigo: 'bajo', etiqueta: 'Nivel bajo (3–4)', min: 3, max: 4 },
|
||||||
|
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
|
||||||
|
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
|
||||||
|
];
|
||||||
|
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
|
||||||
|
|
||||||
|
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
|
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||||
|
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
|
||||||
|
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
|
||||||
|
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
|
||||||
|
function validResumenEeg(r: unknown): boolean {
|
||||||
|
return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
|
||||||
|
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
|
||||||
|
}
|
||||||
|
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
|
||||||
|
// Same rule as CaCu: demonstration records only.
|
||||||
|
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||||
|
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||||
|
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
|
||||||
|
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||||
|
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|
||||||
|
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||||
|
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
|
||||||
|
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
|
||||||
|
&& (item['ultimo_eeg'] === null || isoDate(item['ultimo_eeg']))
|
||||||
|
&& score(item['mchat'], 0, 20) && score(item['css_ados2'], 1, 10)
|
||||||
|
&& eeg(item['alteraciones_eeg']) && (item['modulo_ados2'] === null || typeof item['modulo_ados2'] === 'string')
|
||||||
|
&& Object.hasOwn(ESTADOS_CASO, item['estado_caso'] as string) && textos(item['pendientes']) && textos(item['alteraciones']))
|
||||||
|
|| !Array.isArray(v['tipos_alteracion']) || !v['tipos_alteracion'].every(t => record(t) && typeof t['codigo'] === 'string' && typeof t['etiqueta'] === 'string')
|
||||||
|
|| !validResumenEeg(v['resumen_eeg']))
|
||||||
|
throw new Error('Respuesta de seguimiento inválida');
|
||||||
|
return v as unknown as TeaSeguimientoResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||||
|
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
|
||||||
|
function validAdos(a: unknown): boolean {
|
||||||
|
if (a === null) return true;
|
||||||
|
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|
||||||
|
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
|
||||||
|
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
|
||||||
|
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||||||
|
const dominios = a['dominios'] as unknown[];
|
||||||
|
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
|
||||||
|
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2))
|
||||||
|
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
|
||||||
|
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
|
||||||
|
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||||||
|
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||||||
|
}
|
||||||
|
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
|
||||||
|
function validAlteracion(a: unknown): boolean {
|
||||||
|
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|
||||||
|
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
|
||||||
|
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
|
||||||
|
const estado = a['estado'];
|
||||||
|
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
|
||||||
|
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||||||
|
}
|
||||||
|
function validEeg(e: unknown): boolean {
|
||||||
|
if (e === null) return true;
|
||||||
|
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
|
||||||
|
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|
||||||
|
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
|
||||||
|
&& integer(c['valor']) && (c['unidad'] !== 'canales' || (c['valor'] as number) <= (e['canales'] as number)))) return false;
|
||||||
|
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
|
||||||
|
const ejes = e['ejes_mapa'];
|
||||||
|
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
|
||||||
|
const x = ejes['x'], y = ejes['y'];
|
||||||
|
return x.every(finite) && y.every(finite)
|
||||||
|
&& Array.isArray(ejes['electrodos']) && ejes['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y']))
|
||||||
|
&& e['mapas'].every(m => record(m) && text(m['codigo']) && text(m['metrica']) && Array.isArray(m['z']) && m['z'].length === y.length
|
||||||
|
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
|
||||||
|
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
|
||||||
|
}
|
||||||
|
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
|
||||||
|
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||||
|
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
|
||||||
|
throw new Error('Resumen del paciente inválido');
|
||||||
|
return v as unknown as TeaPacienteDetalle;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({ providedIn: 'root' })
|
||||||
|
export class TeaSeguimientoService {
|
||||||
|
private readonly http = inject(HttpClient);
|
||||||
|
// `estatus` carries the EEG filter so the shared form and query work for both domains.
|
||||||
|
consultar(query: SeguimientoQuery) {
|
||||||
|
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||||||
|
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||||
|
if (query.corte) params = params.set('corte', query.corte);
|
||||||
|
if (query.estatus) params = params.set('alteraciones_eeg', query.estatus);
|
||||||
|
if (query.grupo_edad) params = params.set('grupo_edad', query.grupo_edad);
|
||||||
|
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
|
||||||
|
if (mchat) params = params.set('mchat_min', mchat.min).set('mchat_max', mchat.max);
|
||||||
|
if (css) params = params.set('css_min', css.min).set('css_max', css.max);
|
||||||
|
if (query.estado_caso) params = params.set('estado_caso', query.estado_caso);
|
||||||
|
if (query.alteracion) params = params.set('alteracion', query.alteracion);
|
||||||
|
return this.http.get<unknown>('/tea/seguimiento', { params }).pipe(map(teaSeguimientoResponse));
|
||||||
|
}
|
||||||
|
detalle(id: string) {
|
||||||
|
return this.http.get<unknown>(`/tea/seguimiento/${encodeURIComponent(id)}`).pipe(map(v => teaPacienteDetalle(v, id)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service';
|
||||||
|
import { mapaFigure } from './tea-paciente-resumen';
|
||||||
|
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||||
|
import { IndicadoresTracking } from './indicadores-tracking';
|
||||||
|
|
||||||
|
const item = { id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal',
|
||||||
|
modulo_ados2: '2', estado_caso: 'en_proceso', pendientes: ['Neuropediatría'], alteraciones: ['ritmo_posterior'] };
|
||||||
|
const data = {
|
||||||
|
simulado: true, corte: '2026-09-30', ventana: { meses: 3, desde: '2026-07-01', hasta: '2026-09-30' }, filtros: { alteraciones_eeg: null },
|
||||||
|
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
|
||||||
|
items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }],
|
||||||
|
tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }],
|
||||||
|
resumen_eeg: { normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
|
||||||
|
};
|
||||||
|
const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) });
|
||||||
|
const metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra });
|
||||||
|
const alteraciones = [
|
||||||
|
metrica('ritmo_posterior', 'Ritmo posterior', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Ritmo más lento de lo esperado para la edad.'] }),
|
||||||
|
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable' }),
|
||||||
|
metrica('husos_sueno_n3', 'Husos de sueño N3', { valor: 1.4, valor_z: 0.2, estado: 'normal' }),
|
||||||
|
metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }),
|
||||||
|
metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }),
|
||||||
|
];
|
||||||
|
const mapa = (codigo: string, metrica: string, region: string) => ({ codigo, metrica, z: [[null, 1, null], [0, 2.1, 0], [null, 1, null]], regiones: [{ codigo: 'r', etiqueta: region, valor_z: 2.1 }] });
|
||||||
|
const detalle = {
|
||||||
|
simulado: true, id_seudonimo: 'T-0001', grupo_edad: '16-23 meses',
|
||||||
|
ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo',
|
||||||
|
dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] },
|
||||||
|
{ codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] },
|
||||||
|
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable',
|
||||||
|
criterios_calidad: [{ codigo: 'amplitud', etiqueta: 'Canales con amplitud extrema', valor: 1, unidad: 'canales', nivel: 'bueno' }, { codigo: 'linea', etiqueta: 'Ruido de la línea eléctrica', valor: 8, unidad: 'dB', nivel: 'aceptable' }],
|
||||||
|
alteraciones,
|
||||||
|
mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')],
|
||||||
|
ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } },
|
||||||
|
};
|
||||||
|
const anormal = { ...data, filtros: { alteraciones_eeg: 'anormal' }, paginacion: { ...data.paginacion, total_items: 1 }, items: [item] };
|
||||||
|
|
||||||
|
describe('Seguimiento TEA', () => {
|
||||||
|
let http: HttpTestingController;
|
||||||
|
beforeEach(() => {
|
||||||
|
const runtime = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) } };
|
||||||
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||||
|
http = TestBed.inject(HttpTestingController);
|
||||||
|
});
|
||||||
|
function open() {
|
||||||
|
const fixture = TestBed.createComponent(IndicadoresTracking);
|
||||||
|
fixture.componentRef.setInput('domainLabel', 'TEA'); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('active', true);
|
||||||
|
fixture.detectChanges();
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
const request = () => http.expectOne(r => r.url === '/tea/seguimiento');
|
||||||
|
it('muestra las siete columnas y los valores ausentes como No disponible', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(data); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(Array.from(root.querySelectorAll('thead th')).map(th => th.textContent)).toEqual(
|
||||||
|
['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']);
|
||||||
|
const rows = root.querySelectorAll('tbody tr');
|
||||||
|
expect(rows).toHaveLength(2);
|
||||||
|
expect(rows[0].textContent).toContain('Anormal');
|
||||||
|
expect(rows[1].querySelectorAll('td')[3].textContent).toContain('No disponible');
|
||||||
|
expect(root.textContent).toContain('Página 1 de 1, 2 registros');
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('usa los filtros de CaCu con Alteraciones EEG en lugar del estatus', () => {
|
||||||
|
const fixture = open();
|
||||||
|
const first = request();
|
||||||
|
expect(first.request.params.get('meses')).toBe('3');
|
||||||
|
expect(first.request.params.has('alteraciones_eeg')).toBe(false);
|
||||||
|
first.flush(data); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(root.querySelector('input[type=date]')).not.toBeNull();
|
||||||
|
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
|
||||||
|
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
|
||||||
|
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal']);
|
||||||
|
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
|
||||||
|
fixture.componentInstance.apply();
|
||||||
|
const filtered = request();
|
||||||
|
expect(filtered.request.params.get('alteraciones_eeg')).toBe('anormal');
|
||||||
|
expect(filtered.request.params.get('corte')).toBe('2026-08-31');
|
||||||
|
expect(filtered.request.params.get('meses')).toBe('6');
|
||||||
|
expect(filtered.request.params.get('page_size')).toBe('20');
|
||||||
|
expect(filtered.request.params.get('page')).toBe('1');
|
||||||
|
filtered.flush(anormal); fixture.detectChanges();
|
||||||
|
expect(root.querySelectorAll('tbody tr')).toHaveLength(1);
|
||||||
|
expect(fixture.componentInstance.draft.estatus).toBe('anormal');
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('filtra por grupo de edad, M-CHAT y CSS ADOS-2, sin prioridad, y conserva los filtros al responder y paginar', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(data); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(root.querySelector('select[name=prioridad]')).toBeNull();
|
||||||
|
const opciones = (name: string) => Array.from(root.querySelector<HTMLSelectElement>(`select[name=${name}]`)!.options).map(o => o.textContent?.trim());
|
||||||
|
expect(opciones('grupo_edad')).toEqual(['Todos', '16-23 meses', '24-29 meses', '30-36 meses']);
|
||||||
|
expect(opciones('mchat')).toEqual(['Todos', 'Riesgo bajo (0–2)', 'Riesgo medio (3–7)', 'Riesgo alto (8–20)']);
|
||||||
|
expect(opciones('css')).toEqual(['Todos', 'Evidencia mínima o nula (1–2)', 'Nivel bajo (3–4)', 'Nivel moderado (5–7)', 'Nivel alto (8–10)']);
|
||||||
|
const c = fixture.componentInstance;
|
||||||
|
c.draft = { ...c.draft, grupo_edad: '24-29 meses', mchat: 'alto', css: 'moderado' };
|
||||||
|
c.apply();
|
||||||
|
const filtrada = request();
|
||||||
|
const parametros = (r: typeof filtrada) => Object.fromEntries(['grupo_edad', 'mchat_min', 'mchat_max', 'css_min', 'css_max'].map(k => [k, r.request.params.get(k)]));
|
||||||
|
const esperados = { grupo_edad: '24-29 meses', mchat_min: '8', mchat_max: '20', css_min: '5', css_max: '7' };
|
||||||
|
expect(parametros(filtrada)).toEqual(esperados);
|
||||||
|
filtrada.flush({ ...data, paginacion: { ...data.paginacion, total_items: 0, total_pages: 2 }, items: [] }); fixture.detectChanges();
|
||||||
|
expect(c.draft).toMatchObject({ grupo_edad: '24-29 meses', mchat: 'alto', css: 'moderado' });
|
||||||
|
expect(root.textContent).toContain('No hay registros para los filtros aplicados.');
|
||||||
|
c.navigate(2);
|
||||||
|
expect(parametros(request())).toEqual(esperados);
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('muestra el estado del caso, lo que falta y el módulo junto al puntaje', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(data); fixture.detectChanges();
|
||||||
|
const celdas = fixture.nativeElement.querySelector('tbody tr').querySelectorAll('td');
|
||||||
|
expect(celdas[2].textContent).toContain('En proceso');
|
||||||
|
expect(celdas[2].textContent).toContain('Falta: Neuropediatría');
|
||||||
|
expect(celdas[5].textContent).toContain('8');
|
||||||
|
expect(celdas[5].textContent).toContain('Módulo 2');
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('resume los EEG arriba de la tabla y filtra por estado y tipo de alteración', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(data); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
expect(Array.from(root.querySelectorAll('.resumen-eeg dd')).map(d => d.textContent)).toEqual(['3', '1', '1', '1', '0']);
|
||||||
|
expect(root.querySelector('.resumen-eeg')!.textContent).toContain('Picos paroxísticos');
|
||||||
|
expect(Array.from(root.querySelector<HTMLSelectElement>('select[name=alteracion]')!.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Ritmo posterior', 'Picos paroxísticos']);
|
||||||
|
const c = fixture.componentInstance;
|
||||||
|
c.draft = { ...c.draft, estado_caso: 'completo', alteracion: 'picos_paroxisticos' };
|
||||||
|
c.apply();
|
||||||
|
const filtrada = request();
|
||||||
|
expect(filtrada.request.params.get('estado_caso')).toBe('completo');
|
||||||
|
expect(filtrada.request.params.get('alteracion')).toBe('picos_paroxisticos');
|
||||||
|
filtrada.flush(data); fixture.detectChanges();
|
||||||
|
expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' });
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('abre con las zonas de la primera alteración, cambia al elegir otra y se cierra al repetirla', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(data); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||||
|
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||||
|
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||||
|
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true);
|
||||||
|
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true');
|
||||||
|
const panel = () => root.querySelector('section.mapa')!;
|
||||||
|
expect(panel().classList.contains('panel')).toBe(false);
|
||||||
|
expect(panel().textContent).toContain('Azul: menos actividad');
|
||||||
|
expect(panel().textContent).toContain('Rojo: más actividad');
|
||||||
|
expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior');
|
||||||
|
expect(panel().querySelector('.regiones')!.textContent).toContain('Central');
|
||||||
|
tarjetas[3].click(); fixture.detectChanges();
|
||||||
|
expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos');
|
||||||
|
expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital');
|
||||||
|
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false');
|
||||||
|
expect(tarjetas[1].disabled).toBe(true);
|
||||||
|
expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false);
|
||||||
|
tarjetas[3].click(); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('section.mapa')).toBeNull();
|
||||||
|
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false);
|
||||||
|
tarjetas[0].click(); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('section.mapa')).not.toBeNull();
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => {
|
||||||
|
const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo);
|
||||||
|
const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;
|
||||||
|
expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)');
|
||||||
|
expect(marco()).toBe('#FFFFFF');
|
||||||
|
});
|
||||||
|
it('sin alteraciones abre con la primera métrica evaluable', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(data); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||||
|
const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m);
|
||||||
|
http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('section.mapa .meta')!.textContent).toContain('Ritmo posterior');
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('sin filtros no envía sus parámetros', () => {
|
||||||
|
open();
|
||||||
|
expect(request().request.params.keys().sort()).toEqual(['meses', 'page', 'page_size']);
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('rechaza datos reales, puntajes fuera de rango y más filas que el tamaño de página', () => {
|
||||||
|
expect(() => teaSeguimientoResponse(data)).not.toThrow();
|
||||||
|
expect(() => teaSeguimientoResponse({ ...data, simulado: false })).toThrow();
|
||||||
|
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, mchat: 21 }] })).toThrow();
|
||||||
|
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, css_ados2: 0 }] })).toThrow();
|
||||||
|
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, alteraciones_eeg: 'dudoso' }] })).toThrow();
|
||||||
|
expect(() => teaSeguimientoResponse({ ...data, filtros: { alteraciones_eeg: 'dudoso' } })).toThrow();
|
||||||
|
expect(() => teaSeguimientoResponse({ ...data, paginacion: { ...data.paginacion, page_size: 1 } })).toThrow();
|
||||||
|
const fixture = open();
|
||||||
|
request().flush({ ...data, simulado: false }); fixture.detectChanges();
|
||||||
|
expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||||
|
expect(fixture.nativeElement.textContent).toContain('No se pudo consultar');
|
||||||
|
});
|
||||||
|
// Mock: odd-numbered patients open their own window; even-numbered ones expand in place.
|
||||||
|
const tres = { ...data, paginacion: { ...data.paginacion, total_items: 3 },
|
||||||
|
items: [item, { ...item, id_seudonimo: 'T-0002' }, { ...item, id_seudonimo: 'T-0004' }] };
|
||||||
|
it('el resumen se despliega en la fila, uno a la vez, y se pide al abrirlo', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(tres); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const toggles = root.querySelectorAll<HTMLButtonElement>('button.row-toggle');
|
||||||
|
expect(toggles).toHaveLength(3);
|
||||||
|
expect(toggles[0].getAttribute('aria-expanded')).toBe('false');
|
||||||
|
expect(toggles[1].getAttribute('aria-expanded')).toBe('false');
|
||||||
|
toggles[1].click(); fixture.detectChanges();
|
||||||
|
expect(toggles[1].getAttribute('aria-expanded')).toBe('true');
|
||||||
|
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges();
|
||||||
|
const panel = root.querySelector('#tea-detalle-T-0002')!;
|
||||||
|
expect(panel.textContent).toContain('CSS 3');
|
||||||
|
expect(panel.textContent).toContain('Afecto social (AS)');
|
||||||
|
expect(panel.textContent).toContain('Aceptable');
|
||||||
|
// Opens with the map of the first altered metric.
|
||||||
|
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||||
|
// Item scores start collapsed.
|
||||||
|
expect(panel.querySelector<HTMLDetailsElement>('details')!.open).toBe(false);
|
||||||
|
const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!;
|
||||||
|
expect(metricas.textContent).toContain('Datos de ejemplo');
|
||||||
|
expect(metricas.textContent).toContain('Disminuido');
|
||||||
|
expect(metricas.textContent).toContain('Posibles efectos asociados');
|
||||||
|
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||||
|
expect(metricas.textContent).toContain('Sin registro de sueño en el estudio.');
|
||||||
|
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual(
|
||||||
|
['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']);
|
||||||
|
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
|
||||||
|
(root.querySelectorAll('tbody tr.tea-row')[2] as HTMLElement).click(); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('#tea-detalle-T-0002')).toBeNull();
|
||||||
|
http.expectOne('/tea/seguimiento/T-0004').flush({ ...detalle, id_seudonimo: 'T-0004', ados2: null, eeg: null }); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('#tea-detalle-T-0004')?.textContent).toContain('Sin evaluación ADOS-2 registrada.');
|
||||||
|
toggles[2].click(); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('tr.tea-detalle')).toBeNull();
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('todas las filas son un acordeón: se despliegan en su lugar y una a la vez', () => {
|
||||||
|
const fixture = open();
|
||||||
|
const ficha = vi.fn(); fixture.componentInstance.fichaPacienteAbierta.subscribe(ficha);
|
||||||
|
request().flush(tres); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
const toggles = root.querySelectorAll<HTMLButtonElement>('button.row-toggle');
|
||||||
|
expect(toggles).toHaveLength(tres.items.length);
|
||||||
|
toggles.forEach(toggle => expect(toggle.getAttribute('aria-expanded')).toBe('false'));
|
||||||
|
toggles[0].click(); fixture.detectChanges();
|
||||||
|
expect(toggles[0].getAttribute('aria-expanded')).toBe('true');
|
||||||
|
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('#tea-detalle-T-0001')?.textContent).toContain('CSS 3');
|
||||||
|
(root.querySelectorAll('tbody tr.tea-row')[1] as HTMLElement).click(); fixture.detectChanges();
|
||||||
|
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('#tea-detalle-T-0001')).toBeNull();
|
||||||
|
expect(root.querySelector('#tea-detalle-T-0002')).not.toBeNull();
|
||||||
|
expect(root.querySelector('section.tea-ficha')).toBeNull();
|
||||||
|
expect(ficha).not.toHaveBeenCalled();
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('muestra un error recuperable si el resumen no es válido', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(tres); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[1].click(); fixture.detectChanges();
|
||||||
|
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0099' }); fixture.detectChanges();
|
||||||
|
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => {
|
||||||
|
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, total: 6 } }, 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, css: 11 } }, 'T-0001')).toThrow();
|
||||||
|
const [as, crr] = detalle.ados2.dominios;
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, dominios: [{ ...as, reactivos: [reactivo('A2', 4), as.reactivos[1]] }, crr] } }, 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
|
||||||
|
});
|
||||||
|
it('la calidad general es una palabra, sus criterios son números y se validan', () => {
|
||||||
|
const fixture = open();
|
||||||
|
request().flush(tres); fixture.detectChanges();
|
||||||
|
const root: HTMLElement = fixture.nativeElement;
|
||||||
|
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||||
|
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||||
|
const panel = root.querySelector('section.calidad')!;
|
||||||
|
expect(panel.querySelector('.css')!.textContent!.trim()).toBe('Aceptable');
|
||||||
|
expect(Array.from(panel.querySelectorAll('dt, dd')).map(n => n.textContent)).toEqual(['Canales con amplitud extrema', '1 de 19', 'Ruido de la línea eléctrica', '8 dB']);
|
||||||
|
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('aceptable');
|
||||||
|
expect(panel.textContent).not.toMatch(/Impedancia|Artefactos|de 100/);
|
||||||
|
const conCriterios = (criterios_calidad: unknown) => ({ ...detalle, eeg: { ...detalle.eeg, criterios_calidad } });
|
||||||
|
expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow();
|
||||||
|
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: 'canales', nivel: 'bueno' };
|
||||||
|
expect(() => teaPacienteDetalle(conCriterios([criterio]), 'T-0001')).not.toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, nivel: 'regular' }]), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: null }]), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: 20 }]), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'buena' } }, 'T-0001')).toThrow();
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
it('valida las alteraciones del EEG', () => {
|
||||||
|
const con = (m: object) => ({ ...detalle, eeg: { ...detalle.eeg, alteraciones: [m] } });
|
||||||
|
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, alteraciones: undefined } }, 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
|
||||||
|
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
+30
-17
@@ -10,7 +10,7 @@
|
|||||||
--color-border: #e3e7df;
|
--color-border: #e3e7df;
|
||||||
--color-step: #f0f3e8;
|
--color-step: #f0f3e8;
|
||||||
--font-body: 'Roboto', sans-serif;
|
--font-body: 'Roboto', sans-serif;
|
||||||
--font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif;
|
--font-heading: 'Roboto', 'Helvetica Neue', Arial, sans-serif;
|
||||||
--site-header-height: 72px;
|
--site-header-height: 72px;
|
||||||
|
|
||||||
/* Spacing scale on a 4px grid. Use these for padding, margins and gaps
|
/* Spacing scale on a 4px grid. Use these for padding, margins and gaps
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
--issste-space-3: var(--space-3);
|
--issste-space-3: var(--space-3);
|
||||||
--issste-space-4: var(--space-4);
|
--issste-space-4: var(--space-4);
|
||||||
--issste-space-6: var(--space-6);
|
--issste-space-6: var(--space-6);
|
||||||
--issste-radius: var(--mat-sys-corner-medium);
|
--issste-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The indicators experience: Roboto headings and square corners with a slight rounding (no pills), as in the
|
/* The indicators experience: Roboto headings and square corners with a slight rounding (no pills), as in the
|
||||||
@@ -72,6 +72,13 @@ html {
|
|||||||
density: 0,
|
density: 0,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
// Institutional shapes: square corners with a slight rounding, including buttons (no pills).
|
||||||
|
--mat-sys-corner-extra-small: 2px;
|
||||||
|
--mat-sys-corner-small: 2px;
|
||||||
|
--mat-sys-corner-medium: 4px;
|
||||||
|
--mat-sys-corner-large: 4px;
|
||||||
|
--mat-sys-corner-extra-large: 6px;
|
||||||
|
--mat-sys-corner-full: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@@ -123,24 +130,30 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* Global rules of the indicators dashboard: its floating navigation trigger
|
/* Global rules of the vendored indicators dashboard (fork `dev`) that live
|
||||||
and overlay live outside the component's own styles. */
|
outside the component's own styles. */
|
||||||
:root {
|
:root {
|
||||||
--issste-header-clearance: 7rem;
|
--issste-header-clearance: 7rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dashboard .catalog-grid > app-indicador-catalog-card { scroll-margin-top: var(--issste-header-clearance, 6rem); }
|
.dashboard .catalog-grid > app-indicador-catalog-card { scroll-margin-top: var(--issste-header-clearance, 6rem); }
|
||||||
.dashboard .graphic-navigation-trigger {
|
// «Ir» link inside each option of the indicator selector (the panel renders in the CDK overlay).
|
||||||
position: fixed;
|
.indicator-select-panel .mdc-list-item__primary-text { flex: 1; min-width: 0; }
|
||||||
z-index: 90;
|
.indicator-select-panel .option-row { display: flex; align-items: center; gap: .75rem; width: 100%; }
|
||||||
inset-inline-start: max(.5rem, env(safe-area-inset-left));
|
.indicator-select-panel .option-title { flex: 1; min-width: 0; }
|
||||||
top: 50%;
|
.indicator-select-panel .option-go { flex: none; padding: .25rem .6rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius);
|
||||||
transform: translateY(-50%);
|
color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; }
|
||||||
width: 48px;
|
.indicator-select-panel .option-go:hover { background: var(--issste-accent); }
|
||||||
height: 48px;
|
.indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
color: var(--issste-text);
|
|
||||||
background: var(--issste-accent);
|
// The TEA report: while it's being prepared, charts draw at a width that fits a page.
|
||||||
box-shadow: 0 2px 8px rgb(0 0 0 / 18%);
|
.dashboard.reporte-impresion .catalog-grid { grid-template-columns: minmax(0, 1fr) !important; max-width: 680px; }
|
||||||
|
@media print {
|
||||||
|
.site-header, .site-footer, .institutional-header, .domain-nav, .section-tabs, .global-filters, .catalog-search, .search-result, .reporte-acciones,
|
||||||
|
.dashboard > header > p, .kpi-grid-oculto, app-indicador-catalog-card button, .catalog-metadata, .selection-status { display: none !important; }
|
||||||
|
.dashboard app-indicador-catalog-card, .dashboard .resumen { break-inside: avoid; }
|
||||||
|
.dashboard .plot-viewport { overflow: visible; }
|
||||||
|
// The app scrolls inside its shell; on paper everything has to flow across pages.
|
||||||
|
html, body, .app-shell, .app-shell--workspace, .app-main { display: block !important; height: auto !important; min-height: 0 !important; overflow: visible !important; }
|
||||||
|
body { background: #fff; }
|
||||||
}
|
}
|
||||||
.dashboard .graphic-navigation-trigger:focus-visible { outline: 3px solid var(--issste-text); outline-offset: 3px; }
|
|
||||||
.cdk-overlay-pane.indicator-navigation-overlay:has(.panel-closing) { pointer-events: none; }
|
|
||||||
|
|||||||
Reference in New Issue
Block a user