import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models'; import { DonutHierarchy } from './indicadores-donut-drilldown'; import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette'; export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; } // Normalized presentation nodes and a selection path are independent of Plotly. // No level-3 wire format is assumed. This decoder keeps the complete partition; // local selection is applied to a separate, verified presentation copy. export interface C2Node { id: string; label: string; parentId?: string; } export interface C2Selection { path: readonly string[]; } export function c2Descendants(nodes: readonly C2Node[], selection: C2Selection): readonly C2Node[] { let parentId: string | undefined; for (const id of selection.path) { if (!nodes.some(n => n.id === id && n.parentId === parentId)) return []; parentId = id; } const found = new Set(); if (!parentId) return nodes; const visit = (id: string) => { for (const node of nodes.filter(n => n.parentId === id)) { if (found.has(node.id)) continue; found.add(node.id); visit(node.id); } }; visit(parentId); return nodes.filter(n => found.has(n.id)); } export interface C2Distribution { period: string; unit: string; title: string; categories: readonly C2Category[]; parents: readonly C2Node[]; nodes: readonly C2Node[]; total: number; notes: readonly string[]; } export type C2Result = { status: 'unsupported'; reason: string } | { status: 'supported'; model: C2Distribution; figure: PlotlyFigure; hierarchy?: DonutHierarchy; emptyMessage?: string }; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const label = (v: unknown): v is string => typeof v === 'string' && !!v.trim() && !/[<>&]/.test(v); const color = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v); export function c2Capability(contract: string, representation: string): boolean { return contract === 'C2' && ['fig_c2_donas', 'fig_c2_barras'].includes(representation); } export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Result { const unsupported = (reason: string): C2Result => ({ status: 'unsupported', reason }); if (!c2Capability(data.contrato, selection.figura)) return unsupported('Representación no soportada'); if (data.id !== selection.indicador || data.tipo_periodo !== selection.tipoPeriodo || data.periodos.length !== 1 || parsePeriodos(data.periodos[0], data.tipo_periodo)?.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0]))) return unsupported('Se requiere un periodo único concordante'); if (!label(data['unidad']) || !label(data['titulo']) || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos']) || Object.keys(data['grupos']).length !== 1 || !Object.hasOwn(data['grupos'], 'TOTAL') || data['estrato'] != null || data['meta'] != null || !Array.isArray(data.notas) || !data.notas.every(label)) return unsupported('Metadatos insuficientes o no soportados'); const period = data.periodos[0], catalog = data['categorias'], groups = data['grupos_de_categoria']; if (!Object.keys(catalog).length) return unsupported('Catálogo de categorías vacío'); const categories: C2Category[] = [], orders = new Set(), ids = new Set(); const rows = [...data.filas].sort((a, b) => Number(a['orden']) - Number(b['orden'])); for (const row of rows) { const id = row['categoria'], n = row['n'], order = row['orden']; if (row['periodo'] !== period || row['grupo'] !== 'TOTAL' || row['estrato'] != null || (row['unidad'] !== undefined && row['unidad'] !== data['unidad']) || (row['suprimido'] !== 0 && row['suprimido'] !== false) || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0 || typeof order !== 'number' || !Number.isFinite(order) || orders.has(order) || typeof id !== 'string' || ids.has(id) || !Object.hasOwn(catalog, id)) return unsupported('Partición incompleta, suprimida o no verificable'); const entry = catalog[id]; if (!record(entry) || !label(entry['etiqueta']) || (entry['color'] != null && !color(entry['color'])) || (entry['grupo'] != null && (typeof entry['grupo'] !== 'string' || !Object.hasOwn(groups, entry['grupo']) || !label(groups[entry['grupo']])))) return unsupported('Categoría sin metadatos verificables'); orders.add(order); ids.add(id); categories.push({ id, label: entry['etiqueta'], value: n, color: entry['color'] as string | undefined, parentId: typeof entry['grupo'] === 'string' ? entry['grupo'] : undefined }); } if (categories.length && categories.length !== Object.keys(catalog).length) return unsupported('Faltan categorías explícitas'); if (new Set(categories.map(c => c.label)).size !== categories.length) return unsupported('Etiquetas ambiguas'); const total = categories.reduce((sum, c) => sum + c.value, 0); if (!Number.isSafeInteger(total) || rows.some(r => Object.hasOwn(r, 'denominador') && r['denominador'] !== total) || (Object.hasOwn(data, 'denominador') && data['denominador'] !== total)) return unsupported('Denominador no verificable'); const parentIds = [...new Set(categories.flatMap(c => c.parentId ? [c.parentId] : []))]; if ((parentIds.length && categories.some(c => !c.parentId)) || (categories.length && Object.keys(groups).length !== parentIds.length)) return unsupported('Relación de grupos incompleta'); const parents = parentIds.map(id => ({ id: 'group:' + id, label: groups[id] as string })); if (new Set(parents.map(p => p.label)).size !== parents.length) return unsupported('Grupos ambiguos'); const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))]; const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] }; const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label); const colors = seriesColors(categories.map(c => c.color)); const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined; const layout: Record = { title: { text: model.title + ', ' + period }, autosize: true, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 }, margin: { l: 76, r: 28, t: 112, b: 62, pad: 4 }, legend: selection.figura === 'fig_c2_donas' ? { orientation: 'v', x: 1, xanchor: 'right', y: 1, yanchor: 'top', itemclick: false, itemdoubleclick: false } : { orientation: 'h', x: 1, xanchor: 'right', y: 1.12, yanchor: 'bottom', itemclick: false, itemdoubleclick: false }, meta: { period, unit: model.unit, denominator: total, denominatorScope: 'Suma de conteos publicados de la partición TOTAL, incluyendo categorías sin dato' } }; const figure: PlotlyFigure = { data: [], layout }; if (selection.figura === 'fig_c2_barras') { if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels, marker: { color: colors, line: { color: theme.outline, width: 0.7 } }, hovertemplate: '%{y}
%{x} ' + model.unit + '' }]; layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true, gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1, ticks: 'outside', tickcolor: '#AEB7C2', automargin: true }; layout['yaxis'] = { type: 'category', categoryorder: 'array', categoryarray: [...labels].reverse(), automargin: true, ticklabelstandoff: 12, showgrid: false, showline: true, linecolor: '#AEB7C2', linewidth: 1, ticks: 'outside', tickcolor: '#AEB7C2' }; } else if (total > 0) { layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false, text: '' + total + '', font: { color: theme.text, size: 18 } }]; figure.data = [{ type: 'pie', labels, values, marker: { colors, line: { color: theme.outline, width: 0.7 } }, hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] }, hovertemplate: '%{label}
%{value} ' + model.unit + '
%{percent} de los ' + total + ' ' + model.unit + ' publicados' }]; if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label), values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)), marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } }, hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } }); } const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0 ? { parents: parents.map(p => p.label), children: categories.map(c => ({ label: c.label, value: c.value, parent: groups[c.parentId!] as string })), categoryTrace: 0, parentTrace: 1 } : undefined; return { status: 'supported', model, figure, hierarchy, emptyMessage }; }