feat(indicadores): implementar catalogo expandible UX-05B
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, ViewChild } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { Dominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
imports: [MatButtonModule, MatCardModule, IndicadorFigurePanel],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
<h2 [id]="titleId">{{ indicador.titulo }}</h2>
|
||||
<p>{{ indicador.id }} · Contrato {{ indicador.contrato }} · {{ indicador.figuras.length }} figuras publicadas</p>
|
||||
<button #toggleButton mat-stroked-button [attr.aria-expanded]="expanded"
|
||||
[attr.aria-controls]="contentId" [attr.aria-label]="(expanded ? 'Contraer ' : 'Expandir ') + dominio + ' · ' + indicador.id + ' · ' + indicador.titulo"
|
||||
(click)="toggle()">{{ expanded ? 'Contraer' : 'Expandir' }}</button>
|
||||
</header>
|
||||
<div #content [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
@if (expanded) {
|
||||
@for (figure of indicador.figuras; track panelIdentity(figure)) {
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [figuraId]="figure" [tema]="tema" />
|
||||
} @empty { <p role="status">El indicador no tiene figuras disponibles.</p> }
|
||||
}
|
||||
</div>
|
||||
</mat-card>
|
||||
`,
|
||||
styles: ':host { display: block; margin: 1rem 0; } mat-card { padding: 1.25rem; } h2, p { overflow-wrap: anywhere; } h2 { margin-top: 0; }',
|
||||
})
|
||||
export class IndicadorCatalogCard implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) initialExpanded!: boolean;
|
||||
@ViewChild('toggleButton', { read: ElementRef }) toggleButton!: ElementRef<HTMLButtonElement>;
|
||||
@ViewChild('content') content!: ElementRef<HTMLElement>;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private identity = '';
|
||||
expanded = false;
|
||||
titleId = '';
|
||||
contentId = '';
|
||||
panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); }
|
||||
ngOnChanges() {
|
||||
const identity = indicatorIdentity(this.dominio, this.indicador.id);
|
||||
if (identity === this.identity) return;
|
||||
this.identity = identity;
|
||||
const id = identityElementId(identity);
|
||||
this.titleId = id + '-title';
|
||||
this.contentId = id + '-content';
|
||||
this.expanded = this.memory.expanded(this.dominio, this.indicador.id) ?? this.initialExpanded;
|
||||
}
|
||||
toggle() {
|
||||
if (this.expanded && this.content.nativeElement.contains(this.document.activeElement)) {
|
||||
this.toggleButton.nativeElement.focus();
|
||||
}
|
||||
this.expanded = !this.expanded;
|
||||
this.memory.rememberExpansion(this.dominio, this.indicador.id, this.expanded);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
<p class="period-note">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.</p>
|
||||
</section>
|
||||
}
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="state.status === 'loading'">
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.aria-label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (state.status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<p class="state" role="status">Cargando figura…</p>
|
||||
@@ -20,7 +20,7 @@
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figuraId }}</p>
|
||||
<app-plotly-chart [figure]="state.presentationFigure!" />
|
||||
<app-plotly-chart [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="state.presentationFigure!" />
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Dominio, hasNoVisibleValues, Indicador, PlotlyFigure, Tema } from './in
|
||||
import { figureTitle } from './indicadores.presentation';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
// The page owns requests; the card receives the original and its presentation copy.
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
export interface FigureState {
|
||||
status: 'idle' | 'loading' | 'ready' | 'error';
|
||||
figure?: PlotlyFigure;
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const catalog = [
|
||||
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] },
|
||||
];
|
||||
describe('IndicadorFigurePanel', () => {
|
||||
let page: IndicadorFigurePanel;
|
||||
let http: HttpTestingController;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function filters() {
|
||||
fixture.detectChanges();
|
||||
return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
}
|
||||
function load() { fixture.detectChanges(); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
|
||||
it.each([
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
|
||||
['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']],
|
||||
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
|
||||
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
|
||||
['toString', ['No hay una explicación específica']],
|
||||
])('explica el contrato %s y la distinción entre reporte y valores representables', (contract, expected) => {
|
||||
fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: contract, figuras: ['f1'] }); load();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
for (const text of expected) expect(help).toContain(text);
|
||||
if (contract === 'C3r') {
|
||||
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
|
||||
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
|
||||
}
|
||||
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
|
||||
});
|
||||
it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => {
|
||||
load();
|
||||
const received: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
|
||||
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const original = JSON.stringify(received);
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
expect(JSON.stringify(received)).toBe(original);
|
||||
expect(page.result().figure).toEqual(received);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
expect(chart.figure).toBe(page.result().presentationFigure);
|
||||
expect(chart.figure).not.toBe(page.result().figure);
|
||||
expect(chart.figure?.data).toEqual(received.data);
|
||||
expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } });
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
expect(page.filters?.applied?.selection.mode).toBe('todos');
|
||||
page.applyFilters();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
page.applyFilters();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('cancela figuras al cambiar tema rápidamente', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const dark = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(dark.request.params.get('tema')).toBe('oscuro');
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges();
|
||||
expect(dark.cancelled).toBe(true);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it.each([
|
||||
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
|
||||
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
|
||||
load();
|
||||
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().message).toContain(message);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('error privado');
|
||||
fixture.nativeElement.querySelector('app-indicador-figure-card button').click();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
expect(page.result().status).toBe('ready');
|
||||
});
|
||||
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
|
||||
load(); figure().error(new ProgressEvent('error'));
|
||||
expect(page.result().message).toContain('conectar');
|
||||
page.requestFigure();
|
||||
const pending = figure();
|
||||
fixture.destroy();
|
||||
expect(pending.cancelled).toBe(true);
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
page.applyFilters();
|
||||
const req = figure();
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
req.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
const retry = figure();
|
||||
expect(retry.request.params.get('periodos')).toBe(periodos.join(','));
|
||||
retry.flush({ data: [{ y: [null] }], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const themed = figure();
|
||||
expect(themed.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themed.request.params.get('tema')).toBe('oscuro');
|
||||
themed.flush('error', { status: 500, statusText: 'Server Error' });
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
page.applyFilters(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { presentationFigure } from './indicadores.presentation';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { FilterState, IndicadoresMemory, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorPeriodFilters, IndicadorFigureCard],
|
||||
template: `
|
||||
<section [attr.aria-labelledby]="titleId">
|
||||
<h3 [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
|
||||
@if (filters; as state) {
|
||||
<app-indicador-period-filters [state]="state" [types]="indicador.tipos_periodo"
|
||||
(edited)="filtersEdited()" (apply)="applyFilters()" />
|
||||
}
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (retry)="requestFigure()" />
|
||||
</section>
|
||||
`,
|
||||
styles: ':host { display: block; min-width: 0; } section { margin-top: 1.5rem; } h3 { overflow-wrap: anywhere; }',
|
||||
})
|
||||
export class IndicadorFigurePanel implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly figureRequests = new Subject<FigureSelection | null>();
|
||||
private identity = '';
|
||||
titleId = '';
|
||||
filters?: FilterState;
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
constructor() {
|
||||
this.figureRequests.pipe(switchMap(selection => selection
|
||||
? defer(() => this.service.figura(selection)).pipe(
|
||||
map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState),
|
||||
catchError(error => of({
|
||||
status: 'error',
|
||||
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
|
||||
&& (selection.periodos?.length ?? 0) > 1
|
||||
? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''),
|
||||
} as FigureState)),
|
||||
startWith({ status: 'loading' } as FigureState))
|
||||
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(state => this.result.set(state));
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.identity || changes['indicador']) {
|
||||
// Save the departing identity before accepting a new catalog object.
|
||||
this.saveCurrent();
|
||||
this.identity = identity;
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
this.filters = this.indicador.figuras.includes(this.figuraId)
|
||||
? this.memory.restore(this.dominio, this.indicador, this.figuraId) : undefined;
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
} else if (changes['tema']) this.requestFigure();
|
||||
}
|
||||
private saveCurrent() {
|
||||
if (!this.filters || !this.identity) return;
|
||||
const [domain, indicator, figure] = JSON.parse(this.identity) as [Dominio, string, string];
|
||||
this.memory.save(domain, indicator, figure, this.filters);
|
||||
}
|
||||
filtersEdited() { this.saveCurrent(); }
|
||||
applyFilters() {
|
||||
if (!this.filters) return;
|
||||
const draft = this.filters.editors[this.filters.tipo]!.draft;
|
||||
if (!validDraft(draft, this.filters.tipo, this.indicador.tipos_periodo)) return;
|
||||
this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) };
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
requestFigure() {
|
||||
const applied = this.filters?.applied;
|
||||
if (!this.indicador.figuras.includes(this.figuraId) || !applied
|
||||
|| !validDraft(applied.selection, applied.tipo, this.indicador.tipos_periodo)) {
|
||||
this.figureRequests.next(null);
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({
|
||||
dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId,
|
||||
tipoPeriodo: applied.tipo, tema: this.tema,
|
||||
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
|
||||
});
|
||||
}
|
||||
ngOnDestroy() { this.saveCurrent(); }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
describe('UX-05B contrato de figuras del catálogo', () => {
|
||||
it.each([{ figuras: [] }, { figuras: ['f'] }, { figuras: ['f', 'g'] }])('acepta figuras publicadas $figuras', ({ figuras }) => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
let actual: unknown;
|
||||
TestBed.inject(IndicadoresService).catalogo('tea').subscribe(value => actual = value);
|
||||
const items = [{ id: 'i', titulo: 'I', contrato: 'C1', figuras, tipos_periodo: ['mes'] }];
|
||||
http.expectOne('/tea/indicadores').flush(items); expect(actual).toEqual(items); http.verify();
|
||||
});
|
||||
it('rechaza figuras duplicadas dentro de un indicador', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
let error: unknown; let emitted = false;
|
||||
TestBed.inject(IndicadoresService).catalogo('tea').subscribe({ next: () => emitted = true, error: e => error = e });
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'f'], tipos_periodo: ['mes'] }]);
|
||||
expect(error).toBeInstanceOf(Error); expect(emitted).toBe(false); http.verify();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
|
||||
export function httpMessage(error: unknown, catalog = false): string {
|
||||
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
|
||||
if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.';
|
||||
if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.';
|
||||
if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.';
|
||||
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
|
||||
return 'No se pudo completar la solicitud. Intenta nuevamente.';
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { figureIdentity, indicatorIdentity, identityElementId } from './indicadores-identities';
|
||||
describe('UX-05B identidades', () => {
|
||||
it('separa dominios, indicadores y figuras sin colisiones por delimitadores', () => {
|
||||
const ids = [indicatorIdentity('tea', 'a/b'), indicatorIdentity('cacu', 'a/b'), figureIdentity('tea', 'a/b', 'c'), figureIdentity('tea', 'a', 'b/c'), figureIdentity('tea', 'a', 'á')];
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
expect(new Set(ids.map(identityElementId)).size).toBe(ids.length);
|
||||
expect(ids.map(identityElementId).every(id => /^[a-z0-9-]+$/.test(id))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Dominio } from './indicadores.models';
|
||||
|
||||
// JSON tuples preserve identity even when published IDs contain separators.
|
||||
export function indicatorIdentity(domain: Dominio, indicator: string): string {
|
||||
return JSON.stringify([domain, indicator]);
|
||||
}
|
||||
export function figureIdentity(domain: Dominio, indicator: string, figure: string): string {
|
||||
return JSON.stringify([domain, indicator, figure]);
|
||||
}
|
||||
export function identityElementId(identity: string): string {
|
||||
return 'indicadores-' + Array.from(identity, char => char.codePointAt(0)!.toString(16)).join('-');
|
||||
}
|
||||
@@ -35,20 +35,24 @@ describe('UX-04 memoria temporal', () => {
|
||||
['cacu', indicador, 'f'], ['tea', { ...indicador, id: 'otro' }, 'f'], ['tea', indicador, 'g'],
|
||||
] as const) expect(memory.restore(domain, item, figure).editors.semestre?.draft.mode).toBe('todos');
|
||||
});
|
||||
it('recuerda indicador, tema y figura por indicador', () => {
|
||||
memory.remember('cacu', 'i', 'g', 'oscuro');
|
||||
memory.remember('cacu', 'otro', 'f', 'claro');
|
||||
expect(memory.navigation('cacu')).toEqual({ indicador: 'otro', tema: 'claro' });
|
||||
expect(memory.selectedFigure('cacu', 'i')).toBe('g');
|
||||
expect(memory.navigation('tea')).toBeUndefined();
|
||||
it('distingue ausencia de expansión, true y false y aísla dominios', () => {
|
||||
expect(memory.expanded('tea', 'i')).toBeUndefined();
|
||||
memory.rememberExpansion('tea', 'i', false);
|
||||
memory.rememberExpansion('cacu', 'i', true);
|
||||
expect(memory.expanded('tea', 'i')).toBe(false);
|
||||
expect(memory.expanded('cacu', 'i')).toBe(true);
|
||||
expect(memory.expanded('tea', 'otro')).toBeUndefined();
|
||||
memory.rememberTheme('cacu', 'oscuro');
|
||||
expect(memory.theme('cacu')).toBe('oscuro');
|
||||
expect(memory.theme('tea')).toBe('claro');
|
||||
});
|
||||
it('una instancia nueva reinicia las selecciones y no lee ni escribe almacenamiento', () => {
|
||||
const localRead = vi.spyOn(Storage.prototype, 'getItem');
|
||||
const localWrite = vi.spyOn(Storage.prototype, 'setItem');
|
||||
memory.remember('tea', 'otro', 'g', 'oscuro');
|
||||
memory.rememberTheme('tea', 'oscuro'); memory.rememberExpansion('tea', 'i', false);
|
||||
memory.save('tea', 'i', 'f', { tipo: 'mes', editors: { mes: { added: [], draft: { mode: 'empty' } } } });
|
||||
const fresh = new IndicadoresMemory();
|
||||
expect(fresh.navigation('tea')).toBeUndefined();
|
||||
expect(fresh.theme('tea')).toBe('claro'); expect(fresh.expanded('tea', 'i')).toBeUndefined();
|
||||
expect(fresh.restore('tea', indicador, 'f').tipo).toBe('semestre');
|
||||
expect(localRead).not.toHaveBeenCalled(); expect(localWrite).not.toHaveBeenCalled();
|
||||
localRead.mockRestore(); localWrite.mockRestore();
|
||||
|
||||
@@ -37,14 +37,16 @@ export function pending(state: FilterState): boolean {
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresMemory {
|
||||
private readonly domains = new Map<Dominio, { indicador: string; tema: Tema }>();
|
||||
private readonly figures = new Map<string, string>();
|
||||
private readonly themes = new Map<Dominio, Tema>();
|
||||
private readonly expansions = new Map<string, boolean>();
|
||||
private readonly filters = new Map<string, FilterState>();
|
||||
navigation(domain: Dominio) { return this.domains.get(domain); }
|
||||
selectedFigure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); }
|
||||
remember(domain: Dominio, indicador: string, figura: string, tema: Tema) {
|
||||
this.domains.set(domain, { indicador, tema });
|
||||
this.figures.set(JSON.stringify([domain, indicador]), figura);
|
||||
theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; }
|
||||
rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); }
|
||||
expanded(domain: Dominio, indicador: string): boolean | undefined {
|
||||
return this.expansions.get(JSON.stringify([domain, indicador]));
|
||||
}
|
||||
rememberExpansion(domain: Dominio, indicador: string, expanded: boolean) {
|
||||
this.expansions.set(JSON.stringify([domain, indicador]), expanded);
|
||||
}
|
||||
private key(domain: Dominio, indicador: string, figura: string) {
|
||||
return JSON.stringify([domain, indicador, figura]);
|
||||
|
||||
@@ -6,6 +6,8 @@ import { provideRouter, Router } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { routes } from '../../app.routes';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
@@ -13,7 +15,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
|
||||
describe('UX-04 navegación Angular', () => {
|
||||
@@ -24,8 +26,11 @@ describe('UX-04 navegación Angular', () => {
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
return RouterTestingHarness.create();
|
||||
}
|
||||
function load(domain: 'tea' | 'cacu' | 'cama') {
|
||||
function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]);
|
||||
harness.detectChanges();
|
||||
const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
if (!card.expanded) { card.toggle(); harness.detectChanges(); }
|
||||
const req = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
return req;
|
||||
@@ -34,40 +39,40 @@ describe('UX-04 navegación Angular', () => {
|
||||
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
|
||||
const harness = await setup();
|
||||
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
load('tea'); harness.detectChanges();
|
||||
load('tea', harness); harness.detectChanges();
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
tea.applyFilters();
|
||||
(harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).applyFilters();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu');
|
||||
await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama');
|
||||
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu', harness);
|
||||
await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama', harness);
|
||||
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
const req = load('tea');
|
||||
const req = load('tea', harness);
|
||||
expect(req.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(restored.filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
||||
});
|
||||
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
|
||||
let harness = await setup();
|
||||
const page = await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage);
|
||||
load('cacu'); harness.detectChanges();
|
||||
page.changeTema('oscuro');
|
||||
load('cacu', harness); harness.detectChanges();
|
||||
page.changeTema('oscuro'); harness.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add();
|
||||
page.applyFilters();
|
||||
(harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).applyFilters();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const url = TestBed.inject(Router).url;
|
||||
http.verify(); TestBed.resetTestingModule();
|
||||
harness = await setup();
|
||||
const restarted = await harness.navigateByUrl(url, IndicadoresPage);
|
||||
const req = load('cacu');
|
||||
const req = load('cacu', harness);
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||
expect(restarted.indicadorId).toBe(syntheticCatalogs.cacu[0].id);
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).expanded).toBe(true);
|
||||
expect(restarted.tema).toBe('claro');
|
||||
expect(restarted.filters?.tipo).toBe('semestre');
|
||||
expect(restarted.filters?.editors.mes?.draft.mode).toBe('empty');
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.tipo).toBe('semestre');
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.editors.mes?.draft.mode).toBe('empty');
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
expect(req.request.params.get('tema')).toBe('claro');
|
||||
});
|
||||
|
||||
@@ -21,32 +21,15 @@
|
||||
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
|
||||
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
|
||||
} @else {
|
||||
<mat-card class="filters" aria-label="Selección de figura">
|
||||
<div class="fields">
|
||||
<mat-form-field class="indicator"><mat-label>Indicador</mat-label>
|
||||
<mat-select [ngModel]="indicadorId" (ngModelChange)="selectIndicador($event)">
|
||||
@for (item of catalog(); track item.id) { <mat-option [value]="item.id">{{ item.titulo }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Figura</mat-label>
|
||||
<mat-select [ngModel]="figuraId" (ngModelChange)="selectFigura($event)" [disabled]="!selected?.figuras?.length">
|
||||
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Tema de la figura</mat-label>
|
||||
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
|
||||
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
@if (filters; as state) {
|
||||
<app-indicador-period-filters [state]="state" [types]="selected!.tipos_periodo"
|
||||
(edited)="filtersEdited()" (apply)="applyFilters()" />
|
||||
}
|
||||
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
|
||||
</mat-card>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="selected"
|
||||
[figuraId]="figuraId" [dominio]="dominio" [tema]="tema"
|
||||
(retry)="requestFigure()" />
|
||||
<mat-form-field><mat-label>Tema del dominio</mat-label>
|
||||
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
|
||||
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<p role="status">{{ catalog().length }} indicadores publicados</p>
|
||||
@for (item of catalog(); track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema"
|
||||
[initialExpanded]="catalog().length === 1" />
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
@@ -4,18 +4,6 @@ h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; }
|
||||
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
|
||||
.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; }
|
||||
.filters { padding: 1.5rem; margin: 1.5rem 0; }
|
||||
.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; }
|
||||
.indicator { grid-column: span 2; }
|
||||
.periods { grid-column: 1 / -1; margin-bottom: 1rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; }
|
||||
.validation { color: var(--mat-sys-error); }
|
||||
.state { padding: 1.25rem; margin: 0; }
|
||||
@media (max-width: 850px) { .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 550px) {
|
||||
.fields { grid-template-columns: minmax(0, 1fr); }
|
||||
.indicator { grid-column: auto; }
|
||||
.filters { padding: 1rem; }
|
||||
h1 { font: var(--mat-sys-headline-medium); }
|
||||
}
|
||||
mat-form-field { width: 100%; max-width: 24rem; }
|
||||
@media (max-width: 550px) { h1 { font: var(--mat-sys-headline-medium); } }
|
||||
|
||||
@@ -1,449 +1,220 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { NgModel } from '@angular/forms';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const catalog = [
|
||||
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] },
|
||||
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] },
|
||||
];
|
||||
describe('IndicadoresPage', () => {
|
||||
const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] };
|
||||
describe('UX-05B catálogo expandible', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
page = fixture.componentInstance;
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function filters() {
|
||||
fixture.detectChanges();
|
||||
return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
function load(items: Indicador[] = [item, second], domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
}
|
||||
function load() { http.expectOne('/tea/indicadores').flush(catalog); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
|
||||
function toggle(index = 0) { cards()[index].toggle(); fixture.detectChanges(); }
|
||||
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
|
||||
function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); }
|
||||
function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; }
|
||||
|
||||
it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: Material se estabiliza al editar y restaurar %s sin HTTP', async id => {
|
||||
http.expectOne('/tea/indicadores').flush(syntheticCatalogs.tea);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador(id);
|
||||
figure().flush({ data: [{ type: 'bar', y: [50, 50] }], layout: { barmode: 'stack' } });
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
if (id === 'M02_sexo') expect(page.figuraId).toBe('fig_c2_apiladas');
|
||||
const result = page.result();
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save');
|
||||
const child = () => fixture.debugElement.query(By.directive(IndicadorPeriodFilters));
|
||||
const mode = () => child().queryAll(By.directive(MatSelect))[0].componentInstance as MatSelect;
|
||||
async function choose(value: string) {
|
||||
const select = mode();
|
||||
select.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(true);
|
||||
const option = select.options.find(o => o.value === value)!;
|
||||
(document.getElementById(option.id) as HTMLElement).click();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(false);
|
||||
}
|
||||
async function togglePanel() {
|
||||
const count = saves.mock.calls.length;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const select = mode();
|
||||
select.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(true);
|
||||
select.close(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(false);
|
||||
}
|
||||
expect(saves).toHaveBeenCalledTimes(count);
|
||||
http.expectNone(() => true);
|
||||
expect(page.result()).toBe(result);
|
||||
expect(chart.figure).toBe(result.presentationFigure);
|
||||
}
|
||||
await togglePanel();
|
||||
await choose('manual');
|
||||
expect(filters().entry.draft.mode).toBe('empty');
|
||||
expect(filters().canApply).toBe(false);
|
||||
await togglePanel();
|
||||
await choose('todos');
|
||||
await choose('manual');
|
||||
expect(saves).toHaveBeenCalledTimes(3);
|
||||
// Restoring the empty pending draft must also settle.
|
||||
const other = id === 'M02_sexo' ? 'K01_evaluacion_3_meses' : 'M02_sexo';
|
||||
page.selectIndicador(other); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador(id);
|
||||
const returned = figure(); expect(returned.request.params.has('periodos')).toBe(false);
|
||||
returned.flush({ data: [], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
let control = filters(); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
http.expectNone(() => true);
|
||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||
page.selectIndicador(other); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador(id);
|
||||
const restored = figure(); expect(restored.request.params.has('periodos')).toBe(false);
|
||||
restored.flush({ data: [], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
expect(control.hasPending).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
it.each([0, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => {
|
||||
const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i }));
|
||||
load(items);
|
||||
expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id));
|
||||
expect(cards().every(c => !c.expanded)).toBe(true);
|
||||
expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/'));
|
||||
if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
|
||||
});
|
||||
it('cancela figura y catálogo antiguos al cambiar dominios rápidamente', () => {
|
||||
load(); const oldFigure = figure();
|
||||
page.changeDominio('cacu');
|
||||
expect(oldFigure.cancelled).toBe(true);
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.catalog()).toEqual([]);
|
||||
const oldCatalog = http.expectOne('/cacu/indicadores');
|
||||
page.changeDominio('cama');
|
||||
expect(oldCatalog.cancelled).toBe(true);
|
||||
http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama);
|
||||
const current = http.expectOne(r => r.url.startsWith('/cama/indicadores/') && r.url.includes('/figuras/'));
|
||||
current.flush({ data: [{ y: [null, 42] }], layout: {} });
|
||||
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow();
|
||||
expect(() => oldFigure.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.dominio).toBe('cama');
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([null, 42]);
|
||||
it('un indicador se abre y consulta exactamente una vez cada figura publicada', () => {
|
||||
load([item]); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(2);
|
||||
request('f1').flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} });
|
||||
fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it.each(['cacu', 'cama'] as const)('edita meses sin HTTP y conserva ayuda sin Wilson efectivo en %s', dominio => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
page.changeDominio(dominio);
|
||||
http.expectOne('/' + dominio + '/indicadores').flush(syntheticCatalogs[dominio]);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ y: [null, 0] }], layout: {} });
|
||||
const control = filters();
|
||||
control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
expect(page.result().status).toBe('ready');
|
||||
control.year = '2025'; control.unit = '01'; control.add();
|
||||
control.unit = '02'; control.add();
|
||||
control.unit = '01'; control.add();
|
||||
expect(control.error).toContain('ya está agregado');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
page.applyFilters();
|
||||
const monthly = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(monthly.request.params.get('periodos')).toBe('2025-01,2025-02');
|
||||
control.unit = '13'; control.add();
|
||||
expect(control.error).toContain('unidad válida');
|
||||
expect(monthly.cancelled).toBe(false);
|
||||
control.changeMode('todos');
|
||||
expect(control.entry.draft.mode).toBe('explicit');
|
||||
control.changeTipo('semestre');
|
||||
expect(control.entry.draft.mode).toBe('todos');
|
||||
expect(monthly.cancelled).toBe(false);
|
||||
page.applyFilters();
|
||||
expect(monthly.cancelled).toBe(true);
|
||||
const semesters = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(semesters.request.params.has('periodos')).toBe(false);
|
||||
semesters.flush({ data: [{ y: [null, 0] }], layout: {} });
|
||||
fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
expect(help).toContain('no entregan intervalos Wilson efectivos');
|
||||
expect(help).toContain('eje horizontal muestra el periodo');
|
||||
expect(help).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
expect(help).not.toContain('La línea vertical representa el intervalo');
|
||||
it('la preferencia false prevalece sobre apertura automática al volver', () => {
|
||||
load([item]); flushAll(); toggle();
|
||||
fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
load([item]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true);
|
||||
});
|
||||
it('acepta futuros indicadores y figuras desde catálogo sin fijar cantidades ni contratos por dominio', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
page.changeDominio('cama');
|
||||
const future = [
|
||||
...syntheticCatalogs.cama,
|
||||
{ id: 'synthetic_future', titulo: 'Fixture futuro', contrato: 'C2', figuras: ['fig_c2_apiladas', 'fig_c1_puntos'], tipos_periodo: ['mes', 'semestre'] },
|
||||
];
|
||||
http.expectOne('/cama/indicadores').flush(future);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
page.selectIndicador('synthetic_future');
|
||||
expect(page.filters?.tipo).toBe('mes');
|
||||
const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas'));
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } });
|
||||
fixture.detectChanges();
|
||||
expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('composición porcentual');
|
||||
page.selectFigura('fig_c1_puntos');
|
||||
http.expectOne(r => r.url.includes('/fig_c1_puntos')).flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect((fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard).interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos');
|
||||
it('indicador sin figuras informa y no consulta HTTP', () => {
|
||||
load([{ ...item, figuras: [] }]); expect(cards()[0].expanded).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles');
|
||||
expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
|
||||
expect(page.catalogLoading()).toBe(true);
|
||||
load();
|
||||
expect(page.indicadorId).toBe('i1');
|
||||
expect(page.figuraId).toBe('f1');
|
||||
expect(page.result().status).toBe('loading');
|
||||
const request = figure();
|
||||
expect(request.request.params.has('periodos')).toBe(false);
|
||||
request.flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
it('varias tarjetas y figuras abiertas mantienen solicitudes concurrentes independientes', () => {
|
||||
load(); toggle(0); const a = request('f1'), b = request('f2'); toggle(1); const c = request('g');
|
||||
expect(a.cancelled).toBe(false); expect(b.cancelled).toBe(false);
|
||||
b.flush({ data: [{ y: [2] }], layout: {} }); c.flush({ data: [{ y: [3] }], layout: {} });
|
||||
a.flush({ data: [{ y: [1] }], layout: {} });
|
||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2], [3]]);
|
||||
expect(cards().every(c => c.expanded)).toBe(true);
|
||||
});
|
||||
it('contraer cancela solo sus figuras, descarta respuestas y destruye paneles', () => {
|
||||
load(); toggle(); toggle(1); const a = request('f1'), b = request('f2'), c = request('g');
|
||||
toggle(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true); expect(c.cancelled).toBe(false);
|
||||
expect(() => a.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(panels()).toHaveLength(1); c.flush({ data: [{ y: [3] }], layout: {} });
|
||||
expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]);
|
||||
});
|
||||
it('404 y reintento afectan solo una figura y 200 sin puntos sigue siendo resultado', () => {
|
||||
load([item]); const a = request('f1'), b = request('f2');
|
||||
a.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
b.flush({ data: [{ y: [null] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].result().status).toBe('error'); expect(panels()[1].result().status).toBe('ready');
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación');
|
||||
panels()[0].requestFigure(); request('f1').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it.each([
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
|
||||
['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']],
|
||||
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
|
||||
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
|
||||
['toString', ['No hay una explicación específica']],
|
||||
])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => {
|
||||
http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
for (const text of expected) expect(help).toContain(text);
|
||||
if (contract === 'C3r') {
|
||||
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
|
||||
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
|
||||
it('edición y aplicación son independientes por figura y tema utiliza aplicación', () => {
|
||||
load([item]); flushAll(); const a = control(), b = control(1);
|
||||
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||
panels()[0].applyFilters(); const applied = request('f1'); expect(applied.request.params.get('periodos')).toBe('2025-S1');
|
||||
applied.flush({ data: [], layout: {} }); a.unit = 'S2'; a.add();
|
||||
b.changeTipo('mes'); b.year = '2026'; b.unit = '01'; b.add();
|
||||
page.changeTema('oscuro'); fixture.detectChanges();
|
||||
const themedA = request('f1'), themedB = request('f2');
|
||||
expect(themedA.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themedB.request.params.has('periodos')).toBe(false);
|
||||
expect(themedA.request.params.get('tema')).toBe('oscuro');
|
||||
expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(b.selectedPeriods).toEqual(['2026-01']);
|
||||
themedA.flush({ data: [], layout: {} }); themedB.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('cerrar y reabrir restaura borrador y aplicado por figura sin confirmar borradores', () => {
|
||||
load([item]); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
|
||||
panels()[0].applyFilters(); request('f1').flush({ data: [], layout: {} }); a.unit = 'S2'; a.add();
|
||||
control(1).changeTipo('mes'); control(1).year = '2026'; control(1).unit = '01'; control(1).add();
|
||||
toggle(); toggle();
|
||||
const restored = request('f1'); expect(restored.request.params.get('periodos')).toBe('2025-S1');
|
||||
const other = request('f2'); expect(other.request.params.has('periodos')).toBe(false);
|
||||
expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(control(1).selectedPeriods).toEqual(['2026-01']);
|
||||
restored.flush({ data: [], layout: {} }); other.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => {
|
||||
load(); toggle(); const a = request('f1'), b = request('f2');
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true);
|
||||
const darkA = request('f1'), darkB = request('f2');
|
||||
expect(darkA.request.params.get('tema')).toBe('oscuro'); http.expectNone(r => r.url.endsWith('/g'));
|
||||
darkA.flush({ data: [], layout: {} }); darkB.flush({ data: [], layout: {} });
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); http.expectNone(() => true);
|
||||
toggle(1); const later = request('g'); expect(later.request.params.get('tema')).toBe('oscuro'); later.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('salir del dominio cancela paneles y catálogos obsoletos', () => {
|
||||
load(); toggle(); const a = request('f1'), b = request('f2');
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true);
|
||||
const oldCatalog = http.expectOne('/cacu/indicadores'); page.changeDominio('cama'); fixture.detectChanges();
|
||||
expect(oldCatalog.cancelled).toBe(true); load(syntheticCatalogs.cama, 'cama'); flushAll();
|
||||
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
|
||||
});
|
||||
it('restaura expansión y tema de dominio sin aplicar borrador pendiente', () => {
|
||||
load(); toggle(); flushAll(); control().changeMode('manual');
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); flushAll();
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); flushAll();
|
||||
toggle(); page.changeDominio('tea'); fixture.detectChanges(); load();
|
||||
expect(cards()[0].expanded).toBe(true); expect(cards()[1].expanded).toBe(false);
|
||||
expect(page.tema).toBe('oscuro'); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false);
|
||||
expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} });
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu');
|
||||
expect(cards()[0].expanded).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true);
|
||||
});
|
||||
it('identidades estables conservan componentes al reordenar el catálogo', () => {
|
||||
load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0];
|
||||
page.catalog.set([second, item]); fixture.detectChanges();
|
||||
expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
||||
});
|
||||
it('identidad eliminada no se monta aunque exista preferencia anterior', () => {
|
||||
TestBed.inject(IndicadoresMemory).rememberExpansion('tea', 'removed', true);
|
||||
load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll();
|
||||
});
|
||||
it('botones semánticos anuncian expansión, IDs únicos y devuelven foco al contraer contenido', () => {
|
||||
load();
|
||||
const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf<HTMLButtonElement>;
|
||||
expect(buttons[0].tagName).toBe('BUTTON'); expect(buttons[0].getAttribute('aria-expanded')).toBe('false');
|
||||
buttons[0].click(); fixture.detectChanges(); flushAll();
|
||||
expect(buttons[0].getAttribute('aria-expanded')).toBe('true');
|
||||
expect(document.getElementById(buttons[0].getAttribute('aria-controls')!)).toBeTruthy();
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-period-filters mat-select') as HTMLElement;
|
||||
input.focus(); expect(document.activeElement).toBe(input); cards()[0].toggle(); fixture.detectChanges();
|
||||
expect(document.activeElement).toBe(buttons[0]);
|
||||
const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf<HTMLElement>).map(e => e.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label'));
|
||||
});
|
||||
it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => {
|
||||
load([item]); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } };
|
||||
const before = JSON.stringify(raw); request('f1').flush(raw); request('f2').flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges();
|
||||
expect(JSON.stringify(raw)).toBe(before); expect(panels()[0].result().figure).toEqual(raw);
|
||||
const charts = fixture.debugElement.queryAll(By.directive(ChartStub)); expect(charts).toHaveLength(2);
|
||||
expect(charts[0].componentInstance.figure).not.toBe(charts[1].componentInstance.figure);
|
||||
expect(panels()[0].result().presentationFigure).not.toBe(raw);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('reportes no están disponibles');
|
||||
});
|
||||
it.each(['cacu', 'cama'] as const)('preserva advertencias y filtros mensuales de %s', domain => {
|
||||
load([]); page.changeDominio(domain); load(syntheticCatalogs[domain], domain); flushAll();
|
||||
const c = control(); c.changeTipo('mes'); c.year = '2025'; c.unit = '01'; c.add(); http.expectNone(() => true);
|
||||
panels()[0].applyFilters(); const r = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('no entregan intervalos Wilson efectivos');
|
||||
expect(fixture.nativeElement.textContent).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
});
|
||||
it('catálogo error, reintento y vacío no dejan paneles', () => {
|
||||
http.expectOne('/tea/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges();
|
||||
expect(page.catalogError()).toContain('error interno'); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
page.retryCatalog(); load([]); expect(panels()).toHaveLength(0);
|
||||
});
|
||||
it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: %s conserva selección vacía estable al reabrir sin escrituras ni HTTP redundantes', async id => {
|
||||
load(syntheticCatalogs.tea);
|
||||
const index = cards().findIndex(c => c.indicador.id === id);
|
||||
toggle(index); flushAll();
|
||||
const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(c.canApply).toBe(false); http.expectNone(() => true);
|
||||
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
|
||||
expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos');
|
||||
const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save');
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.componentInstance.panelOpen).toBe(true);
|
||||
select.componentInstance.close(); fixture.detectChanges(); await fixture.whenStable();
|
||||
}
|
||||
expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
|
||||
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
|
||||
expect(writes).not.toHaveBeenCalled(); expect(saves).not.toHaveBeenCalled();
|
||||
expect(panels()[0].result()).toBe(state); http.expectNone(() => true);
|
||||
});
|
||||
it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => {
|
||||
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson');
|
||||
page.selectIndicador('i2'); fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
expect(help).toContain('min/max'); expect(help).not.toContain('Wilson');
|
||||
figure().flush({ data: [], layout: {} });
|
||||
it('mantiene el aviso de investigación en el catálogo', () => {
|
||||
load(); expect(fixture.nativeElement.querySelector('.notice').textContent).toBe('Uso exclusivo de investigación. No usar para decisiones clínicas.');
|
||||
});
|
||||
it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => {
|
||||
load();
|
||||
const received: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
|
||||
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const original = JSON.stringify(received);
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
expect(JSON.stringify(received)).toBe(original);
|
||||
expect(page.result().figure).toEqual(received);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
expect(chart.figure).toBe(page.result().presentationFigure);
|
||||
expect(chart.figure).not.toBe(page.result().figure);
|
||||
expect(chart.figure?.data).toEqual(received.data);
|
||||
expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } });
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('muestra catálogo vacío y permite recargar', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
|
||||
page.retryCatalog();
|
||||
load();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
page.selectIndicador('i2');
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(page.figuraId).toBe('box');
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['median']).toEqual([2]);
|
||||
});
|
||||
it('soporta varias figuras, volver al indicador y selección sin figuras', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
page.selectFigura('f2');
|
||||
expect(figure().request.url).toContain('/i1/figuras/f2');
|
||||
// Cancel the previous request and verify its cancellation explicitly below.
|
||||
page.selectIndicador('empty');
|
||||
expect(page.figuraId).toBe('');
|
||||
expect(page.result().status).toBe('idle');
|
||||
page.selectIndicador('i1');
|
||||
expect(page.figuraId).toBe('f2');
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
expect(page.filters?.applied?.selection.mode).toBe('todos');
|
||||
page.applyFilters();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
page.applyFilters();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('cancela figuras al cambiar tema rápidamente', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
page.changeTema('oscuro');
|
||||
const dark = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(dark.request.params.get('tema')).toBe('oscuro');
|
||||
page.changeTema('claro');
|
||||
expect(dark.cancelled).toBe(true);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it.each([
|
||||
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
|
||||
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
|
||||
load();
|
||||
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().message).toContain(message);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('error privado');
|
||||
fixture.nativeElement.querySelector('app-indicador-figure-card button').click();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
expect(page.result().status).toBe('ready');
|
||||
});
|
||||
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
|
||||
load(); figure().error(new ProgressEvent('error'));
|
||||
expect(page.result().message).toContain('conectar');
|
||||
page.requestFigure();
|
||||
const pending = figure();
|
||||
fixture.destroy();
|
||||
expect(pending.cancelled).toBe(true);
|
||||
});
|
||||
it('controla errores de catálogo y puede recuperarse', () => {
|
||||
http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' });
|
||||
expect(page.catalogError()).toContain('error interno');
|
||||
page.retryCatalog(); load(); figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
page.applyFilters();
|
||||
const req = figure();
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
req.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
const retry = figure();
|
||||
expect(retry.request.params.get('periodos')).toBe(periodos.join(','));
|
||||
retry.flush({ data: [{ y: [null] }], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
page.changeTema('oscuro');
|
||||
const themed = figure();
|
||||
expect(themed.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themed.request.params.get('tema')).toBe('oscuro');
|
||||
themed.flush('error', { status: 500, statusText: 'Server Error' });
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
page.applyFilters(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
});
|
||||
it('restaura borrador pendiente y consulta la aplicación al regresar a indicador y figura', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
let control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); figure().flush({ data: [], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
page.selectFigura('f2'); figure().flush({ data: [], layout: {} });
|
||||
page.selectFigura('f1');
|
||||
const restored = figure(); expect(restored.request.params.get('periodos')).toBe('2025-S1');
|
||||
restored.flush({ data: [], layout: {} });
|
||||
control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
page.selectIndicador('i2'); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador('i1');
|
||||
const returned = figure(); expect(returned.request.params.get('periodos')).toBe('2025-S1');
|
||||
returned.flush({ data: [], layout: {} });
|
||||
control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(control.hasPending).toBe(true);
|
||||
});
|
||||
it('restaura dominio, indicador, figura y tema sin aplicar el borrador mensual pendiente', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
page.changeDominio('cacu');
|
||||
http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const id = page.indicadorId; const fig = page.figuraId;
|
||||
page.changeTema('oscuro'); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
let control = filters(); control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add();
|
||||
page.changeDominio('cama');
|
||||
http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
page.changeDominio('cacu');
|
||||
http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu);
|
||||
const restored = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(restored.request.params.has('periodos')).toBe(false);
|
||||
expect(restored.request.params.get('tema')).toBe('oscuro');
|
||||
restored.flush({ data: [], layout: {} });
|
||||
expect(page.indicadorId).toBe(id); expect(page.figuraId).toBe(fig);
|
||||
control = filters(); expect(control.state.tipo).toBe('mes');
|
||||
expect(control.selectedPeriods).toEqual(['2025-01']);
|
||||
expect(control.state.applied?.tipo).toBe('semestre');
|
||||
});
|
||||
it('conserva memoria al destruir y recrear la página dentro de la aplicación', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador('i2'); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S2'; control.add();
|
||||
fixture.destroy();
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
load();
|
||||
const restored = figure();
|
||||
expect(restored.request.url).toContain('/i2/figuras/box');
|
||||
expect(restored.request.params.has('periodos')).toBe(false);
|
||||
restored.flush({ data: [], layout: {} });
|
||||
expect(filters().selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(filters().hasPending).toBe(true);
|
||||
it('IDs distintos con el mismo título y figura conservan paneles y etiquetas independientes', () => {
|
||||
load([{ ...item, figuras: ['f1'] }, { ...second, titulo: item.titulo, figuras: ['f1'] }]);
|
||||
toggle(0); toggle(1);
|
||||
const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1'));
|
||||
const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1'));
|
||||
a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges();
|
||||
const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf<HTMLButtonElement>;
|
||||
expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label'));
|
||||
expect(buttons[0].tabIndex).toBe(0); expect(buttons[1].tabIndex).toBe(0);
|
||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { ChangeDetectorRef, Component, DestroyRef, inject, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
@@ -8,29 +7,22 @@ import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, FigureSelection, Indicador, Tema } from './indicadores.models';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { presentationFigure } from './indicadores.presentation';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { FilterState, IndicadoresMemory, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { indicatorIdentity } from './indicadores-identities';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
|
||||
export function httpMessage(error: unknown, catalog = false): string {
|
||||
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
|
||||
if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.';
|
||||
if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.';
|
||||
if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.';
|
||||
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
|
||||
return 'No se pudo completar la solicitud. Intenta nuevamente.';
|
||||
}
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard, IndicadorPeriodFilters],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@@ -39,107 +31,38 @@ export class IndicadoresPage {
|
||||
dominio: Dominio = 'tea';
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
private readonly figureRequests = new Subject<FigureSelection | null>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
indicadorId = '';
|
||||
figuraId = '';
|
||||
tema: Tema = 'claro';
|
||||
filters?: FilterState;
|
||||
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
|
||||
|
||||
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
||||
constructor() {
|
||||
const initialDomain: unknown = this.route?.snapshot.data['dominio'];
|
||||
if (isDominio(initialDomain)) this.dominio = initialDomain;
|
||||
this.figureRequests.pipe(switchMap(selection => selection
|
||||
? defer(() => this.service.figura(selection)).pipe(
|
||||
map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState),
|
||||
catchError(error => of({
|
||||
status: 'error',
|
||||
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
|
||||
&& (selection.periodos?.length ?? 0) > 1
|
||||
? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''),
|
||||
} as FigureState)),
|
||||
startWith({ status: 'loading' } as FigureState))
|
||||
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(state => this.result.set(state));
|
||||
this.tema = this.memory.theme(this.dominio);
|
||||
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
|
||||
this.catalogLoading.set(true);
|
||||
this.catalogError.set('');
|
||||
this.catalog.set([]);
|
||||
this.indicadorId = this.figuraId = '';
|
||||
this.filters = undefined;
|
||||
this.figureRequests.next(null);
|
||||
return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })),
|
||||
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
|
||||
this.catalogLoading.set(false);
|
||||
this.catalog.set(items);
|
||||
this.catalogError.set(error);
|
||||
const navigation = this.memory.navigation(this.dominio);
|
||||
this.tema = navigation?.tema ?? 'claro';
|
||||
if (items.length) this.selectIndicador(items.some(i => i.id === navigation?.indicador) ? navigation!.indicador : items[0].id);
|
||||
});
|
||||
}
|
||||
filtersEdited() {
|
||||
if (!this.filters || !this.selected) return;
|
||||
this.memory.save(this.dominio, this.indicadorId, this.figuraId, this.filters);
|
||||
this.memory.remember(this.dominio, this.indicadorId, this.figuraId, this.tema);
|
||||
}
|
||||
changeDominio(dominio: Dominio) {
|
||||
if (!isDominio(dominio) || dominio === this.dominio) return;
|
||||
this.filtersEdited();
|
||||
this.dominio = dominio;
|
||||
this.tema = this.memory.theme(dominio);
|
||||
this.catalogRequests.next();
|
||||
}
|
||||
retryCatalog() { this.filtersEdited(); this.catalogRequests.next(); }
|
||||
selectIndicador(id: string) {
|
||||
if (!this.catalog().some(i => i.id === id)) return;
|
||||
this.filtersEdited();
|
||||
this.indicadorId = id;
|
||||
const remembered = this.memory.selectedFigure(this.dominio, id);
|
||||
this.figuraId = this.selected!.figuras.includes(remembered ?? '') ? remembered! : this.selected!.figuras[0] ?? '';
|
||||
this.restoreFilters();
|
||||
}
|
||||
selectFigura(id: string) {
|
||||
if (!this.selected?.figuras.includes(id)) return;
|
||||
this.filtersEdited();
|
||||
this.figuraId = id;
|
||||
this.restoreFilters();
|
||||
}
|
||||
private restoreFilters() {
|
||||
this.filters = this.memory.restore(this.dominio, this.selected!, this.figuraId);
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
applyFilters() {
|
||||
if (!this.filters || !this.selected) return;
|
||||
const draft = this.filters.editors[this.filters.tipo]!.draft;
|
||||
if (!validDraft(draft, this.filters.tipo, this.selected.tipos_periodo)) return;
|
||||
this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) };
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
retryCatalog() { this.catalogRequests.next(); }
|
||||
changeTema(tema: Tema) {
|
||||
if (tema !== 'claro' && tema !== 'oscuro') return;
|
||||
if ((tema !== 'claro' && tema !== 'oscuro') || tema === this.tema) return;
|
||||
this.tema = tema;
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
// Navigation, retry and theme all use the last application, never the pending editor.
|
||||
requestFigure() {
|
||||
const applied = this.filters?.applied;
|
||||
if (!this.selected?.figuras.includes(this.figuraId) || !applied
|
||||
|| !validDraft(applied.selection, applied.tipo, this.selected.tipos_periodo)) {
|
||||
this.figureRequests.next(null);
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({
|
||||
dominio: this.dominio, tipoPeriodo: applied.tipo, indicador: this.indicadorId,
|
||||
figura: this.figuraId, tema: this.tema,
|
||||
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
|
||||
});
|
||||
this.memory.rememberTheme(this.dominio, tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
||||
const disconnects: ReturnType<typeof vi.fn>[] = [];
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks(); disconnects.length = 0;
|
||||
runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
disconnect = vi.fn(); observe = vi.fn();
|
||||
constructor() { disconnects.push(this.disconnect); }
|
||||
});
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }]);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
|
||||
function respond() {
|
||||
http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: { annotations: [{ text: 'Nota' }] } }));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
it('dos gráficos poseen hosts y etiquetas independientes y purgan al contraer', async () => {
|
||||
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea · i · g');
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
card.toggle(); fixture.detectChanges();
|
||||
for (const host of hosts) expect(runtime.purge).toHaveBeenCalledWith(host);
|
||||
for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(0);
|
||||
});
|
||||
it('un error de renderizado y su reintento no afectan la otra instancia', async () => {
|
||||
runtime.react.mockRejectedValueOnce(new Error('render'));
|
||||
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(charts[0].componentInstance.status()).toBe('error'); expect(charts[1].componentInstance.status()).toBe('ready');
|
||||
const otherHost = charts[1].componentInstance.host.nativeElement;
|
||||
charts[0].componentInstance.retry(); await settle();
|
||||
expect(charts[0].componentInstance.status()).toBe('ready'); expect(charts[1].componentInstance.status()).toBe('ready');
|
||||
expect(runtime.react.mock.calls.filter(c => c[0] === otherHost)).toHaveLength(1); http.expectNone(() => true);
|
||||
});
|
||||
it('destruir la página desconecta y purga todas las instancias salientes', async () => {
|
||||
respond(); await settle(); fixture.destroy();
|
||||
expect(runtime.purge).toHaveBeenCalledTimes(2); expect(disconnects).toHaveLength(2);
|
||||
for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ export class IndicadoresService {
|
||||
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
|
||||
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
|
||||
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
|
||||
&& new Set(item['figuras']).size === item['figuras'].length
|
||||
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
|
||||
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
|
||||
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
|
||||
|
||||
@@ -14,7 +14,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
<div role="alert"><p>No se pudo representar la figura. Puedes reintentar.</p>
|
||||
<button mat-stroked-button (click)="retry()">Reintentar renderizado</button></div>
|
||||
}
|
||||
<div #host class="plot" role="img" aria-label="Figura del indicador seleccionado" [attr.aria-hidden]="status() !== 'ready'"></div>
|
||||
<div #host class="plot" role="img" [attr.aria-label]="label" [attr.aria-hidden]="status() !== 'ready'"></div>
|
||||
@if (status() === 'ready' && notes.length) {
|
||||
<section class="notes" aria-label="Notas completas de la figura">
|
||||
<h2>Notas de la figura</h2>
|
||||
@@ -25,6 +25,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
styles: `:host { display: block; min-width: 0; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { display: none; padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } @media (max-width: 850px) { .notes { display: block; } }`,
|
||||
})
|
||||
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
@Input() label = 'Figura estadística';
|
||||
@Input({ required: true }) figure!: PlotlyFigure;
|
||||
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
|
||||
readonly renderError = output<void>();
|
||||
|
||||
Reference in New Issue
Block a user