import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { vi } from 'vitest'; import { donutPeriodFigures } from './indicadores-donut-periods'; import { Dominio, FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { c2Fixture } from './indicadores-c2-adapter.testing'; import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile'; const periods = ['2025-S2', '2025-S1', '2026-S1']; const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_donas', tipoPeriodo: 'semestre', tema: 'claro', periodos: periods }; function multiData(): IndicadorDatos { const data = c2Fixture(); return { ...data, periodos: [...periods], filas: periods.flatMap((periodo, i) => data.filas.map(r => ({ ...r, periodo, n: Number(r['n']) + i }))) }; } function multiFigure(): PlotlyFigure { return { data: periods.map((p, i) => ({ type: 'pie', name: p, hole: .62, labels: ['A', 'B', 'C'], values: [6 + i, 3 + i, 1 + i], domain: { x: [i / 3, (i + 1) / 3], y: [0, 1] }, customdata: [[p], [p], [p]], text: ['60%', '30%', '10%'], marker: { colors: ['red','blue','green'] } })), layout: { title: { text: 'Título publicado' }, annotations: [ ...periods.map((p, i) => ({ text: p + '
N publicado', x: (i + .5) / 3, y: .5, xref: 'paper', yref: 'paper', showarrow: false })), { text: 'Nota metodológica íntegra', x: 0, y: -.22, xref: 'paper', yref: 'paper', showarrow: false }, { text: 'Anotación desconocida', x: .1, y: .8 }, ] }, config: { responsive: true }, extra: { retained: true } }; } describe('selección de trazas por periodo de dona', () => { it('selecciona trazas, conserva arrays completos y normaliza dominio y anotación sin mutar HTTP', () => { const original = multiFigure(), before = JSON.stringify(original); const pages = donutPeriodFigures(original, selection)!; expect(pages.map(p => p.period)).toEqual(periods); pages.forEach(({ figure }, i) => { expect(figure.data).toHaveLength(1); expect(figure.data[0]).toEqual({ ...original.data[i], domain: { x: [0,1], y: [0,1] } }); expect(figure.layout['annotations']).toEqual([ expect.objectContaining({ text: periods[i] + '
N publicado', x: expect.closeTo(.5) }), ...(original.layout['annotations'] as unknown[]).slice(3), ]); expect(figure.config).toEqual(original.config); expect(figure['extra']).toEqual(original['extra']); }); expect(JSON.stringify(original)).toBe(before); }); it('no agrega trazas de un periodo sin datos ni convierte cero, null o supresión', () => { const original = multiFigure(); original.data.splice(1, 1); original.data[0]['values'] = [0, null, 10]; original.data[0]['customdata'] = [{ suprimido: true }]; const pages = donutPeriodFigures(original, selection)!; expect(pages[0].figure.data[0]['values']).toEqual([0, null, 10]); expect(pages[0].figure.data[0]['customdata']).toEqual([{ suprimido: true }]); expect(pages[1].figure.data).toEqual([]); expect(pages[1].figure.layout['xaxis']).toMatchObject({ visible: false }); expect(pages[0].figure.layout['annotations']).not.toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '
N publicado' })])); expect(pages[1].figure.layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: periods[1] + '
N publicado', x: .5 })])); }); it('mantiene ambos anillos de un único periodo y sus proporciones geométricas', () => { const source = multiFigure(); source.data.push({ ...source.data[0], name: periods[0] + ', grupos', domain: { x: [.06333333333333333, .27], y: [.19,.81] } }); const first = donutPeriodFigures(source, selection)![0].figure; expect(first.data.map(t => t['name'])).toEqual([periods[0], periods[0] + ', grupos']); expect((first.data[1]['domain'] as { x: number[] }).x[0]).toBeCloseTo(.19); expect((first.data[1]['domain'] as { x: number[] }).x[1]).toBeCloseTo(.81); }); it('todos sigue el orden explícito de reportes o el recibido, sin ordenar por índice', () => { const all = { ...selection, periodos: undefined }; expect(donutPeriodFigures(multiFigure(), all)!.map(p => p.period)).toEqual(periods); expect(donutPeriodFigures(multiFigure(), all, [...periods].reverse())!.map(p => p.period)).toEqual([...periods].reverse()); }); it('cero periodos y un solo periodo conservan el comportamiento anterior', () => { expect(donutPeriodFigures({ data: [], layout: {} }, { ...selection, periodos: [] })).toBeUndefined(); const one = multiFigure(); one.data = [one.data[0]]; expect(donutPeriodFigures(one, { ...selection, periodos: [periods[0]] })).toBeUndefined(); expect(donutPeriodFigures({ data: [], layout: {} }, { ...selection, figura: 'fig_c2_barras' })).toBeUndefined(); }); it.each(['bar', 'animation', 'unidentified', 'solid-pie'])('no aplica a otra familia o navegación propia: %s', kind => { const source = multiFigure(); if (kind === 'bar') source.data[0]['type'] = 'bar'; if (kind === 'animation') source.frames = [{ data: [] }]; if (kind === 'unidentified') source.data[0]['name'] = 'No identificado'; if (kind === 'solid-pie') source.data[0]['hole'] = 0; expect(donutPeriodFigures(source, selection)).toBeUndefined(); }); it('admite otra representación publicada con la misma estructura de dona', () => { expect(donutPeriodFigures(multiFigure(), { ...selection, figura: 'future_donut' })).toHaveLength(3); }); }); @Component({ selector: 'app-plotly-chart', inputs: ['figure','label','showNotes'], template: '' }) class ChartStub { figure?: PlotlyFigure; } describe('navegación multiperiodo en el panel común', () => { let fixture: ReturnType>, http: HttpTestingController; const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] }; function apply(selected = periods, revision = 1) { fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [...selected] }, revision }); fixture.detectChanges(); } beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController); for (const [name, value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro' })) fixture.componentRef.setInput(name, value); }); afterEach(() => { fixture.destroy(); http.verify(); }); const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos')); const panel = () => fixture.componentInstance; const card = () => fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; const buttons = () => fixture.nativeElement.querySelectorAll('.donut-periods button') as NodeListOf; function load(data = multiData()) { apply(); dataRequest().flush(data); fixture.detectChanges(); } it.each(['tea', 'cacu', 'cama'] as Dominio[])('%s: datos completos, navegación acotada sin HTTP ni cambio del filtro', domain => { fixture.componentRef.setInput('dominio', domain); load(); const applied = structuredClone(panel().applied); const host = fixture.nativeElement.querySelector('app-plotly-chart'); expect(buttons()[0].disabled).toBe(true); expect(buttons()[1].disabled).toBe(false); for (let i = 0; i < periods.length; i++) { expect(panel().activeDonutPeriod).toBe(periods[i]); expect(fixture.nativeElement.querySelector('.donut-periods [role="status"]').textContent).toContain(`${i + 1} de 3`); expect(card().chartFigure?.data).toHaveLength(1); expect(panel().result().figure?.data.every(t => String(t['name']).startsWith(periods[i]))).toBe(true); if (i < 2) { buttons()[1].click(); fixture.detectChanges(); } } expect(buttons()[1].disabled).toBe(true); panel().changeDonutPeriod(1); expect(panel().activeDonutPeriod).toBe(periods[2]); buttons()[0].click(); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[1]); expect(panel().applied).toEqual(applied); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true); }); it('dos periodos, controles nativos accesibles y sin interceptar Enter/Espacio', () => { apply(periods.slice(0,2)); dataRequest().flush({ ...multiData(), periodos: periods.slice(0,2), filas: multiData().filas.filter(r => r['periodo'] !== periods[2]) }); fixture.detectChanges(); expect(buttons()[1].tagName).toBe('BUTTON'); expect(buttons()[1].type).toBe('button'); expect(buttons()[1].getAttribute('aria-label')).toBe('Periodo siguiente de la dona'); for (const key of ['Enter', ' ']) { const e = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); buttons()[1].dispatchEvent(e); expect(e.defaultPrevented).toBe(false); } buttons()[1].click(); fixture.detectChanges(); expect(buttons()[1].disabled).toBe(true); }); it('retiene periodo activo seleccionado y elige primero si se elimina; no comparte índice con otra figura', () => { load(); panel().changeDonutPeriod(1); fixture.detectChanges(); apply([periods[1], periods[2]], 2); dataRequest().flush({ ...multiData(), periodos: periods.slice(1), filas: multiData().filas.filter(r => r['periodo'] !== periods[0]) }); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[1]); const subset = { ...multiData(), periodos: [periods[0], periods[2]], filas: multiData().filas.filter(r => r['periodo'] !== periods[1]) }; apply([periods[0], periods[2]], 3); dataRequest().flush(subset); fixture.detectChanges(); expect(panel().result().status).toBe('ready'); expect(panel().activeDonutPeriod).toBe(periods[0]); panel().changeDonutPeriod(1); fixture.detectChanges(); fixture.componentRef.setInput('indicador', { ...item, id: 'otro' }); fixture.detectChanges(); dataRequest().flush({ ...subset, id: 'otro' }); fixture.detectChanges(); expect(panel().activeDonutPeriod).toBe(periods[0]); }); it('navegación limpia selección dependiente; cada nueva categoría declara el periodo', () => { load(); const selected = vi.fn(); panel().hierarchySelected.subscribe(selected); card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges(); expect(selected).toHaveBeenLastCalledWith({ parent: 'G2', category: 'B', period: periods[0] }); panel().changeDonutPeriod(1); fixture.detectChanges(); expect(selected).toHaveBeenLastCalledWith({}); expect(card().activeParent).toBeUndefined(); expect(card().activeCategory).toBeUndefined(); card().expandParent('G2'); expect(selected).toHaveBeenLastCalledWith({ parent: 'G2', period: periods[1] }); http.expectNone(() => true); }); it('perfil y ancho se aplican también al navegar a páginas ya cargadas', () => { load(); fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); panel().updatePlotWidth(320); panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().plotWidth).toBe(320); expect(panel().result().footnotes).toEqual(multiData().notas); http.expectNone(() => true); }); it('periodo vacío y cero conservan su identidad, notas y posibilidad de navegar', () => { const data = multiData(); data.filas = data.filas.filter(r => r['periodo'] !== periods[1]); data.filas.filter(r => r['periodo'] === periods[2]).forEach(r => r['n'] = 0); load(data); panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().figure?.data).toEqual([]); expect(fixture.nativeElement.textContent).toContain('No hay filas publicadas'); expect(card().chartFigure?.layout['height']).toBe(440); expect(fixture.nativeElement.querySelector('app-plotly-chart').style.getPropertyValue('--plot-height')).toBe('440px'); panel().changeDonutPeriod(1); fixture.detectChanges(); expect(panel().result().emptyMessage).toContain('conteos publicados son cero'); expect(fixture.nativeElement.textContent).toContain('2026-S1'); http.expectNone(() => true); }); it.each(['null', 'suppressed', 'simple'])('/figuras %s separa las trazas sin peticiones por clic', kind => { const data = multiData(); if (kind === 'null') data.filas[0]['n'] = null; else if (kind === 'suppressed') { data.filas[0]['n'] = null; data.filas[0]['suprimido'] = 1; } else delete data['unidad']; apply(); dataRequest().flush(data); const source = multiFigure(); if (kind !== 'simple') source.data[0]['values'] = [null, 3, 1]; const before = JSON.stringify(source); http.expectOne(r => r.url.includes('/figuras/')).flush(source); fixture.detectChanges(); expect(panel().result().source).toBe('figuras'); expect(card().chartFigure?.data).toHaveLength(1); if (kind !== 'simple') expect(card().chartFigure?.data[0]['values']).toEqual([null,3,1]); panel().changeDonutPeriod(1); fixture.detectChanges(); expect(card().chartFigure?.data[0]['name']).toBe(periods[1]); expect(JSON.stringify(source)).toBe(before); http.expectNone(() => true); }); it('un periodo no presenta navegación y una selección vacía es incompatible sin HTTP', () => { // TEA draws single-period C2 donuts with highlight buttons instead (indicadores-tea-c2.ts). fixture.componentRef.setInput('dominio', 'cama'); apply([periods[0]]); dataRequest().flush(c2Fixture()); fixture.detectChanges(); expect(buttons()).toHaveLength(0); expect(card().state.hierarchy).toBeTruthy(); apply([], 2); fixture.detectChanges(); expect(panel().result().status).toBe('incompatible'); expect(buttons()).toHaveLength(0); http.expectNone(() => true); }); });