feat(indicadores): completa metadatos y navegación multiperiodo
This commit is contained in:
@@ -4,7 +4,7 @@ export interface SeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
grupo_edad: string;
|
||||
estatus: SeguimientoStatus;
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string } | null;
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
|
||||
@@ -21,7 +21,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && typeof c['calidad'] === 'string')
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
})) throw new Error('Respuesta de seguimiento inválida');
|
||||
|
||||
@@ -16,17 +16,35 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
afterEach(()=>{ fixture.destroy(); http.verify(); });
|
||||
function open() { fixture.componentRef.setInput('active',true); fixture.detectChanges(); return http.expectOne(r=>r.url==='/cacu/seguimiento'); }
|
||||
function respond() { open().flush(fixtureData); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges(); }
|
||||
it('consulta solo al abrir CaCu, presenta simulación, nulos, calidad y genotipo sin prioridad clínica', () => {
|
||||
it('consulta solo al abrir CaCu, presenta ventana, nulos, calidad y genotipo sin leyendas de prototipo ni prioridad clínica', () => {
|
||||
fixture.detectChanges(); http.expectNone(()=>true); respond();
|
||||
const root:HTMLElement=fixture.nativeElement;
|
||||
expect(root.textContent).toContain('Datos simulados — uso de demostración');
|
||||
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||
expect(root.textContent).toContain('Ventana consultada:');
|
||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
expect(root.textContent).not.toMatch(/Ronda|Espera|Motivo de revisión/);
|
||||
expect(root.querySelector('tbody tr td:last-child')?.textContent).toBe('No disponible');
|
||||
expect(latestStudy(seguimientoResponse(fixtureData).items[5])).toBe('2026-08-15');
|
||||
expect(latestStudy({...seguimientoResponse(fixtureData).items[0],ultima_citologia:null,ultimo_vph:null})).toBeNull();
|
||||
});
|
||||
it('acepta calidad nula por paciente y la presenta de forma neutra sin rechazar la página', () => {
|
||||
const items = fixtureData.items.map((item, index) => index === 2
|
||||
? {...item, ultima_citologia:{...item.ultima_citologia!, calidad:null}}
|
||||
: item);
|
||||
expect(seguimientoResponse({...fixtureData, items}).items).toHaveLength(fixtureData.items.length);
|
||||
fixture.componentRef.setInput('active',true); fixture.detectChanges();
|
||||
http.expectOne(r=>r.url==='/cacu/seguimiento').flush({...fixtureData,items});
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{NORMAL:{etiqueta:'Normal'}}}); fixture.detectChanges();
|
||||
const rows = fixture.nativeElement.querySelectorAll('tbody tr');
|
||||
expect(rows).toHaveLength(fixtureData.items.length);
|
||||
expect(rows[2].textContent).toContain('Calidad: —');
|
||||
expect(rows[2].textContent).not.toContain('Calidad: null');
|
||||
});
|
||||
it('página y filtros conservan los parámetros aplicados; navegación por pestañas no repite GET', () => {
|
||||
respond(); fixture.componentInstance.draft={corte:'2026-09-30',meses:6,estatus:'VIGILANCIA',page:1,page_size:10}; fixture.componentInstance.apply();
|
||||
let req=http.expectOne(r=>r.url==='/cacu/seguimiento'); expect(req.request.params.get('meses')).toBe('6'); expect(req.request.params.get('estatus')).toBe('VIGILANCIA');
|
||||
@@ -49,11 +67,15 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
it('no activa registros reales ni acepta respuestas malformadas', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow();
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow();
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
|
||||
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
|
||||
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
|
||||
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
|
||||
});
|
||||
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
|
||||
const service=TestBed.inject(CacuSeguimientoService);
|
||||
|
||||
@@ -78,6 +78,25 @@ describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
|
||||
fixture.componentRef.setInput('indicador', { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2',
|
||||
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] });
|
||||
fixture.detectChanges();
|
||||
const helps = fixture.nativeElement.querySelectorAll('.methodology-toggle') as NodeListOf<HTMLButtonElement>;
|
||||
expect(helps).toHaveLength(2);
|
||||
helps[0].click(); helps[1].click(); fixture.detectChanges();
|
||||
const metadata = http.expectOne('/cacu/indicadores/cacu_eu7/metadatos');
|
||||
http.expectNone('/cacu/indicadores/cacu_eu7/metadatos');
|
||||
metadata.flush({ figuras_detalle: [
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Instrucción para donas.'] },
|
||||
{ figura: 'fig_c2_barras', descripcion: null, como_leer: ['Instrucción para barras.'] },
|
||||
{ figura: 'otra', descripcion: null, como_leer: ['No debe asignarse.'] },
|
||||
] });
|
||||
fixture.detectChanges();
|
||||
const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(e => e.componentInstance as IndicadorFigureCard);
|
||||
expect(cards.map(card => card.interpretation)).toEqual([['Instrucción para donas.'], ['Instrucción para barras.']]);
|
||||
expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true);
|
||||
});
|
||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChanges, OnDestroy, output, untracked, ViewChild } from '@angular/core';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { catchError, of, Subscription } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, Tema } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
@@ -15,6 +15,7 @@ import { dualFigures } from './indicadores-dual-figures';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
@@ -49,7 +50,7 @@ import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
@for (figure of displayFigures; track panelIdentity(figure)) {
|
||||
<div class="representation-panel">
|
||||
@if (isDual) { <h3>{{ figureDisplayName(figure, indicador.figuras) }}</h3> }
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [figuraId]="figure" [tema]="tema" [applied]="applied" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (hierarchySelected)="localSelection = $event" />
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [metadata]="metadata" [figuraId]="figure" [tema]="tema" [applied]="applied" [visible]="visible" [visualProfile]="visualProfile" [localSelection]="localSelection" (metadataRequested)="loadMetadata()" (hierarchySelected)="localSelection = $event" />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -87,6 +88,10 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private numericSubscription?: Subscription;
|
||||
private numericKey = '';
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private metadataSubscription?: Subscription;
|
||||
private metadataKey = '';
|
||||
metadata?: IndicadorMetadatos;
|
||||
private activatedKey = '';
|
||||
constructor() {
|
||||
effect(() => {
|
||||
@@ -112,7 +117,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
this.numericSubscription?.unsubscribe();
|
||||
this.numericSubscription = this.snapshots.read(this.dominio, this.indicador, this.applied).subscribe();
|
||||
}
|
||||
ngOnDestroy() { this.numericSubscription?.unsubscribe(); }
|
||||
ngOnDestroy() { this.numericSubscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@@ -146,6 +151,9 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
const identity = indicatorIdentity(this.dominio, this.indicador.id);
|
||||
if (identity === this.identity) { this.updateNumeric(); return; }
|
||||
this.identity = identity;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadata = undefined;
|
||||
this.metadataKey = '';
|
||||
const id = identityElementId(identity);
|
||||
this.titleId = id + '-title';
|
||||
this.contentId = id + '-content';
|
||||
@@ -158,4 +166,17 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
this.updateNumeric();
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
loadMetadata() {
|
||||
const key = JSON.stringify([this.dominio, this.indicador.id]);
|
||||
if (this.metadataKey === key) return;
|
||||
this.metadataKey = key;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.indicators.metadatos(this.dominio, this.indicador.id)
|
||||
.pipe(catchError(() => of(undefined))).subscribe(value => {
|
||||
if (this.metadataKey !== key) return;
|
||||
if (!value) this.metadataKey = '';
|
||||
this.metadata = value;
|
||||
this.changeDetector.markForCheck();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ' · ' + dominio + ' · ' + figuraId"
|
||||
[attr.aria-expanded]="methodologyExpanded()" [attr.aria-controls]="methodologyId"
|
||||
(click)="methodologyExpanded.set(!methodologyExpanded())">
|
||||
(click)="toggleMethodology()">
|
||||
<mat-icon aria-hidden="true">help_outline</mat-icon>
|
||||
Cómo leer
|
||||
</button>
|
||||
@@ -75,7 +75,16 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="state.hierarchy ? '440px' : null" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
@if (state.status === 'ready' && state.donutLegend?.length) {
|
||||
<div class="donut-static-legend" role="list" aria-label="Leyenda de la dona">
|
||||
@for (entry of state.donutLegend; track entry.label) {
|
||||
<span class="donut-static-legend__item" role="listitem">
|
||||
<span class="legend-swatch" [style.background]="entry.color ?? 'currentColor'" aria-hidden="true"></span>{{ entry.label }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="state.plotHeight ? state.plotHeight + 'px' : (state.hierarchy || state.donutLegend ? '440px' : null)" [style.--plot-min-width]="chartMinimumWidth ? chartMinimumWidth + 'px' : null" [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" (widthChanged)="reportPlotWidth($event)" (plotClick)="plotClicked($event)" />
|
||||
@if (state.footnotes?.length) {
|
||||
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
|
||||
@@ -85,6 +85,13 @@
|
||||
.donut-legend button:focus-visible, .donut-restore:focus-visible {
|
||||
outline: 2px solid currentColor; outline-offset: 3px;
|
||||
}
|
||||
.donut-static-legend {
|
||||
display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: .25rem .9rem;
|
||||
padding: .5rem .75rem .25rem; color: var(--issste-text); box-sizing: border-box;
|
||||
}
|
||||
.dark .donut-static-legend { color: #eef1f7; }
|
||||
.donut-static-legend__item { display: flex; align-items: center; gap: .5rem; min-height: 32px; max-width: 100%;
|
||||
font: var(--mat-sys-body-small); overflow-wrap: anywhere; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.donut-children-region, .donut-children-region.expanded { transition: none; transform: none; }
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { presentationFigure } from './indicadores.presentation';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutHierarchy } from './indicadores-donut-drilldown';
|
||||
import { donutHierarchy, donutLegend } from './indicadores-donut-drilldown';
|
||||
|
||||
describe('IndicadorFigureCard', () => {
|
||||
const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] };
|
||||
@@ -91,6 +91,21 @@ describe('IndicadorFigureCard', () => {
|
||||
state({ status: 'ready', figure: structuredClone(figure), presentationFigure: figure, hierarchy }); await settle();
|
||||
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
|
||||
});
|
||||
it('homologa la dona simple con leyenda HTML superior sin alterar categorías ni valores', async () => {
|
||||
const { figure } = donutFixture();
|
||||
figure.data.pop();
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
|
||||
const copy = presentationFigure(figure, { indicador: selected.id, figura: 'fig_c2_donas', tema: 'claro' });
|
||||
const legend = donutLegend(copy)!;
|
||||
state({ status: 'ready', figure, presentationFigure: copy, donutLegend: legend }); await settle();
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
expect(fixture.nativeElement.querySelectorAll('.donut-static-legend__item')).toHaveLength(3);
|
||||
expect(fixture.nativeElement.querySelector('.donut-static-legend').textContent).toContain('A');
|
||||
expect(chart.figure.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||
expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']);
|
||||
expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']);
|
||||
});
|
||||
it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => {
|
||||
const { figure, data } = donutFixture();
|
||||
state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data) });
|
||||
@@ -292,6 +307,41 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'))
|
||||
.toBe(fixture.nativeElement.querySelector('.methodology-detail').id);
|
||||
});
|
||||
it('usa instrucciones exactas en orden y conserva caracteres especiales como texto', () => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_donas', descripcion: 'No repetir', como_leer: [
|
||||
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
|
||||
] }] });
|
||||
state({ status: 'idle' });
|
||||
const lines = fixture.nativeElement.querySelectorAll('.methodology-detail li');
|
||||
expect([...lines].map((line: Element) => line.textContent)).toEqual([
|
||||
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
|
||||
]);
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(fixture.componentInstance.interpretation).toEqual([...lines].map((line: Element) => line.textContent));
|
||||
});
|
||||
it.each([
|
||||
['sin coincidencia', [{ figura: 'otra_figura', descripcion: null, como_leer: ['No corresponde.'] }]],
|
||||
['vacías', [{ figura: 'fig_c2_apiladas', descripcion: 'Sin instrucciones específicas.', como_leer: [] }]],
|
||||
['nulas', [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: null }]],
|
||||
])('mantiene fallback local con figuras_detalle %s', (_label, details) => {
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: details });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.componentInstance.interpretation).toContain('Las categorías corresponden a la distribución de cada grupo y periodo.');
|
||||
expect(fixture.componentInstance.interpretation).toContain('SIN_DATO, cuando aparece, es una categoría legítima de la representación.');
|
||||
});
|
||||
it('preserva íntegramente, sin filtrado semántico, instrucciones sobre supresión y categorías pequeñas', () => {
|
||||
const instructions = ['Se ocultan categorías individuales pequeñas.', 'La supresión se determina por grupo.', 'Conclusión.'];
|
||||
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: instructions }] });
|
||||
state({ status: 'idle' });
|
||||
expect(fixture.componentInstance.interpretation).toEqual(instructions);
|
||||
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((line: Element) => line.textContent)).toEqual(instructions);
|
||||
});
|
||||
it.each([
|
||||
['fig_c2_barras', 'Barras'],
|
||||
['fig_c2_donas', 'Donas'],
|
||||
|
||||
@@ -4,14 +4,14 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { Dominio, hasNoVisibleValues, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { figureTitle } from './indicadores.presentation';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutSelection, donutView } from './indicadores-donut-drilldown';
|
||||
import { contractInterpretation, figureMetadataInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
@@ -21,7 +21,9 @@ export interface FigureState {
|
||||
footnotes?: readonly string[];
|
||||
categoryLabels?: readonly CategoryLabel[];
|
||||
minimumPlotWidth?: number;
|
||||
donutLegend?: readonly DonutLegendEntry[];
|
||||
plotWidth?: number;
|
||||
plotHeight?: number;
|
||||
message?: string;
|
||||
hierarchy?: DonutHierarchy;
|
||||
source?: 'datos' | 'figuras';
|
||||
@@ -78,8 +80,13 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
}
|
||||
private updateDonut() {
|
||||
const { presentationFigure, hierarchy } = this.state;
|
||||
this.chartFigure = presentationFigure && hierarchy
|
||||
? donutView(presentationFigure, hierarchy, this.activeParent, this.state.plotWidth) : presentationFigure;
|
||||
// Empty pages retain the series' plot height as well. This is a derived
|
||||
// layout copy; the original figure and its annotations remain available.
|
||||
const source = presentationFigure && this.state.plotHeight
|
||||
? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure;
|
||||
this.chartFigure = source && hierarchy
|
||||
? donutView(source, hierarchy, this.activeParent, this.state.plotWidth)
|
||||
: source && this.state.donutLegend ? donutSimpleView(source) : source;
|
||||
}
|
||||
expandParent(parent: string) {
|
||||
if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent)
|
||||
@@ -108,6 +115,7 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@@ -117,6 +125,12 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
if (typeof width === 'number') this.plotWidthChanged.emit(width);
|
||||
}
|
||||
readonly methodologyExpanded = signal(false);
|
||||
readonly metadataRequested = output<void>();
|
||||
toggleMethodology() {
|
||||
const open = !this.methodologyExpanded();
|
||||
this.methodologyExpanded.set(open);
|
||||
if (open && !this.metadata) this.metadataRequested.emit();
|
||||
}
|
||||
get methodologyId(): string {
|
||||
return identityElementId(figureIdentity(this.dominio, this.selected?.id ?? '', this.figuraId)) + '-methodology';
|
||||
}
|
||||
@@ -144,6 +158,7 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get interpretation(): readonly string[] {
|
||||
return contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
return figureMetadataInterpretation(this.metadata, this.figuraId)
|
||||
?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Component, DestroyRef, inject, Input, OnChanges, SimpleChanges, signal,
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, Tema } from './indicadores.models';
|
||||
import { DimensionEstrato, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
import { READABLE_VISUAL_PROFILE, FigureVisualProfile } from './indicadores-visual-profile';
|
||||
@@ -10,10 +10,11 @@ import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
|
||||
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
|
||||
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
@@ -23,16 +24,34 @@ import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indica
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
|
||||
<label>Distribución
|
||||
<select aria-label="Dimensión de las barras" [value]="dimension" (change)="changeDimension($any($event.target).value)">
|
||||
<option value="">Distribución general</option>
|
||||
@for (d of capabilities; track d) { <option [value]="d" [disabled]="!singlePeriod">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (!singlePeriod) { <p>Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
|
||||
<legend>Distribución</legend>
|
||||
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
|
||||
(click)="changeDimension('')">Distribución general</button>
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension !== ''" [class.active]="dimension !== ''"
|
||||
[disabled]="!singlePeriod" (click)="chooseStratified()">Distribución estratificada</button>
|
||||
</div>
|
||||
@if (dimension && capabilities.length > 1) {
|
||||
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
|
||||
@for (d of capabilities; track d) {
|
||||
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
|
||||
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</fieldset>
|
||||
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
|
||||
}
|
||||
@if (result().status === 'ready' && donutPages.length > 1) {
|
||||
<nav class="donut-periods" aria-label="Periodos de la dona">
|
||||
<button type="button" aria-label="Periodo anterior de la dona" [disabled]="donutPeriodIndex <= 0" (click)="changeDonutPeriod(-1)">‹</button>
|
||||
<span role="status" aria-live="polite">{{ activeDonutPeriod }} · {{ donutPeriodIndex + 1 }} / {{ donutPages.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (hierarchySelected)="hierarchySelected.emit($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
|
||||
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
|
||||
@@ -49,8 +68,23 @@ import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indica
|
||||
:host { display: block; min-width: 0; }
|
||||
section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); }
|
||||
.applied-summary { color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
select { margin: .5rem; padding: .75rem; max-width: 100%; background: var(--issste-surface); color: var(--issste-text); }
|
||||
.distribution-control { margin: var(--issste-space-3) 0; padding: 0; border: 0; min-width: 0; }
|
||||
.distribution-control legend { padding: 0; font-weight: 600; }
|
||||
.distribution-toggle, .distribution-dimensions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .5rem; }
|
||||
.distribution-dimensions { margin-top: .75rem; }
|
||||
.distribution-toggle button, .distribution-dimensions button { min-height: 44px; max-width: 100%; padding: .65rem .9rem;
|
||||
border: 1px solid var(--issste-border); border-radius: 999px; background: var(--issste-surface); color: var(--issste-text);
|
||||
font: inherit; text-align: start; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.distribution-toggle button.active, .distribution-dimensions button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; }
|
||||
.distribution-toggle button:disabled, .distribution-dimensions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.distribution-toggle button:focus-visible, .distribution-dimensions button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.distribution-note { margin: .5rem 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.cells { overflow: auto; max-height: 24rem; } th, td { text-align: start; padding: .5rem; }
|
||||
.donut-periods { display: flex; align-items: center; justify-content: center; gap: .75rem; min-height: 48px; }
|
||||
.donut-periods span { text-align: center; overflow-wrap: anywhere; }
|
||||
.donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; }
|
||||
.donut-periods button:disabled { opacity: .45; }
|
||||
.donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
@@ -60,6 +94,7 @@ import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indica
|
||||
export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@@ -67,6 +102,35 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
@Input() localSelection: DonutSelection = {};
|
||||
readonly hierarchySelected = output<DonutSelection>();
|
||||
readonly metadataRequested = output<void>();
|
||||
donutPages: { period: string; state: FigureState }[] = [];
|
||||
activeDonutPeriod?: string;
|
||||
private donutIdentity = '';
|
||||
get donutPeriodIndex() { return this.donutPages.findIndex(p => p.period === this.activeDonutPeriod); }
|
||||
changeDonutPeriod(step: number) {
|
||||
if (this.result().status !== 'ready' || ![-1, 1].includes(step)) return;
|
||||
const page = this.donutPages[this.donutPeriodIndex + step];
|
||||
if (!page) return;
|
||||
this.activeDonutPeriod = page.period;
|
||||
// Selection belongs to one page. Reset dependent category/stratum state
|
||||
// even when the same labels exist in the following period.
|
||||
this.hierarchySelected.emit({});
|
||||
this.result.set(this.refreshDonutPage(page.state));
|
||||
}
|
||||
selectHierarchy(selection: DonutSelection) {
|
||||
this.hierarchySelected.emit(selection.parent || selection.category
|
||||
? { ...selection, period: this.activeDonutPeriod ?? this.readySelection?.periodos?.[0] } : {});
|
||||
}
|
||||
private refreshDonutPage(state: FigureState): FigureState {
|
||||
const presentation = this.present(state.figure!, this.readySelection!, state.hierarchy);
|
||||
return { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
|
||||
}
|
||||
private activateDonutPages(pages: { period: string; state: FigureState }[]): FigureState {
|
||||
const plotHeight = pages.some(p => p.state.hierarchy) ? 440 : undefined;
|
||||
this.donutPages = pages.map(p => ({ ...p, state: { ...p.state, plotHeight } }));
|
||||
this.activeDonutPeriod = pages.some(p => p.period === this.activeDonutPeriod) ? this.activeDonutPeriod : pages[0]?.period;
|
||||
return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state;
|
||||
}
|
||||
dimension: DimensionEstrato | '' = '';
|
||||
cells: StratifiedCell[] = [];
|
||||
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
|
||||
@@ -79,8 +143,12 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
if (this.dimension === value) return;
|
||||
this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure();
|
||||
}
|
||||
chooseStratified() {
|
||||
if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]);
|
||||
}
|
||||
private presentStratified(data: IndicadorDatos): FigureState {
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, this.localSelection);
|
||||
const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {};
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
@@ -96,6 +164,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
private generation = 0;
|
||||
private currentKey = '';
|
||||
titleId = '';
|
||||
distributionAvailabilityId = '';
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; }
|
||||
constructor() {
|
||||
@@ -112,7 +181,11 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
: of({ state: { status: 'idle' } as FigureState, selection: undefined, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(({ state, selection, revision, generation }) => {
|
||||
if (generation === this.generation && revision === this.applied?.revision) {
|
||||
if (state.status === 'ready') this.readySelection = selection;
|
||||
if (state.status === 'ready') {
|
||||
this.readySelection = selection;
|
||||
if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1
|
||||
? selection.periodos[0] : state.figure && donutPeriod(state.figure);
|
||||
}
|
||||
this.result.set(state);
|
||||
}
|
||||
});
|
||||
@@ -130,18 +203,35 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(
|
||||
switchMap(data => {
|
||||
if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.');
|
||||
const periods = selection.periodos ?? data.periodos;
|
||||
if (selection.figura === 'fig_c2_donas' && periods.length > 1) {
|
||||
const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) }));
|
||||
if (pages.every(p => p.adapted.status === 'supported')) {
|
||||
return of(this.activateDonutPages(pages.map(({ period, adapted }) => {
|
||||
if (adapted.status !== 'supported') throw new Error('Periodo no soportado');
|
||||
return { period, state: { ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage } };
|
||||
})));
|
||||
}
|
||||
return this.publishedFigure(selection, 'Partición multiperiodo no verificable', data);
|
||||
}
|
||||
const adapted = c2Figure(data, selection);
|
||||
return adapted.status === 'supported'
|
||||
? of({ ...this.present(adapted.figure, selection, adapted.hierarchy), source: 'datos' as const,
|
||||
footnotes: adapted.model.notes, emptyMessage: adapted.emptyMessage })
|
||||
: this.publishedFigure(selection, adapted.reason);
|
||||
: this.publishedFigure(selection, adapted.reason, data);
|
||||
}));
|
||||
}
|
||||
return this.publishedFigure(selection);
|
||||
}
|
||||
private publishedFigure(selection: FigureSelection, fallbackReason?: string) {
|
||||
private publishedFigure(selection: FigureSelection, fallbackReason?: string, data?: IndicadorDatos) {
|
||||
return defer(() => this.service.figura(selection)).pipe(
|
||||
switchMap(figure => {
|
||||
const pages = donutPeriodFigures(figure, selection, data?.periodos);
|
||||
if (pages) return of(this.activateDonutPages(pages.map(({ period, figure: page }) => ({ period,
|
||||
state: { ...this.present(page, selection, data && donutHierarchy(page, periodDatos(data, period))),
|
||||
source: 'figuras' as const, fallbackReason,
|
||||
emptyMessage: !page.data.length ? 'No hay valores representables publicados para el periodo ' + period + '. Consulta las notas de la figura.' : undefined } }))));
|
||||
const period = this.indicador.contrato === 'C2'
|
||||
? donutPeriod(figure) : undefined;
|
||||
const present = (hierarchy?: DonutHierarchy) => ({ ...this.present(figure, selection, hierarchy), source: 'figuras' as const, fallbackReason });
|
||||
@@ -158,6 +248,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
const presentation = figurePresentation(figure, selection, this.visualProfile, this.plotWidth);
|
||||
return { status: 'ready', figure, presentationFigure: presentation.figure, footnotes: presentation.footnotes,
|
||||
categoryLabels: presentation.categoryLabels, minimumPlotWidth: presentation.minimumPlotWidth, hierarchy,
|
||||
donutLegend: selection.figura === 'fig_c2_donas' && !hierarchy ? donutLegend(presentation.figure) : undefined,
|
||||
plotWidth: selection.figura === 'fig_c2_donas' && this.indicador.contrato === 'C2' && this.plotWidth !== undefined
|
||||
? (this.plotWidth < 480 ? 320 : 480) : undefined };
|
||||
}
|
||||
@@ -180,7 +271,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = '';
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; }
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
this.distributionAvailabilityId = this.titleId + '-distribution-availability';
|
||||
const key = this.requestKey();
|
||||
if (key === this.currentKey) {
|
||||
if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') {
|
||||
@@ -215,6 +308,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
if (!this.visible) return;
|
||||
this.currentKey = this.requestKey();
|
||||
this.stratifiedData = undefined; this.cells = [];
|
||||
this.donutPages = [];
|
||||
const applied = this.applied;
|
||||
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
this.generation++;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
:host { display: block; min-width: 0; overflow-wrap: anywhere; }
|
||||
section + section { margin-top: var(--issste-space-4); }
|
||||
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; }
|
||||
.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.ficha-fields { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 3fr); gap: var(--issste-space-2) var(--issste-space-4); max-width: 75ch; margin: 0; }
|
||||
.ficha-fields > div { display: contents; }
|
||||
dt { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
dd { margin: 0; }
|
||||
ul { padding-inline-start: 1.5rem; }
|
||||
li + li { margin-top: var(--issste-space-2); }
|
||||
@media (max-width: 36rem) {
|
||||
.ficha-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); }
|
||||
dd { margin-bottom: var(--issste-space-2); }
|
||||
}
|
||||
@@ -2,16 +2,89 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorMetadata } from './indicador-metadata';
|
||||
describe('Metadatos opcionales verificados',()=>{
|
||||
it('muestra referencias y poblaciones como texto seguro y etiquetas legibles',()=>{
|
||||
TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]});
|
||||
const f=TestBed.createComponent(IndicadorMetadata), http=TestBed.inject(HttpTestingController);
|
||||
f.componentRef.setInput('dominio','cacu');f.componentRef.setInput('indicador','future');f.detectChanges();
|
||||
http.expectOne('/cacu/indicadores/future/metadatos').flush({referencias:[{tipo:'citation',etiqueta:'Guía publicada <img src=x>',ref:'Indicador 7'}],poblaciones:[{grupo:'TOTAL',codigo:'initial-population',descripcion:'Pacientes con estudio publicado.'}]});f.detectChanges();
|
||||
expect(f.nativeElement.textContent).toContain('Guía publicada <img src=x>');expect(f.nativeElement.querySelector('img')).toBeNull();expect(f.nativeElement.textContent).toContain('Pacientes con estudio publicado.');expect(f.nativeElement.textContent).not.toMatch(/initial-population|citation|TOTAL/);http.verify();f.destroy();
|
||||
|
||||
function render(data: unknown) {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const fixture = TestBed.createComponent(IndicadorMetadata);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('indicador', 'future');
|
||||
fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores/future/metadatos').flush(data as Record<string, unknown>);
|
||||
fixture.detectChanges();
|
||||
return { fixture, http, text: fixture.nativeElement.textContent as string };
|
||||
}
|
||||
|
||||
describe('Metadatos metodológicos opcionales', () => {
|
||||
it('muestra descripción sin ficha y trata etiquetas recibidas como texto', () => {
|
||||
const { fixture, http, text } = render({ titulo: 'Título del catálogo', descripcion: 'Guía <img src=x onerror=alert(1)>\nSegunda línea', ficha: null });
|
||||
expect(text).toContain('Guía <img src=x onerror=alert(1)>');
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(text).toContain('Segunda línea');
|
||||
expect(text).not.toContain('Ficha metodológica');
|
||||
expect(text).not.toContain('Título del catálogo');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
it.each([{}, {referencias:[],poblaciones:[]},{referencias:'invalid'}])('conserva el estado actual sin campos opcionales válidos',data=>{
|
||||
TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]});
|
||||
const f=TestBed.createComponent(IndicadorMetadata), http=TestBed.inject(HttpTestingController);f.componentRef.setInput('dominio','tea');f.componentRef.setInput('indicador','i1');f.detectChanges();http.expectOne('/tea/indicadores/i1/metadatos').flush(data);f.detectChanges();expect(f.nativeElement.textContent).toContain('no está disponible');http.verify();f.destroy();
|
||||
|
||||
it('muestra todos los campos no vacíos de la ficha', () => {
|
||||
const { fixture, http, text } = render({
|
||||
descripcion: 'Información general.',
|
||||
ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' },
|
||||
});
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha metodológica', 'Código', 'IND-01', 'Para', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra sólo los campos utilizables de una ficha parcial', () => {
|
||||
const { fixture, http, text } = render({ ficha: { codigo: 'IND-02', para: ' ', unidad: null, definicion: 'Definición breve', nota: '' } });
|
||||
expect(text).toContain('Código'); expect(text).toContain('IND-02');
|
||||
expect(text).toContain('Definición breve'); expect(text).not.toContain('Para');
|
||||
expect(text).not.toContain('Unidad'); expect(text).not.toContain('Pregunta'); expect(text).not.toContain('Nota');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('acepta nota nula y conserva el resto de la ficha', () => {
|
||||
const { fixture, http, text } = render({ ficha: { unidad: 'Tasa', nota: null } });
|
||||
expect(text).toContain('Unidad'); expect(text).toContain('Tasa');
|
||||
expect(text).not.toContain('Nota'); expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra estado vacío con descripción y ficha ausentes o nulas', () => {
|
||||
const { fixture, http, text } = render({ descripcion: null, ficha: null, referencias: null, poblaciones: null });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Ficha metodológica'); expect(text).not.toContain('Descripción');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('mantiene referencias y poblaciones de payloads anteriores junto con la descripción', () => {
|
||||
const { fixture, http, text } = render({
|
||||
descripcion: 'Descripción publicada.',
|
||||
referencias: [{ tipo: 'citation', etiqueta: 'Guía publicada <em>edición 2</em>', ref: 'Indicador 7' }],
|
||||
poblaciones: [{ grupo: 'TOTAL', codigo: 'initial-population', descripcion: 'Pacientes con estudio publicado.' }],
|
||||
categorias: { NORMAL: { etiqueta: 'Normal' } },
|
||||
});
|
||||
expect(text).toContain('Descripción publicada.');
|
||||
expect(text).toContain('Guía publicada <em>edición 2</em> · Indicador 7');
|
||||
expect(text).toContain('Pacientes con estudio publicado.');
|
||||
expect(fixture.nativeElement.querySelector('em')).toBeNull();
|
||||
expect(text).not.toMatch(/initial-population|citation|TOTAL|no está disponible/);
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('conserva compatibilidad con el payload anterior que sólo trae categorías', () => {
|
||||
const { fixture, http, text } = render({ categorias: { NORMAL: { etiqueta: 'Normal' } } });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Normal');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('no anuncia ausencia cuando hay ficha utilizable aunque sus demás campos estén vacíos', () => {
|
||||
const { fixture, http, text } = render({ ficha: { codigo: ' IND-03 ' } });
|
||||
expect(text).toContain('IND-03'); expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,15 +6,36 @@ import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-metadata',
|
||||
styleUrl: './indicador-metadata.scss',
|
||||
template: `
|
||||
@if (loading) { <p role="status">Cargando información metodológica…</p> }
|
||||
@if (metadata?.referencias?.length) {
|
||||
<h4>Referencias</h4><ul>@for (ref of metadata!.referencias; track $index) { <li>{{ ref.etiqueta }}@if (ref.ref) { · {{ ref.ref }} }</li> }</ul>
|
||||
@if (description; as text) {
|
||||
<section aria-labelledby="metadata-description-title">
|
||||
<h4 id="metadata-description-title">Descripción</h4>
|
||||
<p class="metadata-copy">{{ text }}</p>
|
||||
</section>
|
||||
}
|
||||
@if (metadata?.poblaciones?.length) {
|
||||
<h4>Poblaciones del estudio</h4><ul>@for (p of metadata!.poblaciones; track $index) { <li>{{ p.descripcion }}</li> }</ul>
|
||||
@if (fichaFields.length) {
|
||||
<section aria-labelledby="metadata-ficha-title">
|
||||
<h4 id="metadata-ficha-title">Ficha metodológica</h4>
|
||||
<dl class="ficha-fields">@for (field of fichaFields; track field.key) {
|
||||
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div>
|
||||
}</dl>
|
||||
</section>
|
||||
}
|
||||
@if (!loading && !metadata?.referencias?.length && !metadata?.poblaciones?.length) { <p>La información metodológica ampliada no está disponible para este indicador.</p> }
|
||||
@if (references.length) {
|
||||
<section aria-labelledby="metadata-references-title">
|
||||
<h4 id="metadata-references-title">Referencias</h4>
|
||||
<ul>@for (ref of references; track $index) { <li>{{ ref.etiqueta }}@if (hasText(ref.ref)) { · {{ ref.ref }} }</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (populations.length) {
|
||||
<section aria-labelledby="metadata-populations-title">
|
||||
<h4 id="metadata-populations-title">Poblaciones del estudio</h4>
|
||||
<ul>@for (population of populations; track $index) { <li>{{ population.descripcion }}</li> }</ul>
|
||||
</section>
|
||||
}
|
||||
@if (!loading && !hasUsableMetadata) { <p>La información metodológica ampliada no está disponible para este indicador.</p> }
|
||||
`,
|
||||
})
|
||||
export class IndicadorMetadata implements OnChanges {
|
||||
@@ -25,6 +46,19 @@ export class IndicadorMetadata implements OnChanges {
|
||||
metadata?: IndicadorMetadatos;
|
||||
loading = false;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly fichaLabels = [
|
||||
['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'],
|
||||
['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
|
||||
] as const;
|
||||
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
|
||||
get description() { return this.hasText(this.metadata?.descripcion) ? this.metadata!.descripcion!.trim() : undefined; }
|
||||
get fichaFields() {
|
||||
const ficha = this.metadata?.ficha;
|
||||
return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : [];
|
||||
}
|
||||
get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); }
|
||||
get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); }
|
||||
get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutView } from './indicadores-donut-drilldown';
|
||||
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { numericRows } from './indicadores-numeric-rows';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
|
||||
@@ -37,14 +37,33 @@ describe('C2: datos publicados a Plotly', () => {
|
||||
expect(final.data[0]['hovertemplate']).toContain('<extra></extra>');
|
||||
expect(final.data[0]['hovertemplate']).not.toContain('<extra>2025-S2');
|
||||
});
|
||||
it('el layout final de dona simple reserva el sector superior derecho para la leyenda', () => {
|
||||
it('la vista de dona simple comparte el lienzo centrado y la leyenda superior', () => {
|
||||
const data = c2Fixture(); data['grupos_de_categoria'] = {};
|
||||
Object.values(data['categorias'] as Record<string, Record<string, unknown>>).forEach(c => c['grupo'] = null);
|
||||
const result = supported(data);
|
||||
const final = figurePresentation(result.figure, selection).figure;
|
||||
expect(final.layout['legend']).toMatchObject({ orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top' });
|
||||
expect(final.data[0]['domain']).toEqual({ x: [0, 0.72], y: [0, 1] });
|
||||
expect(final.data[0]['hovertemplate']).toContain('<extra></extra>');
|
||||
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
|
||||
const legend = donutLegend(final), view = donutSimpleView(final);
|
||||
expect(legend).toEqual([
|
||||
{ label: 'A', color: '#7184A2' }, { label: 'B', color: '#A4B88A' }, { label: 'C', color: '#D0B778' },
|
||||
]);
|
||||
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
|
||||
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
expect(view.data[0]['showlegend']).toBe(false);
|
||||
expect(view.data[0]['labels']).toEqual(final.data[0]['labels']);
|
||||
expect(view.data[0]['values']).toEqual(final.data[0]['values']);
|
||||
expect(final).toEqual(before);
|
||||
});
|
||||
it('homologa la dona jerárquica en los tres dominios con el mismo periodo único', () => {
|
||||
const snapshots = (['tea', 'cacu', 'cama'] as const).map(dominio => {
|
||||
const adapted = supported(c2Fixture(), { ...selection, dominio });
|
||||
expect(adapted.model.period).toBe('2025-S2');
|
||||
expect(adapted.hierarchy).toBeDefined();
|
||||
return donutView(adapted.figure, adapted.hierarchy!);
|
||||
});
|
||||
for (const view of snapshots.slice(1)) expect(view).toEqual(snapshots[0]);
|
||||
expect(snapshots[0].layout['showlegend']).toBe(false);
|
||||
expect(snapshots[0].layout['margin']).toMatchObject({ l: 16, r: 16, t: 16, b: 16, pad: 0 });
|
||||
expect(snapshots[0].data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
|
||||
});
|
||||
it('ordena por orden publicado aunque las filas lleguen desordenadas; conserva ceros explícitos', () => {
|
||||
const data = c2Fixture(); data.filas[0]['n'] = 0; data.filas.reverse();
|
||||
|
||||
@@ -6,7 +6,8 @@ export interface DonutHierarchy {
|
||||
categoryTrace: number;
|
||||
parentTrace?: number;
|
||||
}
|
||||
export interface DonutSelection { parent?: string; category?: string; }
|
||||
export interface DonutSelection { parent?: string; category?: string; period?: string; }
|
||||
export interface DonutLegendEntry { label: string; color?: string; }
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
@@ -37,6 +38,39 @@ function centerCountAt(value: unknown, x: number, y: number): value is Record<st
|
||||
&& typeof value['text'] === 'string' && /^<b>\d+<\/b>$/.test(value['text']);
|
||||
}
|
||||
|
||||
export function donutLegend(figure: PlotlyFigure): readonly DonutLegendEntry[] | undefined {
|
||||
if (figure.data.length !== 1) return;
|
||||
const trace = figure.data[0];
|
||||
if (trace['type'] !== 'pie' || !labels(trace)) return;
|
||||
const marker = record(trace['marker']) ? trace['marker'] : undefined;
|
||||
const colors = marker && Array.isArray(marker['colors']) && marker['colors'].length === trace.labels.length
|
||||
? marker['colors'] : [];
|
||||
return trace.labels.map((label, index) => ({
|
||||
label,
|
||||
color: typeof colors[index] === 'string' && /^#[0-9a-f]{6}$/i.test(colors[index] as string)
|
||||
? colors[index] as string : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
function donutCanvas(source: PlotlyFigure): PlotlyFigure {
|
||||
const figure = structuredClone(source);
|
||||
figure.layout['showlegend'] = false;
|
||||
figure.layout['height'] = 440;
|
||||
figure.layout['margin'] = { ...(record(figure.layout['margin']) ? figure.layout['margin'] : {}),
|
||||
l: 16, r: 16, t: 16, b: 16, pad: 0, autoexpand: false };
|
||||
const annotations = figure.layout['annotations'];
|
||||
if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a)
|
||||
? { ...a, x: 0.5, y: 0.5, xanchor: 'center', yanchor: 'middle' } : a);
|
||||
return figure;
|
||||
}
|
||||
|
||||
export function donutSimpleView(source: PlotlyFigure): PlotlyFigure {
|
||||
const figure = donutCanvas(source);
|
||||
figure.data = figure.data.map(trace => trace['type'] === 'pie'
|
||||
? { ...trace, domain: { x: [0, 1], y: [0, 1] }, showlegend: false } : trace);
|
||||
return figure;
|
||||
}
|
||||
|
||||
// Only a structural candidate: /datos supplies the semantics. No indicator ID,
|
||||
// category count, legendgroup, trace order or exact domain decides eligibility.
|
||||
// C2 metadata describes category -> parent, not further levels or facets.
|
||||
@@ -117,7 +151,7 @@ export function donutHierarchy(figure: PlotlyFigure, data: IndicadorDatos): Donu
|
||||
// The inner ring retains ALL parents so another can be selected directly. Its
|
||||
// denominator is the full verified partition; the outer ring is within-parent.
|
||||
export function donutView(source: PlotlyFigure, hierarchy: DonutHierarchy, parent?: string, _availableWidth?: number): PlotlyFigure {
|
||||
const figure = structuredClone(source);
|
||||
const figure = donutCanvas(source);
|
||||
const meta = figure.layout['meta'];
|
||||
const unit = record(meta) && typeof meta['unit'] === 'string' && !/[<>&]/.test(meta['unit']) ? ' ' + meta['unit'] : '';
|
||||
const outer = figure.data[hierarchy.categoryTrace];
|
||||
@@ -139,10 +173,6 @@ export function donutView(source: PlotlyFigure, hierarchy: DonutHierarchy, paren
|
||||
x: (plotDomain.x[0] + plotDomain.x[1]) / 2,
|
||||
y: (plotDomain.y[0] + plotDomain.y[1]) / 2,
|
||||
};
|
||||
figure.layout['showlegend'] = false;
|
||||
figure.layout['height'] = 440;
|
||||
figure.layout['margin'] = { ...(record(figure.layout['margin']) ? figure.layout['margin'] : {}),
|
||||
l: 16, r: 16, t: 16, b: 16, pad: 0, autoexpand: false };
|
||||
const annotations = figure.layout['annotations'];
|
||||
if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a)
|
||||
? { ...a, x: center.x, y: center.y, xanchor: 'center', yanchor: 'middle' } : a);
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { vi } from 'vitest';
|
||||
import { donutPeriodFigures } from './indicadores-donut-periods';
|
||||
import { Dominio, FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile';
|
||||
|
||||
const periods = ['2025-S2', '2025-S1', '2026-S1'];
|
||||
const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_donas', tipoPeriodo: 'semestre', tema: 'claro', periodos: periods };
|
||||
function multiData(): IndicadorDatos {
|
||||
const data = c2Fixture();
|
||||
return { ...data, periodos: [...periods], filas: periods.flatMap((periodo, i) => data.filas.map(r => ({ ...r, periodo, n: Number(r['n']) + i }))) };
|
||||
}
|
||||
function multiFigure(): PlotlyFigure {
|
||||
return { data: periods.map((p, i) => ({ type: 'pie', name: p, hole: .62, labels: ['A', 'B', 'C'], values: [6 + i, 3 + i, 1 + i],
|
||||
domain: { x: [i / 3, (i + 1) / 3], y: [0, 1] }, customdata: [[p], [p], [p]], text: ['60%', '30%', '10%'], marker: { colors: ['red','blue','green'] } })),
|
||||
layout: { title: { text: 'Título publicado' }, annotations: [
|
||||
...periods.map((p, i) => ({ text: p + '<br>N publicado', x: (i + .5) / 3, y: .5, xref: 'paper', yref: 'paper', showarrow: false })),
|
||||
{ text: 'Nota metodológica íntegra', x: 0, y: -.22, xref: 'paper', yref: 'paper', showarrow: false },
|
||||
{ text: 'Anotación desconocida', x: .1, y: .8 },
|
||||
] }, config: { responsive: true }, extra: { retained: true } };
|
||||
}
|
||||
describe('selección de trazas por periodo de dona', () => {
|
||||
it('selecciona trazas, conserva arrays completos y normaliza dominio y anotación sin mutar HTTP', () => {
|
||||
const original = multiFigure(), before = JSON.stringify(original);
|
||||
const pages = donutPeriodFigures(original, selection)!;
|
||||
expect(pages.map(p => p.period)).toEqual(periods);
|
||||
pages.forEach(({ figure }, i) => {
|
||||
expect(figure.data).toHaveLength(1);
|
||||
expect(figure.data[0]).toEqual({ ...original.data[i], domain: { x: [0,1], y: [0,1] } });
|
||||
expect(figure.layout['annotations']).toEqual([
|
||||
expect.objectContaining({ text: periods[i] + '<br>N publicado', x: expect.closeTo(.5) }),
|
||||
...(original.layout['annotations'] as unknown[]).slice(3),
|
||||
]);
|
||||
expect(figure.config).toEqual(original.config); expect(figure['extra']).toEqual(original['extra']);
|
||||
});
|
||||
expect(JSON.stringify(original)).toBe(before);
|
||||
});
|
||||
it('no agrega trazas de un periodo sin datos ni convierte cero, null o supresión', () => {
|
||||
const original = multiFigure(); original.data.splice(1, 1);
|
||||
original.data[0]['values'] = [0, null, 10]; original.data[0]['customdata'] = [{ suprimido: true }];
|
||||
const pages = donutPeriodFigures(original, selection)!;
|
||||
expect(pages[0].figure.data[0]['values']).toEqual([0, null, 10]);
|
||||
expect(pages[0].figure.data[0]['customdata']).toEqual([{ suprimido: true }]);
|
||||
expect(pages[1].figure.data).toEqual([]);
|
||||
expect(pages[1].figure.layout['xaxis']).toMatchObject({ visible: false });
|
||||
expect(pages[0].figure.layout['annotations']).not.toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '<br>N publicado' })]));
|
||||
expect(pages[1].figure.layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '<br>N publicado', x: .5 })]));
|
||||
});
|
||||
it('mantiene ambos anillos de un único periodo y sus proporciones geométricas', () => {
|
||||
const source = multiFigure();
|
||||
source.data.push({ ...source.data[0], name: periods[0] + ', grupos', domain: { x: [.06333333333333333, .27], y: [.19,.81] } });
|
||||
const first = donutPeriodFigures(source, selection)![0].figure;
|
||||
expect(first.data.map(t => t['name'])).toEqual([periods[0], periods[0] + ', grupos']);
|
||||
expect((first.data[1]['domain'] as { x: number[] }).x[0]).toBeCloseTo(.19);
|
||||
expect((first.data[1]['domain'] as { x: number[] }).x[1]).toBeCloseTo(.81);
|
||||
});
|
||||
it('todos sigue el orden explícito de reportes o el recibido, sin ordenar por índice', () => {
|
||||
const all = { ...selection, periodos: undefined };
|
||||
expect(donutPeriodFigures(multiFigure(), all)!.map(p => p.period)).toEqual(periods);
|
||||
expect(donutPeriodFigures(multiFigure(), all, [...periods].reverse())!.map(p => p.period)).toEqual([...periods].reverse());
|
||||
});
|
||||
it('cero periodos y un solo periodo conservan el comportamiento anterior', () => {
|
||||
expect(donutPeriodFigures({ data: [], layout: {} }, { ...selection, periodos: [] })).toBeUndefined();
|
||||
const one = multiFigure(); one.data = [one.data[0]];
|
||||
expect(donutPeriodFigures(one, { ...selection, periodos: [periods[0]] })).toBeUndefined();
|
||||
expect(donutPeriodFigures({ data: [], layout: {} }, { ...selection, figura: 'fig_c2_barras' })).toBeUndefined();
|
||||
});
|
||||
it.each(['bar', 'animation', 'unidentified', 'solid-pie'])('no aplica a otra familia o navegación propia: %s', kind => {
|
||||
const source = multiFigure();
|
||||
if (kind === 'bar') source.data[0]['type'] = 'bar';
|
||||
if (kind === 'animation') source.frames = [{ data: [] }];
|
||||
if (kind === 'unidentified') source.data[0]['name'] = 'No identificado';
|
||||
if (kind === 'solid-pie') source.data[0]['hole'] = 0;
|
||||
expect(donutPeriodFigures(source, selection)).toBeUndefined();
|
||||
});
|
||||
it('admite otra representación publicada con la misma estructura de dona', () => {
|
||||
expect(donutPeriodFigures(multiFigure(), { ...selection, figura: 'future_donut' })).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure','label','showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
describe('navegación multiperiodo en el panel común', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http: HttpTestingController;
|
||||
const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] };
|
||||
function apply(selected = periods, revision = 1) {
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [...selected] }, revision });
|
||||
fixture.detectChanges();
|
||||
}
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController);
|
||||
for (const [name, value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro' })) fixture.componentRef.setInput(name, value);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
const panel = () => fixture.componentInstance;
|
||||
const card = () => fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
||||
const buttons = () => fixture.nativeElement.querySelectorAll('.donut-periods button') as NodeListOf<HTMLButtonElement>;
|
||||
function load(data = multiData()) { apply(); dataRequest().flush(data); fixture.detectChanges(); }
|
||||
it.each(['tea', 'cacu', 'cama'] as Dominio[])('%s: datos completos, navegación acotada sin HTTP ni cambio del filtro', domain => {
|
||||
fixture.componentRef.setInput('dominio', domain); load(); const applied = structuredClone(panel().applied);
|
||||
const host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false);
|
||||
for (let i = 0; i < periods.length; i++) {
|
||||
expect(panel().activeDonutPeriod).toBe(periods[i]);
|
||||
expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} / 3`);
|
||||
expect(card().chartFigure?.data).toHaveLength(1);
|
||||
expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true);
|
||||
if (i < 2) { buttons()[1].click(); fixture.detectChanges(); }
|
||||
}
|
||||
expect(buttons()[1].disabled).toBe(true); panel().changeDonutPeriod(1); expect(panel().activeDonutPeriod).toBe(periods[2]);
|
||||
buttons()[0].click(); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[1]);
|
||||
expect(panel().applied).toEqual(applied); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true);
|
||||
});
|
||||
it('dos periodos, controles nativos accesibles y sin interceptar Enter/Espacio', () => {
|
||||
apply(periods.slice(0,2)); dataRequest().flush({ ...multiData(), periodos: periods.slice(0,2), filas: multiData().filas.filter(r => r['periodo'] !== periods[2]) }); fixture.detectChanges();
|
||||
expect(buttons()[1].tagName).toBe('BUTTON'); expect(buttons()[1].type).toBe('button');
|
||||
expect(buttons()[1].getAttribute('aria-label')).toBe('Periodo siguiente de la dona');
|
||||
for (const key of ['Enter', ' ']) { const e = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); buttons()[1].dispatchEvent(e); expect(e.defaultPrevented).toBe(false); }
|
||||
buttons()[1].click(); fixture.detectChanges(); expect(buttons()[1].disabled).toBe(true);
|
||||
});
|
||||
it('retiene periodo activo seleccionado y elige primero si se elimina; no comparte índice con otra figura', () => {
|
||||
load(); panel().changeDonutPeriod(1); fixture.detectChanges();
|
||||
apply([periods[1], periods[2]], 2); dataRequest().flush({ ...multiData(), periodos: periods.slice(1), filas: multiData().filas.filter(r => r['periodo'] !== periods[0]) }); fixture.detectChanges();
|
||||
expect(panel().activeDonutPeriod).toBe(periods[1]);
|
||||
const subset = { ...multiData(), periodos: [periods[0], periods[2]], filas: multiData().filas.filter(r => r['periodo'] !== periods[1]) };
|
||||
apply([periods[0], periods[2]], 3); dataRequest().flush(subset); fixture.detectChanges();
|
||||
expect(panel().result().status).toBe('ready'); expect(panel().activeDonutPeriod).toBe(periods[0]);
|
||||
panel().changeDonutPeriod(1); fixture.detectChanges();
|
||||
fixture.componentRef.setInput('indicador', { ...item, id: 'otro' }); fixture.detectChanges();
|
||||
dataRequest().flush({ ...subset, id: 'otro' }); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[0]);
|
||||
});
|
||||
it('navegación limpia selección dependiente; cada nueva categoría declara el periodo', () => {
|
||||
load(); const selected = vi.fn(); panel().hierarchySelected.subscribe(selected);
|
||||
card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges();
|
||||
expect(selected).toHaveBeenLastCalledWith({ parent: 'G2', category: 'B', period: periods[0] });
|
||||
panel().changeDonutPeriod(1); fixture.detectChanges();
|
||||
expect(selected).toHaveBeenLastCalledWith({}); expect(card().activeParent).toBeUndefined(); expect(card().activeCategory).toBeUndefined();
|
||||
card().expandParent('G2'); expect(selected).toHaveBeenLastCalledWith({ parent: 'G2', period: periods[1] }); http.expectNone(() => true);
|
||||
});
|
||||
it('perfil y ancho se aplican también al navegar a páginas ya cargadas', () => {
|
||||
load(); fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); panel().updatePlotWidth(320);
|
||||
panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().plotWidth).toBe(320);
|
||||
expect(panel().result().footnotes).toEqual(multiData().notas); http.expectNone(() => true);
|
||||
});
|
||||
it('periodo vacío y cero conservan su identidad, notas y posibilidad de navegar', () => {
|
||||
const data = multiData(); data.filas = data.filas.filter(r => r['periodo'] !== periods[1]); data.filas.filter(r => r['periodo'] === periods[2]).forEach(r => r['n'] = 0);
|
||||
load(data); panel().changeDonutPeriod(1); fixture.detectChanges();
|
||||
expect(panel().result().figure?.data).toEqual([]); expect(fixture.nativeElement.textContent).toContain('No hay filas publicadas');
|
||||
expect(card().chartFigure?.layout['height']).toBe(440);
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart').style.getPropertyValue('--plot-height')).toBe('440px');
|
||||
panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().emptyMessage).toContain('conteos publicados son cero');
|
||||
expect(fixture.nativeElement.textContent).toContain('2026-S1'); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['null', 'suppressed', 'simple'])('/figuras %s separa las trazas sin peticiones por clic', kind => {
|
||||
const data = multiData();
|
||||
if (kind === 'null') data.filas[0]['n'] = null;
|
||||
else if (kind === 'suppressed') { data.filas[0]['n'] = null; data.filas[0]['suprimido'] = 1; }
|
||||
else delete data['unidad'];
|
||||
apply(); dataRequest().flush(data); const source = multiFigure();
|
||||
if (kind !== 'simple') source.data[0]['values'] = [null, 3, 1];
|
||||
const before = JSON.stringify(source); http.expectOne(r => r.url.includes('/figuras/')).flush(source); fixture.detectChanges();
|
||||
expect(panel().result().source).toBe('figuras'); expect(card().chartFigure?.data).toHaveLength(1);
|
||||
if (kind !== 'simple') expect(card().chartFigure?.data[0]['values']).toEqual([null,3,1]);
|
||||
panel().changeDonutPeriod(1); fixture.detectChanges(); expect(card().chartFigure?.data[0]['name']).toBe(periods[1]);
|
||||
expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true);
|
||||
});
|
||||
it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => {
|
||||
apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges();
|
||||
expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy();
|
||||
apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
// Published C2 trace identity, shared by simple pies and the two concentric rings.
|
||||
export function tracePeriod(trace: Record<string, unknown>): string | undefined {
|
||||
return typeof trace['name'] === 'string'
|
||||
? /^(\d{4}-(?:S[12]|0[1-9]|1[0-2]))(?:$|, )/.exec(trace['name'])?.[1] : undefined;
|
||||
}
|
||||
export function periodDatos(data: IndicadorDatos, period: string): IndicadorDatos {
|
||||
return { ...data, periodos: [period], filas: data.filas.filter(row => row['periodo'] === period) };
|
||||
}
|
||||
export interface DonutPeriodFigure { period: string; figure: PlotlyFigure; }
|
||||
|
||||
// Select traces before Plotly receives them. Never change counts, per-point
|
||||
// attributes, suppression, or the original response. Other chart families and
|
||||
// figures with their own animation/navigation retain their existing renderer.
|
||||
export function donutPeriodFigures(source: PlotlyFigure, selection: FigureSelection,
|
||||
reportedPeriods: readonly string[] = []): DonutPeriodFigure[] | undefined {
|
||||
if ((!source.data.length && selection.figura !== 'fig_c2_donas') || source.frames?.length
|
||||
|| source.layout['sliders'] !== undefined || source.layout['updatemenus'] !== undefined
|
||||
|| source.data.some(t => t['type'] !== 'pie' || typeof t['hole'] !== 'number' || t['hole'] <= 0 || t['hole'] >= 1 || !tracePeriod(t))) return;
|
||||
const received = [...new Set(source.data.map(t => tracePeriod(t)!))];
|
||||
const periods = [...new Set(selection.periodos ?? [...reportedPeriods, ...received])];
|
||||
if (!periods.length || periods.some(p => !selection.tipoPeriodo || parsePeriodos(p, selection.tipoPeriodo)?.[0] !== p)) return;
|
||||
// A single-period figure keeps its exact published geometry and annotations.
|
||||
if (periods.length === 1 && received.every(p => p === periods[0])) return;
|
||||
return periods.map(period => {
|
||||
const figure = structuredClone(source);
|
||||
figure.data = figure.data.filter(t => tracePeriod(t) === period);
|
||||
const domains = figure.data.map(t => t['domain']).filter(record);
|
||||
const xs = domains.flatMap(d => Array.isArray(d['x']) ? d['x'] as number[] : [0, 1]);
|
||||
const left = Math.min(...xs), right = Math.max(...xs);
|
||||
const normalize = (x: number) => (x - left) / (right - left);
|
||||
// Remove only period-labelled center annotations belonging to other pages.
|
||||
// Documentary notes and all unrecognized annotations remain untouched.
|
||||
if (Array.isArray(figure.layout['annotations'])) figure.layout['annotations'] = figure.layout['annotations'].flatMap(a => {
|
||||
if (!record(a) || a['xref'] !== 'paper' || a['yref'] !== 'paper' || a['y'] !== 0.5
|
||||
|| a['showarrow'] !== false || typeof a['text'] !== 'string') return [a];
|
||||
const owner = /(?:^|[^\d])(\d{4}-(?:S[12]|0[1-9]|1[0-2]))(?=$|[^\d])/.exec(a['text'])?.[1];
|
||||
if (!owner || ![...periods, ...reportedPeriods, ...received].includes(owner)) return [a];
|
||||
return owner === period ? [{ ...a, x: typeof a['x'] === 'number' && right > left ? normalize(a['x']) : 0.5 }] : [];
|
||||
});
|
||||
if (Number.isFinite(left) && Number.isFinite(right) && right > left) {
|
||||
for (const trace of figure.data) {
|
||||
const domain = trace['domain'];
|
||||
if (record(domain) && Array.isArray(domain['x']) && domain['x'].every(x => typeof x === 'number')) {
|
||||
trace['domain'] = { ...domain, x: domain['x'].map(normalize) };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!figure.data.length) {
|
||||
// An empty donut page has no Cartesian observations. Keep the active
|
||||
// suppression/availability annotation, without Plotly's default axes.
|
||||
for (const axis of ['xaxis', 'yaxis']) figure.layout[axis] = { ...(record(figure.layout[axis]) ? figure.layout[axis] : {}), visible: false };
|
||||
}
|
||||
return { period, figure };
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { Dominio, IndicadorMetadatos } from './indicadores.models';
|
||||
|
||||
// Existing WebApp explanations, shared by figures and the definitions section.
|
||||
// These are editorial guidance, not additional metadata supplied by WebApi.
|
||||
@@ -17,6 +17,13 @@ const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
};
|
||||
export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.';
|
||||
|
||||
export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined {
|
||||
const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId);
|
||||
if (!detail) return undefined;
|
||||
const instructions = detail.como_leer ?? [];
|
||||
return instructions.some(line => line.trim().length > 0) ? instructions : undefined;
|
||||
}
|
||||
|
||||
export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
|
||||
if (contract === 'C2') return [
|
||||
pie
|
||||
|
||||
@@ -202,7 +202,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
themedA.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => {
|
||||
it('UX-06D expandir metodología carga metadatos una vez y conserva panel, figura y borrador', () => {
|
||||
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
|
||||
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const filters = control();
|
||||
@@ -212,6 +212,10 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
http.expectOne(r => r.url === '/tea/indicadores/i1/metadatos').flush({});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false');
|
||||
expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
|
||||
@@ -158,7 +158,9 @@ describe('UX-05C búsqueda local y partición estable', () => {
|
||||
const helpIds = helps.map(button => button.getAttribute('aria-controls')!);
|
||||
expect(new Set(helpIds).size).toBe(5);
|
||||
for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true);
|
||||
helps[0].click(); fixture.detectChanges(); await settle();
|
||||
helps[0].click(); fixture.detectChanges();
|
||||
http.expectOne(r => r.url.endsWith('/metadatos')).flush({});
|
||||
fixture.detectChanges(); await settle();
|
||||
expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']);
|
||||
expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]);
|
||||
for (const query of ['sexo', 'evaluacion', '']) {
|
||||
|
||||
@@ -35,10 +35,45 @@ describe('Barras estratificadas: activación y caché',()=>{
|
||||
fixture.componentInstance.changeDimension(''); http.expectNone(()=>true);
|
||||
expect(fixture.componentInstance.result().figure?.data[0]['x']).toEqual(general().filas.map(r=>r['n']));
|
||||
});
|
||||
it('reemplaza el selector por un toggle accesible y conserva las dimensiones publicadas',()=>{
|
||||
fixture.detectChanges(); request().flush(general()); fixture.detectChanges();
|
||||
const toggle = fixture.nativeElement.querySelectorAll('.distribution-toggle [role="radio"]') as NodeListOf<HTMLButtonElement>;
|
||||
expect(toggle).toHaveLength(2); expect(fixture.nativeElement.querySelector('select')).toBeNull();
|
||||
expect(toggle[0].textContent).toContain('Distribución general'); expect(toggle[0].getAttribute('aria-checked')).toBe('true');
|
||||
expect(toggle[1].getAttribute('aria-checked')).toBe('false'); expect(toggle[1].disabled).toBe(false);
|
||||
for(const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
toggle[1].dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.dimension).toBe('grupo_edad');
|
||||
expect(toggle[1].getAttribute('aria-checked')).toBe('true');
|
||||
expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2);
|
||||
for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); }
|
||||
});
|
||||
it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{
|
||||
fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'todos'}}); fixture.detectChanges();
|
||||
request().flush(general()); fixture.detectChanges();
|
||||
const stratified = fixture.nativeElement.querySelectorAll('.distribution-toggle [role="radio"]')[1] as HTMLButtonElement;
|
||||
expect(stratified.disabled).toBe(true); expect(stratified.getAttribute('aria-checked')).toBe('false');
|
||||
expect(fixture.nativeElement.querySelector('.distribution-note').textContent).toContain('Selecciona un periodo');
|
||||
expect(fixture.nativeElement.querySelector('.distribution-control').getAttribute('aria-describedby'))
|
||||
.toBe(fixture.nativeElement.querySelector('.distribution-note').id);
|
||||
});
|
||||
it('no declara ni consulta capacidades ausentes; no acepta ronda',()=>{
|
||||
fixture.componentRef.setInput('indicador',{...item,filtros:undefined});fixture.detectChanges();request().flush(general());fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('select')).toBeNull();fixture.componentInstance.changeDimension('grupo_edad');http.expectNone(()=>true);
|
||||
});
|
||||
it('aplica categoría solo en su periodo y limpia dependencia sin HTTP al restaurar',()=>{
|
||||
fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');request().flush(age);fixture.detectChanges();
|
||||
const all=structuredClone(fixture.componentInstance.result().figure);
|
||||
fixture.componentRef.setInput('localSelection',{parent:'Anormal',category:'LIEAG',period:'2025-S2'});fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure?.data[0]['y']).toEqual(['LIEAG']);
|
||||
fixture.componentRef.setInput('localSelection',{parent:'Anormal',category:'LIEAG',period:'2026-S1'});fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure).toEqual(all);
|
||||
fixture.componentRef.setInput('localSelection',{});fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().figure).toEqual(all);http.expectNone(()=>true);
|
||||
});
|
||||
it('cambio de periodo cancela transporte y consulta dimensión con el nuevo periodo',()=>{
|
||||
fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');const old=request();
|
||||
fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'explicit',periodos:['2026-S1']}});fixture.detectChanges();expect(old.cancelled).toBe(true);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
@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><caption>Columnas propuestas para revisión.</caption>
|
||||
<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>
|
||||
@@ -25,9 +25,7 @@
|
||||
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
|
||||
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
|
||||
@if (data; as response) {
|
||||
@if (response.simulado) { <p class="simulation" role="status">Datos simulados — uso de demostración</p> }
|
||||
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
|
||||
@if (provisional) { <p>Las reglas de selección son provisionales.</p> }
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
@@ -36,7 +34,7 @@
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr>
|
||||
<td>{{ item.id_seudonimo }}</td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c.bethesda) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
|
||||
@@ -27,9 +27,25 @@ export interface IndicadorDatosEstratificados extends IndicadorDatos {
|
||||
etiquetas_estrato: Record<string, string>;
|
||||
totales_estrato?: EstratoTotal[];
|
||||
}
|
||||
export interface IndicadorFicha {
|
||||
codigo?: string | null;
|
||||
para?: string | null;
|
||||
unidad?: string | null;
|
||||
pregunta?: string | null;
|
||||
definicion?: string | null;
|
||||
nota?: string | null;
|
||||
}
|
||||
export interface IndicadorFiguraDetalle {
|
||||
figura: string;
|
||||
descripcion: string | null;
|
||||
como_leer: string[] | null;
|
||||
}
|
||||
export interface IndicadorMetadatos {
|
||||
referencias?: { tipo: string; etiqueta: string; ref: string | null }[];
|
||||
poblaciones?: { grupo: string; codigo: string; descripcion: string }[];
|
||||
descripcion?: string | null;
|
||||
ficha?: IndicadorFicha | null;
|
||||
referencias?: { tipo: string; etiqueta: string; ref: string | null }[] | null;
|
||||
poblaciones?: { grupo: string; codigo: string; descripcion: string }[] | null;
|
||||
figuras_detalle?: IndicadorFiguraDetalle[] | null;
|
||||
categorias?: Record<string, { etiqueta: string; color?: string | null }>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,39 @@ describe('IndicadoresService HTTP', () => {
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
it('acepta metadatos de figura y conserva payloads anteriores sin figuras_detalle', () => {
|
||||
let legacy: unknown, nullDetails: unknown, current: unknown;
|
||||
service.metadatos('cacu', 'old').subscribe(value => legacy = value);
|
||||
http.expectOne('/cacu/indicadores/old/metadatos').flush({ descripcion: 'Anterior', ficha: null, referencias: null, poblaciones: null });
|
||||
service.metadatos('cacu', 'empty').subscribe(value => nullDetails = value);
|
||||
http.expectOne('/cacu/indicadores/empty/metadatos').flush({ figuras_detalle: null });
|
||||
service.metadatos('cacu', 'new').subscribe(value => current = value);
|
||||
http.expectOne('/cacu/indicadores/new/metadatos').flush({ figuras_detalle: [
|
||||
{ figura: 'fig_a', descripcion: null, como_leer: ['Una instrucción.', 'Otra instrucción.'] },
|
||||
{ figura: 'fig_b', descripcion: 'Descripción sin instrucciones.', como_leer: [] },
|
||||
{ figura: 'fig_c', descripcion: null, como_leer: null },
|
||||
] });
|
||||
expect(legacy).toMatchObject({ descripcion: 'Anterior' });
|
||||
expect(nullDetails).toMatchObject({ figuras_detalle: null });
|
||||
expect(current).toMatchObject({ figuras_detalle: [
|
||||
{ figura: 'fig_a', como_leer: ['Una instrucción.', 'Otra instrucción.'] },
|
||||
{ figura: 'fig_b', descripcion: 'Descripción sin instrucciones.', como_leer: [] },
|
||||
{ figura: 'fig_c', como_leer: null },
|
||||
] });
|
||||
});
|
||||
it.each([
|
||||
{ figuras_detalle: 'incorrecto' },
|
||||
{ figuras_detalle: [{ figura: '', descripcion: null, como_leer: [] }] },
|
||||
{ figuras_detalle: [{ figura: 'fig', descripcion: null, como_leer: [] }, { figura: 'fig', descripcion: null, como_leer: ['ambiguo'] }] },
|
||||
{ figuras_detalle: [{ figura: 'fig', descripcion: 1, como_leer: [] }] },
|
||||
{ figuras_detalle: [{ figura: 'fig', descripcion: null, como_leer: ['válida', 1] }] },
|
||||
])('rechaza elementos de figuras_detalle mal formados $figuras_detalle', payload => {
|
||||
let error: unknown;
|
||||
service.metadatos('cacu', 'i').subscribe({ error: value => error = value });
|
||||
http.expectOne('/cacu/indicadores/i/metadatos').flush(payload);
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => {
|
||||
service.catalogo(dominio).subscribe(items => {
|
||||
expect(items).toEqual(syntheticCatalogs[dominio]);
|
||||
@@ -117,4 +150,35 @@ describe('contrato datos exclusivo de KPI', () => {
|
||||
req.flush({ id: 'otro', contrato: 'C3r', tipo_periodo: 'semestre', periodos: [], filas: [] });
|
||||
expect(error).toBeInstanceOf(Error); http.verify();
|
||||
});
|
||||
it('serializa cero, uno, dos y tres filtros en un único parámetro ordenado', () => {
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const service = TestBed.inject(IndicadoresService);
|
||||
const comprobar = (filtros: readonly string[]) => {
|
||||
service.datos('cacu', 'cacu_eu7', 'mes', ['2025-01'], {
|
||||
estrato: 'grupo_edad', filtros,
|
||||
}).subscribe();
|
||||
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
||||
expect(req.request.params.getAll('filtro')).toEqual(filtros.length ? [filtros.join(',')] : null);
|
||||
expect(req.request.params.getAll('filtro')?.length ?? 0).toBe(filtros.length ? 1 : 0);
|
||||
expect(req.request.params.get('periodos')).toBe('2025-01');
|
||||
expect(req.request.params.get('estrato')).toBe('grupo_edad');
|
||||
req.flush({ id:'cacu_eu7', contrato:'C2', tipo_periodo:'mes', periodos:['2025-01'], filas:[], estrato:'grupo_edad' });
|
||||
};
|
||||
comprobar([]);
|
||||
comprobar(['grupo_edad:35-44']);
|
||||
comprobar(['grupo_edad:35-44', 'estatus_seguimiento:VIGILANCIA']);
|
||||
comprobar(['grupo_edad:35-44', 'estatus_seguimiento:VIGILANCIA', 'otra_dimension:valor']);
|
||||
});
|
||||
it('deja que HttpParams codifique caracteres reservados dentro de los pares', () => {
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const service = TestBed.inject(IndicadoresService);
|
||||
const pair = 'grupo_edad:35 & más';
|
||||
service.datos('cacu', 'cacu_eu7', 'mes', undefined, { filtros:[pair] }).subscribe();
|
||||
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
||||
expect(req.request.params.getAll('filtro')).toEqual([pair]);
|
||||
expect(req.request.params.toString()).toContain('filtro=grupo_edad:35%20%26%20m%C3%A1s');
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
expect(req.request.params.has('estrato')).toBe(false);
|
||||
req.flush({ id:'cacu_eu7', contrato:'C2', tipo_periodo:'mes', periodos:[], filas:[] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -30,12 +30,32 @@ export class IndicadoresService {
|
||||
metadatos(dominio: Dominio, indicador: string) {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(value => {
|
||||
if (!record(value)) throw new Error('Metadatos inválidos');
|
||||
const description = value['descripcion'];
|
||||
if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos');
|
||||
const ficha = value['ficha'];
|
||||
if (ficha !== undefined && ficha !== null) {
|
||||
if (!record(ficha)) throw new Error('Metadatos inválidos');
|
||||
for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) {
|
||||
const content = ficha[field];
|
||||
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
|
||||
}
|
||||
}
|
||||
for (const field of ['referencias', 'poblaciones']) {
|
||||
const list = value[field];
|
||||
if (list !== undefined && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
|
||||
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
|
||||
? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string')
|
||||
: typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos');
|
||||
}
|
||||
const figureDetails = value['figuras_detalle'];
|
||||
if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v)
|
||||
&& typeof v['figura'] === 'string' && v['figura'].trim().length > 0
|
||||
&& (v['descripcion'] === null || typeof v['descripcion'] === 'string')
|
||||
&& (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record<string, unknown>)['figura'])).size !== figureDetails.length) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
return value as IndicadorMetadatos;
|
||||
}));
|
||||
}
|
||||
@@ -49,7 +69,7 @@ export class IndicadoresService {
|
||||
if (!['grupo_edad', 'estatus_seguimiento'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
params = params.set('estrato', scope.estrato);
|
||||
}
|
||||
for (const filtro of scope.filtros ?? []) params = params.append('filtro', filtro);
|
||||
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
||||
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
|
||||
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => {
|
||||
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|
||||
|
||||
Reference in New Issue
Block a user