227 lines
17 KiB
TypeScript
227 lines
17 KiB
TypeScript
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 { By } from '@angular/platform-browser';
|
|
import { IndicadoresPage } from './indicadores-page';
|
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
|
import { IndicadorFigureCard } from './indicador-figure-card';
|
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
|
import { pending } from './indicadores-memory';
|
|
import { Indicador } from './indicadores.models';
|
|
|
|
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
|
class ChartStub {}
|
|
describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartida de %s', domain => {
|
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController, page: IndicadoresPage;
|
|
const periods = ['2026-S2', '2026-S1', '2025-S2'];
|
|
const definitions = KPI_BY_DOMAIN[domain];
|
|
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
|
|
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
|
|
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }];
|
|
beforeEach(() => {
|
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
|
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
|
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
|
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
|
http = TestBed.inject(HttpTestingController);
|
|
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
|
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
|
const inventory = http.match(r => r.url.endsWith('/periodos'));
|
|
expect(inventory).toHaveLength(4); // The anchor search shares the catalog inventory request.
|
|
inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
|
|
fixture.detectChanges();
|
|
});
|
|
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
|
function data(index: number, period: string, value = 7) {
|
|
const d = definitions[index];
|
|
return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: [period], categorias: { A: {} }, filas: [{
|
|
periodo: period, grupo: index === 1 && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0,
|
|
valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] };
|
|
}
|
|
function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); }
|
|
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); }
|
|
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
|
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
|
function flushPanels(period: string, expected = 2) {
|
|
const requests = http.match(r => r.url.endsWith('/datos'));
|
|
expect(requests).toHaveLength(expected);
|
|
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period);
|
|
const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); });
|
|
fixture.detectChanges();
|
|
}
|
|
function choose() {
|
|
request(periods[0]).flush(data(0, periods[0], 0)); request(periods[1]).flush(data(0, periods[1]));
|
|
fixture.detectChanges(); flushPanels(periods[1]);
|
|
}
|
|
function flushFigures(period: string, expected: number) {
|
|
const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(expected);
|
|
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); r.flush({ data: [], layout: {} }); }); fixture.detectChanges();
|
|
}
|
|
it('alternar secciones conserva búsqueda inicial en curso y aplica una sola autoridad temporal', () => {
|
|
const ongoing = request(periods[0]);
|
|
for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) {
|
|
page.changeSection(section); fixture.detectChanges();
|
|
for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
|
expect(page.initialPeriodState()).toBe('loading');
|
|
expect(ongoing.cancelled).toBe(false);
|
|
http.expectNone(() => true);
|
|
}
|
|
ongoing.flush(data(0, periods[0])); fixture.detectChanges(); flushPanels(periods[0]);
|
|
expect(page.activeSection()).toBe('datos');
|
|
const applied = page.filters!.applied;
|
|
page.changeSection('resumen'); fixture.detectChanges();
|
|
expect(page.filters!.applied).toBe(applied);
|
|
expect(panels().every(p => p.temporalReference === periods[0])).toBe(true);
|
|
http.expectNone(() => true);
|
|
});
|
|
it('pestañas conservan periodo inicial resuelto, borrador, fijación y representación sin solicitudes', () => {
|
|
choose(); const applied = page.filters!.applied, state = page.filters;
|
|
const before = cards(); page.togglePinned(items[1] as Indicador); fixture.detectChanges();
|
|
const card = before[0]; card.selectFigure('g'); fixture.detectChanges();
|
|
editor().select([periods[2]]); fixture.detectChanges();
|
|
for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
|
|
page.changeSection(section); fixture.detectChanges();
|
|
for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
|
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
|
|
expect(editor().selectedPeriods).toEqual([periods[2]]);
|
|
expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g');
|
|
expect(page.isPinned(items[1] as Indicador)).toBe(true);
|
|
expect(page.initialPeriodState()).toBe('ready'); http.expectNone(() => true);
|
|
}
|
|
});
|
|
it('espera sin KPI/figuras de Todos y sincroniza los tres KPI, borrador y aplicado', () => {
|
|
expect(page.initialPeriodBlocked).toBe(true); expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
|
|
http.expectNone(r => r.url.includes('/figuras/')); choose();
|
|
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[1]] });
|
|
expect(page.filters!.editors.semestre!.draft).toEqual(page.filters!.applied.selection);
|
|
expect(pending(page.filters!)).toBe(false); expect(editor().selectedPeriods).toEqual([periods[1]]);
|
|
expect(panels()).toHaveLength(3);
|
|
expect(panels().every(p => p.applied === page.filters!.applied && !p.initialPresentation && p.temporalReference === periods[1])).toBe(true);
|
|
expect(panels()[0].result().value).toBe(7); http.expectNone(() => true);
|
|
});
|
|
it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => {
|
|
choose(); http.expectNone(r => r.url.includes('/figuras/'));
|
|
cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); });
|
|
// EU7 now owns a coordinated C2 view. This temporal fixture publishes only
|
|
// placeholder f/g figures, so that card must stop as incompatible, without GET.
|
|
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true);
|
|
});
|
|
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
|
|
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
|
|
const requests = http.match(r => r.url.endsWith('/datos')); expect(requests).toHaveLength(2);
|
|
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
|
|
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
|
|
});
|
|
it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => {
|
|
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
|
|
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
|
|
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
|
|
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
|
|
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
|
|
});
|
|
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
|
|
choose(); const applied = page.filters!.applied;
|
|
page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true);
|
|
const card = cards().find(card => !card.isEu7)!;
|
|
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
|
|
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
|
|
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
|
|
expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready');
|
|
});
|
|
it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => {
|
|
choose(); editor().select([periods[2]]); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
|
|
page.changeDominio(otherDomain); http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges();
|
|
page.changeDominio('tea'); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
|
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
|
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
|
|
expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true);
|
|
});
|
|
it('cambio de dominio durante búsqueda cancela y no aplica respuestas viejas', () => {
|
|
const old = request(periods[0]); page.changeDominio(otherDomain); fixture.detectChanges(); expect(old.cancelled).toBe(true);
|
|
http.expectOne('/' + otherDomain + '/indicadores').flush([]); fixture.detectChanges(); expect(page.filters).toBeUndefined(); http.expectNone(() => true);
|
|
});
|
|
it('Aplicar Todos durante búsqueda cancela y respeta la decisión manual', () => {
|
|
const old = request(periods[0]); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false);
|
|
page.applyFilters(); fixture.detectChanges(); expect(old.cancelled).toBe(true); flushPanels(periods[0], 3);
|
|
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true);
|
|
});
|
|
it('error HTTP queda visible, sin datos mezclados, con reintento funcional', () => {
|
|
request(periods[0]).flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
|
expect(page.initialPeriodState()).toBe('error'); expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0);
|
|
expect(fixture.nativeElement.textContent).not.toContain('private'); page.retryInitialPeriod();
|
|
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges(); flushPanels(periods[0]);
|
|
expect(page.initialPeriodState()).toBe('ready'); http.expectNone(() => true);
|
|
});
|
|
it('sin positivo comunica ausencia y espera selección manual sin aplicar un periodo incorrecto', () => {
|
|
periods.forEach(p => request(p).flush(data(0, p, 0))); fixture.detectChanges();
|
|
expect(page.initialPeriodState()).toBe('empty'); expect(page.filters!.applied.selection.mode).toBe('todos');
|
|
expect(fixture.nativeElement.textContent).toContain('No se encontró un periodo');
|
|
expect(page.initialPeriodBlocked).toBe(true); expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0);
|
|
http.expectNone(() => true);
|
|
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
|
|
expect(panels()[0].result().value).toBe(0); expect(panels().every(p => !p.initialPresentation)).toBe(true);
|
|
expect(page.initialPeriodBlocked).toBe(false); http.expectNone(() => true);
|
|
});
|
|
it('editar interrumpe la búsqueda sin consultar ni sobrescribir el borrador antes de Aplicar', () => {
|
|
const old = request(periods[0]); editor().select([periods[2]]); fixture.detectChanges();
|
|
expect(old.cancelled).toBe(true); expect(page.initialPeriodState()).toBe('manual');
|
|
expect(page.filters!.applied.selection.mode).toBe('todos');
|
|
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
|
page.retryCatalog(); http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
|
expect(editor().selectedPeriods).toEqual([periods[2]]); expect(page.initialPeriodState()).toBe('manual'); http.expectNone(() => true);
|
|
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], 3);
|
|
expect(panels().every(p => p.temporalReference === periods[2])).toBe(true); http.expectNone(() => true);
|
|
});
|
|
it('un ancla retirada del catálogo requiere selección manual y no consulta datos retirados', () => {
|
|
const old = request(periods[0]); page.retryCatalog(); expect(old.cancelled).toBe(true);
|
|
http.expectOne('/' + domain + '/indicadores').flush(items.filter(item => item.id !== definitions[0].id)); fixture.detectChanges();
|
|
expect(page.initialPeriodState()).toBe('unavailable');
|
|
expect(page.kpiIndicator(definitions[0].id)).toBeUndefined();
|
|
expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
|
|
editor().select([periods[0]]); page.applyFilters(); fixture.detectChanges();
|
|
http.match(r => r.url.endsWith('/datos')).forEach(r => {
|
|
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos'));
|
|
expect(index).toBeGreaterThan(0); r.flush(data(index, periods[0]));
|
|
}); fixture.detectChanges();
|
|
expect(panels()).toHaveLength(2); expect(panels().every(p => p.temporalReference === periods[0])).toBe(true); http.expectNone(() => true);
|
|
});
|
|
it('inicializa y restaura los tres dominios con periodos propios sin repetir datos resueltos', () => {
|
|
choose();
|
|
const own = new Map<string, string>([[domain, periods[1]]]);
|
|
const catalogs = new Map<string, typeof items>([[domain, items]]);
|
|
for (const target of ['tea', 'cacu', 'cama'] as const) {
|
|
if (target === domain) continue;
|
|
const definitions = KPI_BY_DOMAIN[target];
|
|
const period = own.size === 1 ? '2024-S2' : '2025-S1';
|
|
own.set(target, period);
|
|
const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] }));
|
|
catalogs.set(target, catalog);
|
|
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges();
|
|
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] }));
|
|
const payload = (index: number) => {
|
|
const value = data(index, period); value.id = definitions[index].id;
|
|
value.filas[0].grupo = index === 1 && target !== 'tea' ? 'total' : 'TOTAL'; return value;
|
|
};
|
|
http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges();
|
|
http.match(r => r.url.endsWith('/datos')).forEach(r => {
|
|
const index = definitions.findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); r.flush(payload(index));
|
|
}); fixture.detectChanges();
|
|
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [period] });
|
|
}
|
|
for (const target of ['tea', 'cacu', 'cama'] as const) {
|
|
if (page.dominio !== target) {
|
|
page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalogs.get(target)!); fixture.detectChanges();
|
|
}
|
|
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [own.get(target)] });
|
|
expect(panels().every(p => p.temporalReference === own.get(target))).toBe(true);
|
|
http.expectNone(() => true);
|
|
}
|
|
});
|
|
});
|