feat(ui): mejorar periodos KPI y presentacion del dashboard

This commit is contained in:
Angel Capetillo Zavala
2026-10-14 11:46:17 -06:00
parent 9fcc65d84f
commit 69afcc7fdb
26 changed files with 778 additions and 604 deletions
@@ -1,3 +1,4 @@
import { periodAvailabilityProvider } from './indicadores-periodos.testing';
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
@@ -20,23 +21,24 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
class ChartStub { figure?: PlotlyFigure; }
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', () => {
describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { fixture.destroy(); http.verify(); });
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
function load(items: Indicador[] = [item, second], domain = 'tea') {
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
}
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 panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
function toggle(index = 0) { cards()[index].setVisible(true); 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; }
@@ -83,48 +85,23 @@ describe('UX-05B catálogo expandible', () => {
toggle(0); toggle(1); flushAll();
expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]);
expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']);
expect(cards()).toEqual(before); expect(cards().every(card => card.expanded)).toBe(true);
expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true);
http.expectNone(() => true);
});
it('UX-06C: tarjeta contraída contiene solo identidad y flecha decorativa en un botón nativo', () => {
load();
const host = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement;
const header = host.querySelector('header')!;
expect(header.querySelector('h2')?.textContent).toBe('Uno');
expect(header.querySelector('.indicator-id')?.textContent).toBe('i1');
expect(host.textContent).not.toContain('Contrato');
expect(host.textContent).not.toContain('figuras publicadas');
expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0);
const button = header.querySelector('button')!;
expect(button.type).toBe('button');
expect(button.tabIndex).toBe(0);
expect(button.getAttribute('aria-expanded')).toBe('false');
expect(button.getAttribute('aria-label')).toContain('Expandir tea · i1 · Uno');
expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_more');
expect(button.querySelector('mat-icon')?.getAttribute('aria-hidden')).toBe('true');
http.expectNone(() => true);
it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => {
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
expect(host.querySelector('h2').textContent).toBe('Uno');
expect(host.querySelector('header button')).toBeNull();
expect(host.querySelector('mat-select')).toBeTruthy();
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
expect(host.textContent).toContain('Contrato C1'); http.expectNone(() => true);
});
it('UX-06C: conserva encabezado, botón y relación accesible al abrir varias figuras y contraer', () => {
load();
const host = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement;
const header = host.querySelector('header')!;
const button = header.querySelector('button')!;
const contentId = button.getAttribute('aria-controls')!;
button.click(); fixture.detectChanges(); flushAll();
expect(host.querySelector('header')).toBe(header);
expect(header.querySelector('button')).toBe(button);
expect(button.getAttribute('aria-controls')).toBe(contentId);
expect(button.getAttribute('aria-expanded')).toBe('true');
expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_less');
expect(button.getAttribute('aria-label')).toContain('Contraer tea · i1 · Uno');
expect(header.textContent).not.toContain('Contrato');
expect(host.querySelector('.catalog-metadata')?.textContent).toContain('Contrato C1 · 2 figuras publicadas');
expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(1);
button.click(); fixture.detectChanges();
expect(host.querySelector('.catalog-metadata')).toBeNull();
expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0);
expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_more');
http.expectNone(() => true);
it('D.3.A conserva encabezado y contenido al salir del viewport', () => {
load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card');
const header = host.querySelector('header'); toggle(); flushAll();
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel);
expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true);
});
it('UX-06C: conserva título largo completo y el control separado de la identidad', () => {
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
@@ -132,8 +109,8 @@ describe('UX-05B catálogo expandible', () => {
const header = fixture.nativeElement.querySelector('app-indicador-catalog-card header') as HTMLElement;
expect(header.querySelector('h2')?.textContent).toBe(title);
expect(header.querySelector('.card-identity button')).toBeNull();
expect(header.lastElementChild?.tagName).toBe('BUTTON');
expect(header.querySelector('button')?.getAttribute('aria-label')).toContain(title);
expect(header.querySelector('button')).toBeNull();
expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title);
http.expectNone(() => true);
});
it('UX-06B conserva una navegación con rutas y estado activo en los tres dominios', () => {
@@ -162,29 +139,29 @@ describe('UX-05B catálogo expandible', () => {
expect(page.tema).toBe('claro');
page.changeTema('oscuro'); fixture.detectChanges();
expect(page.tema).toBe('oscuro');
expect(cards().every(card => !card.expanded)).toBe(true);
expect(cards().every(card => !card.visible)).toBe(true);
http.expectNone(() => true);
});
it.each([0, 1, 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(cards().every(c => !c.visible)).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('abrir manualmente consulta exactamente una vez la primera figura publicada', () => {
load([item]); toggle(); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(1);
it('activar visibilidad consulta exactamente una vez la primera figura publicada', () => {
load([item]); toggle(); expect(cards()[0].visible).toBe(true); expect(panels()).toHaveLength(1);
request('f1').flush({ data: [], layout: {} });
fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true);
});
it('el cierre manual se conserva al volver sin consultar figuras', () => {
load([item]); toggle(); flushAll(); toggle();
fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
load([item]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true);
it('volver al dominio espera nueva visibilidad sin memoria de cierre', () => {
load([item]); toggle(); flushAll();
fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
load([item]); expect(cards()[0].visible).toBe(false); http.expectNone(() => true);
});
it('indicador sin figuras informa y no consulta HTTP', () => {
load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].expanded).toBe(true);
load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].visible).toBe(true);
expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles');
expect(panels()).toHaveLength(0); http.expectNone(() => true);
});
@@ -194,11 +171,12 @@ describe('UX-05B catálogo expandible', () => {
c.flush({ data: [{ y: [3] }], layout: {} });
a.flush({ data: [{ y: [1] }], layout: {} });
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [3]]);
expect(cards().every(c => c.expanded)).toBe(true);
expect(cards().every(c => c.visible)).toBe(true);
});
it('contraer cancela solo sus figuras, descarta respuestas y destruye paneles', () => {
it('retirar una tarjeta cancela solo su solicitud y destruye su panel', () => {
load(); toggle(); toggle(1); const a = request('f1'), c = request('g');
toggle(); expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false);
page.catalog.set([second]); fixture.detectChanges();
expect(a.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]);
@@ -242,16 +220,14 @@ describe('UX-05B catálogo expandible', () => {
http.expectNone(() => true);
}
});
it('cerrar y reabrir conserva borrador general y consulta aplicado en la figura seleccionada', () => {
it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => {
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
page.applyFilters(); fixture.detectChanges(); flushAll(); a.unit = 'S2'; a.add();
toggle(); toggle();
const restored = request('f1');
expect(restored.request.params.get('periodos')).toBe('2025-S1');
cards()[0].setVisible(false); fixture.detectChanges(); toggle();
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']);
restored.flush({ data: [], layout: {} });
http.expectNone(() => true);
});
it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => {
it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => {
load(); toggle(); const a = request('f1');
page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true);
const darkA = request('f1');
@@ -267,17 +243,17 @@ describe('UX-05B catálogo expandible', () => {
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', () => {
it('restaura representació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'); toggle(); 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'); expect(cards()[0].awaitingFigures).toBe(true); http.expectNone(() => true);
expect(cards()[0].visible).toBe(false); expect(cards()[1].visible).toBe(false);
expect(page.tema).toBe('oscuro'); expect(cards()[0].visible).toBe(false); http.expectNone(() => true);
toggle(); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false);
expect(control().entry.draft.mode).toBe('empty'); a.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);
expect(cards()[0].visible).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];
@@ -285,22 +261,16 @@ describe('UX-05B catálogo expandible', () => {
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).rememberActivation('tea', 'removed', 'manual-open');
TestBed.inject(IndicadoresMemory).rememberFigure('tea', 'removed', 'f1');
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-catalog-card .methodology-toggle') as HTMLElement;
input.focus(); expect(document.activeElement).toBe(input); cards()[0].toggle(); fixture.detectChanges();
expect(document.activeElement).toBe(buttons[0]);
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
load(); toggle(); flushAll();
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle');
input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input);
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'));
expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull();
});
it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => {
load(); toggle(0); toggle(1); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } };
@@ -354,9 +324,9 @@ describe('UX-05B catálogo expandible', () => {
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);
const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf<HTMLElement>;
expect(panels()[0].titleId).not.toBe(panels()[1].titleId);
expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1);
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]);
});
});