import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter'; import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette'; import { c2Fixture } from './indicadores-c2-adapter.testing'; import { FigureSelection } from './indicadores.models'; import { donutFixture } from './indicadores-donut-drilldown.testing'; import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown'; import { figurePresentation } from './indicadores.presentation'; const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; function supported(data = c2Fixture(), s = selection) { const result = c2Figure(data, s); if (result.status !== 'supported') throw new Error(result.reason); return result; } describe('C2: datos publicados a Plotly', () => { it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => { const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure; expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']])); expect(result.model.total).toBe(10); expect(result.model.unit).toBe('paciente'); expect(result.hierarchy?.parents).toEqual(['G1', 'G2']); expect(result.model.notes).toEqual(data.notas); expect(data).toEqual(before); }); it('dona simple sin jerarquía y barras comparten categorías, conteos, unidades y orden', () => { const data = c2Fixture(); data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record>).forEach(c => c['grupo'] = null); const donut = supported(data), bars = supported(data, { ...selection, figura: 'fig_c2_barras' }); expect(donut.figure.data).toHaveLength(1); expect(donut.hierarchy).toBeUndefined(); expect(bars.figure.data[0]['x']).toEqual(donut.figure.data[0]['values']); expect(bars.figure.data[0]['y']).toEqual(donut.figure.data[0]['labels']); expect(bars.figure.layout['xaxis']).toMatchObject({ title: { text: 'Conteo (paciente)' } }); }); it('el layout final de barras muestra ambos ejes y el hover no repite el periodo', () => { const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' }); const final = figurePresentation(bars.figure, { ...selection, figura: 'fig_c2_barras' }).figure; expect(final.layout['xaxis']).toMatchObject({ showline: true, linewidth: 1, ticks: 'outside', automargin: true, zeroline: false }); expect(final.layout['yaxis']).toMatchObject({ showline: true, linewidth: 1, ticks: 'outside', automargin: true, ticklabelstandoff: 12 }); expect(final.layout['margin']).toMatchObject({ l: 76, r: 28, t: 112, b: 62 }); expect(final.data[0]['hovertemplate']).toContain(''); expect(final.data[0]['hovertemplate']).not.toContain('2025-S2'); }); it('la vista de dona simple comparte el lienzo centrado y la leyenda superior', () => { const data = c2Fixture(); data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record>).forEach(c => c['grupo'] = null); const result = supported(data); const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final); const legend = donutLegend(final), view = donutSimpleView(final); expect(legend).toEqual([ { label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] }, ]); expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } }); expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); expect(view.data[0]['showlegend']).toBe(false); expect(view.data[0]['labels']).toEqual(final.data[0]['labels']); expect(view.data[0]['values']).toEqual(final.data[0]['values']); expect(final).toEqual(before); }); it('homologa la dona jerárquica en los tres dominios con el mismo periodo único', () => { const snapshots = (['tea', 'cacu', 'cama'] as const).map(dominio => { const adapted = supported(c2Fixture(), { ...selection, dominio }); expect(adapted.model.period).toBe('2025-S2'); expect(adapted.hierarchy).toBeDefined(); return donutView(adapted.figure, adapted.hierarchy!); }); for (const view of snapshots.slice(1)) expect(view).toEqual(snapshots[0]); expect(snapshots[0].layout['showlegend']).toBe(false); expect(snapshots[0].layout['margin']).toMatchObject({ l: 16, r: 16, t: 16, b: 16, pad: 0 }); expect(snapshots[0].data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] }); }); it('ordena por orden publicado aunque las filas lleguen desordenadas; conserva ceros explícitos', () => { const data = c2Fixture(); data.filas[0]['n'] = 0; data.filas.reverse(); const result = supported(data); expect(result.figure.data[0]['labels']).toEqual(['A','B','C']); expect(result.figure.data[0]['values']).toEqual([0,3,1]); expect(result.figure.layout['meta']).toMatchObject({ denominator: 4 }); }); it.each(['null', 'suppressed', 'unknown-suppression', 'negative', 'nan', 'fraction', 'overflow', 'missing-category', 'duplicate', 'unknown-category', 'duplicate-order', 'wrong-period', 'stratum', 'overlapping-group', 'missing-unit', 'mixed-groups', 'bad-color', 'ambiguous-label', 'future-meta', 'denominator'])('usa respaldo sin reconstruir %s', kind => { const data = c2Fixture(), row = data.filas[0], catalog = data['categorias'] as Record>; if (kind === 'null') row['n'] = null; if (kind === 'suppressed') { row['suprimido'] = 1; row['n'] = 100; } if (kind === 'unknown-suppression') delete row['suprimido']; if (kind === 'negative') row['n'] = -1; if (kind === 'nan') row['n'] = NaN; if (kind === 'fraction') row['n'] = 1.5; if (kind === 'overflow') row['n'] = Number.MAX_SAFE_INTEGER; if (kind === 'missing-category') data.filas.pop(); if (kind === 'duplicate') data.filas.push({ ...row }); if (kind === 'unknown-category') row['categoria'] = 'outside'; if (kind === 'duplicate-order') data.filas[1]['orden'] = row['orden']; if (kind === 'wrong-period') row['periodo'] = '2024-S1'; if (kind === 'stratum') row['estrato'] = 'age'; if (kind === 'overlapping-group') row['grupo'] = 'other'; if (kind === 'missing-unit') delete data['unidad']; if (kind === 'mixed-groups') catalog['A']['grupo'] = null; if (kind === 'bad-color') catalog['A']['color'] = 'url(external)'; if (kind === 'ambiguous-label') catalog['A']['etiqueta'] = 'B'; if (kind === 'future-meta') data['meta'] = { future: true }; if (kind === 'denominator') row['denominador'] = 100; expect(c2Figure(data, selection).status).toBe('unsupported'); }); it('distingue ausencia de filas de una partición completa de ceros, sin inventar porcentajes', () => { const empty = c2Fixture(); empty.filas = []; expect(supported(empty).emptyMessage).toContain('No hay filas'); expect(supported(empty).figure.data).toEqual([]); const zeros = c2Fixture(); zeros.filas.forEach(r => r['n'] = 0); expect(supported(zeros).emptyMessage).toContain('son cero'); expect(supported(zeros).figure.data).toEqual([]); expect(supported(zeros, { ...selection, figura: 'fig_c2_barras' }).figure.data[0]['x']).toEqual([0,0,0]); }); it('no combina unidades discordantes entre filas y metadatos', () => { const data = c2Fixture(); data.filas[0]['unidad'] = 'examen'; expect(c2Figure(data, selection).status).toBe('unsupported'); }); it('porcentajes sólo sobre suma completa verificable, incluye categorías sin dato', () => { const data = c2Fixture(); data.filas.forEach(r => r['denominador'] = 10); data['denominador'] = 10; const result = supported(data); expect(result.figure.layout['meta']).toMatchObject({ denominator: 10 }); expect(result.figure.data[0]['hovertemplate']).toContain('10 paciente publicados'); }); it('explorar, cambiar padre y restaurar parte del original y no modifica las barras', () => { const data = c2Fixture(), result = supported(data), original = structuredClone(result.figure); const bars = supported(data, { ...selection, figura: 'fig_c2_barras' }), before = structuredClone(bars); expect(donutView(result.figure, result.hierarchy!).data[0]['values']).toEqual([6,4]); const root = donutView(result.figure, result.hierarchy!); const expanded = donutView(result.figure, result.hierarchy!, 'G2'); const changed = donutView(result.figure, result.hierarchy!, 'G1'); expect(root.layout['legend']).toMatchObject({ orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top' }); expect(expanded.layout['legend']).toEqual(root.layout['legend']); expect(changed.layout['legend']).toEqual(root.layout['legend']); expect(expanded.data[0]['values']).toEqual([3,1]); expect(expanded.data[0]['hovertemplate']).toContain('paciente'); expect(expanded.data[1]['hovertemplate']).toContain('paciente'); for (const trace of [...root.data, ...expanded.data, ...changed.data]) { expect(trace['hovertemplate']).toContain(''); expect(trace['hovertemplate']).not.toContain('2025-S2'); } const compact = donutView(result.figure, result.hierarchy!, 'G2', 360); expect(compact.layout['showlegend']).toBe(false); expect(compact.layout['margin']).toMatchObject({ b: 16, l: 16, r: 16 }); expect(compact.data[0]['legendgrouptitle']).toEqual({ text: 'Categorías de G2' }); expect(changed.data[0]['values']).toEqual([6]); expect(root.data[0]['labels']).toEqual(['G1','G2']); expect(result.figure).toEqual(original); expect(bars).toEqual(before); }); it('no asume IDs de indicador ni dominio; sólo capacidades publicadas', () => { for (const dominio of ['tea','cacu','cama'] as const) { const data = c2Fixture(); data.id = 'future_name'; expect(supported(data, { ...selection, dominio, indicador: data.id }).model.total).toBe(10); } expect(c2Capability('C1', 'fig_c2_donas')).toBe(false); expect(c2Capability('C3r', 'fig_c2_barras')).toBe(false); expect(c2Capability('C2', 'future_representation')).toBe(false); }); it('periodo mensual concordante; varios periodos, tipo incorrecto y periodo distinto usan respaldo', () => { const data = c2Fixture(); data.tipo_periodo = 'mes'; data.periodos = ['2025-02']; data.filas.forEach(r => r['periodo'] = '2025-02'); expect(supported(data, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-02'] }).model.period).toBe('2025-02'); expect(c2Figure(data, selection).status).toBe('unsupported'); const sample = c2Fixture(); sample.periodos.push('2026-S1'); expect(c2Figure(sample, selection).status).toBe('unsupported'); expect(c2Figure(c2Fixture(), { ...selection, periodos: ['2026-S1'] }).status).toBe('unsupported'); }); it('árbol y ruta permiten descendientes de profundidad variable sin definir un JSON de nivel tres', () => { const nodes = [...supported().model.nodes, { id: 'detail', label: 'Detalle sintético', parentId: 'category:B' }, { id: 'deeper', label: 'Más detalle', parentId: 'detail' }]; expect(c2Descendants(nodes, { path: ['group:g2', 'category:B'] }).map(n => n.id)).toEqual(['detail','deeper']); expect(c2Descendants(nodes, { path: ['group:g1', 'category:B'] })).toEqual([]); expect(c2Descendants(nodes, { path: [] })).toBe(nodes); }); }); describe('paleta C2 institucional y semántica', () => { it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => { const data = c2Fixture(); (data['categorias'] as Record>)['A']['color'] = '#D98E4A'; const figure = supported(data, { ...selection, tema }).figure; expect((figure.data[0]['marker'] as Record)['colors']).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]); expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]); expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background); expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text }); expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2'); expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]); expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]); expect(c2Color('#D98E4A', 0)).toBe(C2_PALETTE.series[0]); expect(c2Color('#B55A1F', 2)).toBe(C2_PALETTE.series[2]); expect(c2Color('#9DBFE3', 1)).toBe('#9DBFE3'); expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]); expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined(); }); it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => { const luminance = (hex: string) => { const c = hex.slice(1).match(/../g)!.map(v => parseInt(v,16)/255).map(v => v <= .04045 ? v/12.92 : ((v+.055)/1.055)**2.4); return c[0]*.2126+c[1]*.7152+c[2]*.0722; }; for (const theme of [C2_PALETTE.claro,C2_PALETTE.oscuro]) { const text = luminance(theme.text), background = luminance(theme.background); const outline = luminance(theme.outline); expect((Math.max(text,background)+.05)/(Math.min(text,background)+.05)).toBeGreaterThan(4.5); expect((Math.max(outline,background)+.05)/(Math.min(outline,background)+.05)).toBeGreaterThan(1.4); } }); it('da aire a etiquetas y leyendas y conserva guías discretas en las barras', () => { const bars = supported(c2Fixture(), { ...selection, figura: 'fig_c2_barras' }).figure; expect(bars.layout['margin']).toMatchObject({ l: 76, t: 112, b: 62 }); expect(bars.layout['legend']).toMatchObject({ orientation: 'h', x: 1, xanchor: 'right', y: 1.12, yanchor: 'bottom' }); expect(bars.layout['xaxis']).toMatchObject({ showgrid: true, zeroline: false }); expect(bars.layout['yaxis']).toMatchObject({ automargin: true, ticklabelstandoff: 12, showgrid: false }); expect((bars.data[0]['marker'] as Record)['line']).toMatchObject({ color: C2_PALETTE.claro.outline, width: 0.7 }); const donut = supported(c2Fixture(), selection).figure; expect((donut.data[0]['marker'] as Record)['line']).toMatchObject({ color: C2_PALETTE.claro.outline, width: 0.7 }); }); });