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 { CACU_RESULTADO_KPI, 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>, 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'] })), // Two figures, so every domain keeps an ordinary card whose representation can change. { id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f', 'g'] }]; 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(); // The anchor shares the catalog inventory request; availability runs four at a time. expect(flushPeriodos(() => [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })))).toBe(items.length); 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: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0, valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] }; } function flushPeriodos(periodos: () => unknown[]) { let flushed = 0; for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos'))) { pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() })); flushed += pending.length; } return flushed; } function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); } // Regression assertions below target the original KPI contracts. The added lab // consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts. // Satisfy its independent request with an explicit empty response, never diagnosis data. function originalRequests() { const requests = http.match(r => r.url.endsWith('/datos')); for (const r of requests.filter(r => r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'))) { const period = r.request.params.get('periodos')!; r.flush({ id: CACU_RESULTADO_KPI.id, contrato: 'C3r', tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [], filas: [] }); } return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos')); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } // The shared request queue runs four at a time: flushing a batch starts the next. function flushPanels(period: string, expected = definitions.length - 1) { let flushed = 0; for (let requests = originalRequests(); requests.length; requests = originalRequests()) { 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)); }); flushed += requests.length; } expect(flushed).toBe(expected); 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.endsWith('/seguimiento') || r.url.includes('/fhir/'))) 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.endsWith('/seguimiento') || r.url.includes('/fhir/'))) 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(definitions.length); 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 and the CaCu paired times own coordinated views. This temporal fixture publishes // only placeholder f/g figures, so EU7 stops as incompatible without GET; the paired times // ask /datos for the same shared period, including the partner hidden from the catalog. fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length); const tiempos = http.match(r => r.url.endsWith('/datos')); // P0-C.1 cached the same lab payload; the paired figure reuses it. expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(false); for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); } 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 = originalRequests(); expect(requests).toHaveLength(definitions.length - 1); 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 prevalece sin repetir la búsqueda', () => { choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] }); 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.tiempos)!; 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], definitions.length); 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], definitions.length); 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], definitions.length); 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(); originalRequests().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(definitions.length - 1); 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([[domain, periods[1]]]); const catalogs = new Map([[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(); flushPeriodos(() => [{ periodo: period, tipo: 'semestre' }]); const payload = (index: number) => { const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato; value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value; }; http.expectOne(r => r.url.endsWith('/' + definitions[0].id + '/datos')).flush(payload(0)); fixture.detectChanges(); originalRequests().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); } }); });