import { c2Figure } from './indicadores-c2-adapter'; import { c2Fixture } from './indicadores-c2-adapter.testing'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; import { FigureSelection, PlotlyFigure } from './indicadores.models'; const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; const local = { parent: 'G2', period: '2025-S2' }; function bars(data = c2Fixture()): PlotlyFigure { const result = c2Figure(data, selection); if (result.status !== 'supported') throw new Error(result.reason); return result.figure; } describe('selección local segura de barras generales C2', () => { it('sin selección conserva la distribución completa', () => { const data = c2Fixture(), source = bars(data), before = structuredClone(source); expect(c2GeneralSelection(source, data, selection, {})).toBeUndefined(); expect(source).toEqual(before); }); it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => { const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source }); const view = c2GeneralSelection(source, data, selection, local)!; expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } }); expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] }); expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' }); expect(view.context).toContain('G2, 2025-S2'); expect({ data, source }).toEqual(before); (view.figure.data[0]['x'] as number[])[0] = 999; expect(source).toEqual(before.source); }); it.each([true, false])('categoría con padre declarado: %s, conserva porcentaje original sin renormalizar', withParent => { const data = c2Fixture(), source = bars(data); source.data[0]['text'] = ['60%', '30%', '10%']; source.data[0]['customdata'] = [['A', 10], ['B', 10], ['C', 10]]; source.data[0]['hovertemplate'] = '%{y}: %{x} (%{text})'; const view = c2GeneralSelection(source, data, selection, { ...local, parent: withParent ? 'G2' : undefined, category: 'B' })!; expect(view.figure.data[0]).toMatchObject({ x: [3], y: ['B'], text: ['30%'], customdata: [['B', 10]], hovertemplate: '%{y}: %{x} (%{text})' }); expect(view.context).toContain('denominador de la distribución completa del periodo'); }); it('preserva colores escalares, arrays de errores y atributos escalares desconocidos', () => { const data = c2Fixture(), source = bars(data); source.data[0]['marker'] = { color: '#abcdef' }; source.data[0]['error_x'] = { array: [1, 2, 3], arrayminus: [0, 1, 2] }; source.data[0]['future'] = { retained: true }; expect(c2GeneralSelection(source, data, selection, local)!.figure.data[0]).toMatchObject({ marker: { color: '#abcdef' }, error_x: { array: [2, 3], arrayminus: [1, 2] }, future: { retained: true } }); }); it.each([ { parent: 'inexistente', period: local.period }, { category: 'inexistente', period: local.period }, { parent: 'G1', category: 'B', period: local.period }, { parent: 'G2' }, { ...local, period: '2026-S1' }, { period: local.period }, ])('selección inválida %j mantiene la vista completa', candidate => { const data = c2Fixture(), source = bars(data), before = structuredClone(source); expect(c2GeneralSelection(source, data, selection, candidate)).toBeUndefined(); expect(source).toEqual(before); }); it.each(['simple', 'partial-hierarchy', 'missing-row', 'null', 'suppressed', 'missing-unit', 'denominator', 'ambiguous-label'])('contrato %s no produce un filtrado parcial', kind => { const data = c2Fixture(), source = bars(data), catalog = data['categorias'] as Record>; if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(catalog).forEach(c => c['grupo'] = null); } if (kind === 'partial-hierarchy') catalog['A']['grupo'] = null; if (kind === 'missing-row') data.filas.shift(); if (kind === 'null') data.filas[0]['n'] = null; if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; if (kind === 'missing-unit') delete data['unidad']; if (kind === 'denominator') data['denominador'] = 999; if (kind === 'ambiguous-label') catalog['A']['etiqueta'] = 'B'; const before = structuredClone({ source, data }); expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); expect({ source, data }).toEqual(before); }); it.each(['partial', 'mismatch', 'duplicate-period', 'unnamed', 'wrong-type', 'frames', 'menu', 'unknown-array', 'short-array', 'explicit-ticks', 'normalization', 'metadata-period', 'metadata-denominator', 'secondary-axis', 'external-data'])('figura %s conserva la presentación publicada', kind => { const data = c2Fixture(), source = bars(data); if (kind === 'partial') { source.data[0]['x'] = [3, 1]; source.data[0]['y'] = ['B', 'C']; } if (kind === 'mismatch') source.data[0]['x'] = [7, 3, 1]; if (kind === 'duplicate-period') source.data.push(structuredClone(source.data[0])); if (kind === 'unnamed') delete source.data[0]['name']; if (kind === 'wrong-type') source.data[0]['type'] = 'scatter'; if (kind === 'frames') source.frames = [{ name: 'future' }]; if (kind === 'menu') source.layout['updatemenus'] = []; if (kind === 'unknown-array') source.data[0]['future'] = [1, 2, 3]; if (kind === 'short-array') source.data[0]['text'] = ['60%']; if (kind === 'explicit-ticks') source.layout['yaxis'] = { tickvals: [0, 1, 2] }; if (kind === 'normalization') source.layout['barnorm'] = 'percent'; if (kind === 'metadata-period') source.layout['meta'] = { period: '2026-S1' }; if (kind === 'metadata-denominator') source.layout['meta'] = { denominator: 999 }; if (kind === 'secondary-axis') source.data[0]['yaxis'] = 'y2'; if (kind === 'external-data') source.data[0]['xsrc'] = 'remote'; const before = structuredClone(source); expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); expect(source).toEqual(before); }); it('cero explícito permanece cero y no se reconstruye un valor null/suprimido', () => { const data = c2Fixture(); data.filas[2]['n'] = 0; const source = bars(data); expect(c2GeneralSelection(source, data, selection, { ...local, category: 'C' })!.figure.data[0]['x']).toEqual([0]); data.filas[2]['n'] = null; data.filas[2]['suprimido'] = 1; source.data[0]['x'] = [6, 3, null]; expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); expect(source.data[0]['x']).toEqual([6, 3, null]); }); it('multiperiodo conserva únicamente la traza seleccionada y sus porcentajes, sin sumar periodos', () => { const data = c2Fixture(), source = bars(data); delete source.layout['meta']; // Published multiperiod bars have per-trace periods. data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1', n: Number(r['n']) * 2 }))); const second = { ...structuredClone(source.data[0]), name: '2025-S1', x: [12, 6, 2], text: ['60%', '30%', '10%'] }; source.data.push(second); const multiple = { ...selection, periodos: [...data.periodos] }, before = structuredClone({ data, source }); const view = c2GeneralSelection(source, data, multiple, { ...local, period: '2025-S1' })!; expect(view.figure.data).toHaveLength(1); expect(view.figure.data[0]).toMatchObject({ name: '2025-S1', x: [6, 2], y: ['B', 'C'], text: ['30%', '10%'] }); expect(c2GeneralSelection(source, data, selection, { ...local, period: '2025-S1' })).toBeUndefined(); expect(c2GeneralSelection(source, data, multiple, {})).toBeUndefined(); expect({ data, source }).toEqual(before); }); it('Todos con reporte: un periodo sin traza publicada conserva la vista completa disponible', () => { const data = c2Fixture(), source = bars(data); data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1' }))); const before = structuredClone(source); expect(c2GeneralSelection(source, data, { ...selection, periodos: undefined }, { ...local, period: '2025-S1' })).toBeUndefined(); expect(source).toEqual(before); }); it.each([ { id: 'c2_grados_biopsia_sintetico', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' }, categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] }, { id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' }, categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] }, { id: 'cama_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Benigno', ANORMAL: 'Cáncer', SIN_DATO: 'Sin dato' }, categories: [['BENIGNO', 'Benigno', 'NO_ANORMAL'], ['CARCINOMA_IN_SITU', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA_INVASOR', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] }, ])('$id: relaciones publicadas con conteos sintéticos, sin reglas por ID', candidate => { const data = c2Fixture(); data.id = candidate.id; data['unidad'] = candidate.unit; data['grupos_de_categoria'] = candidate.groups; data['categorias'] = Object.fromEntries(candidate.categories.map(([id, etiqueta, grupo]) => [id, { etiqueta, grupo }])); data.filas = candidate.categories.map(([categoria], orden) => ({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, orden, n: orden + 1, suprimido: 0 })); const s = { ...selection, indicador: candidate.id }, adapted = c2Figure(data, s); if (adapted.status !== 'supported') throw new Error(adapted.reason); const source = adapted.figure, parent = candidate.groups.ANORMAL; expect(c2GeneralSelection(source, data, s, { parent, period: local.period })!.figure.data[0]['y']) .toEqual(candidate.categories.filter(c => c[2] === 'ANORMAL').map(c => c[1])); const category = candidate.categories.find(c => c[2] === 'ANORMAL')![1]; expect(c2GeneralSelection(source, data, s, { parent, category, period: local.period })!.figure.data[0]['y']).toEqual([category]); // Re-identification does not change capabilities or behavior. data.id = 'otro-identificador'; expect(c2GeneralSelection(source, data, { ...s, indicador: data.id }, { parent, period: local.period })).toBeDefined(); }); });