import { IndicadorDatos, PlotlyFigure } from './indicadores.models'; export interface DonutHierarchy { parents: readonly string[]; children: readonly { label: string; parent: string; value: number }[]; categoryTrace: number; parentTrace?: number; } export interface DonutSelection { parent?: string; category?: string; period?: string; } export interface DonutLegendEntry { label: string; color?: string; } function record(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } function plainLabel(value: unknown): value is string { return typeof value === 'string' && !!value.trim() && !/[<>]/.test(value); } function labels(trace: Record): trace is Record & { labels: string[]; values: number[] } { return Array.isArray(trace['labels']) && trace['labels'].length > 0 && trace['labels'].every(plainLabel) && new Set(trace['labels']).size === trace['labels'].length && Array.isArray(trace['values']) && trace['values'].length === trace['labels'].length && trace['values'].every(v => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0); } // Reject point-wise attributes whose correspondence cannot be preserved on a // subset. Scalars and unknown scalar attributes survive on the derived copy. function safeArrays(value: Record, path = ''): boolean { return Object.entries(value).every(([key, item]) => { const field = path + key; return Array.isArray(item) ? ['labels', 'values', 'marker.colors', 'domain.x', 'domain.y'].includes(field) : !record(item) || safeArrays(item, field + '.'); }); } function centerCount(value: unknown): value is Record & { text: string } { return centerCountAt(value, 0.5, 0.5); } function centerCountAt(value: unknown, x: number, y: number): value is Record & { text: string } { return record(value) && value['x'] === x && value['y'] === y && value['xref'] === 'paper' && value['yref'] === 'paper' && value['showarrow'] === false && typeof value['text'] === 'string' && /^\d+<\/b>$/.test(value['text']); } export function donutLegend(figure: PlotlyFigure): readonly DonutLegendEntry[] | undefined { if (figure.data.length !== 1) return; const trace = figure.data[0]; if (trace['type'] !== 'pie' || !labels(trace)) return; const marker = record(trace['marker']) ? trace['marker'] : undefined; const colors = marker && Array.isArray(marker['colors']) && marker['colors'].length === trace.labels.length ? marker['colors'] : []; return trace.labels.map((label, index) => ({ label, color: typeof colors[index] === 'string' && /^#[0-9a-f]{6}$/i.test(colors[index] as string) ? colors[index] as string : undefined, })); } function donutCanvas(source: PlotlyFigure): PlotlyFigure { const figure = structuredClone(source); figure.layout['showlegend'] = false; figure.layout['height'] = 440; figure.layout['margin'] = { ...(record(figure.layout['margin']) ? figure.layout['margin'] : {}), l: 16, r: 16, t: 16, b: 16, pad: 0, autoexpand: false }; const annotations = figure.layout['annotations']; if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a) ? { ...a, x: 0.5, y: 0.5, xanchor: 'center', yanchor: 'middle' } : a); return figure; } export function donutSimpleView(source: PlotlyFigure): PlotlyFigure { const figure = donutCanvas(source); figure.data = figure.data.map(trace => trace['type'] === 'pie' ? { ...trace, domain: { x: [0, 1], y: [0, 1] }, showlegend: false } : trace); return figure; } // Only a structural candidate: /datos supplies the semantics. No indicator ID, // category count, legendgroup, trace order or exact domain decides eligibility. // C2 metadata describes category -> parent, not further levels or facets. export function donutPeriod(figure: PlotlyFigure): string | undefined { if (figure.frames?.length || !figure.data.length || figure.data.length > 2 || figure.config?.['staticPlot'] === true || ['updatemenus', 'sliders'].some(k => figure.layout[k] !== undefined) || (Array.isArray(figure.layout['hiddenlabels']) && figure.layout['hiddenlabels'].length)) return; const periods = new Set(); for (const trace of figure.data) { if (trace['type'] !== 'pie' || !labels(trace) || trace['visible'] === false || trace['visible'] === 'legendonly' || typeof trace['hole'] !== 'number' || trace['hole'] <= 0 || trace['hole'] >= 1 || !safeArrays(trace) || (record(trace['marker']) && Array.isArray(trace['marker']['colors']) && trace['marker']['colors'].length !== trace.labels.length)) return; const match = typeof trace['name'] === 'string' && /^(\d{4}-(?:S[12]|0[1-9]|1[0-2]))(?:$|, )/.exec(trace['name']); if (!match) return; periods.add(match[1]); } return periods.size === 1 ? [...periods][0] : undefined; } export function donutHierarchy(figure: PlotlyFigure, data: IndicadorDatos): DonutHierarchy | undefined { const period = donutPeriod(figure); if (!period || data.contrato !== 'C2' || data.periodos.length !== 1 || data.periodos[0] !== period || data.tipo_periodo !== (period.includes('-S') ? 'semestre' : 'mes') || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !data.filas.length || data.filas.some(r => r['periodo'] !== period || r['grupo'] !== 'TOTAL' || r['estrato'] != null || r['suprimido'] !== 0 || typeof r['n'] !== 'number' || !Number.isSafeInteger(r['n']) || r['n'] < 0 || typeof r['orden'] !== 'number' || !Number.isFinite(r['orden']))) return; const categories = data['categorias'], groups = data['grupos_de_categoria']; const children: { label: string; parent: string; value: number }[] = []; const ids = new Set(); for (const row of data.filas) { const id = row['categoria']; if (typeof id !== 'string' || ids.has(id) || !Object.hasOwn(categories, id)) return; ids.add(id); const category = categories[id]; if (!record(category) || !plainLabel(category['etiqueta']) || typeof category['grupo'] !== 'string' || !Object.hasOwn(groups, category['grupo'])) return; const parent = groups[category['grupo']]; if (!plainLabel(parent)) return; children.push({ label: category['etiqueta'], parent, value: row['n'] as number }); } // Every category must be explicit, including published zeros. A complete // TOTAL partition is required; never aggregate overlapping row populations. if (Object.keys(categories).length !== children.length || new Set(children.map(c => c.label)).size !== children.length || !Number.isSafeInteger(children.reduce((sum, c) => sum + c.value, 0)) || children.every(c => c.value === 0)) return; // A numeric center may be another denominator. Only adapt it when it also // agrees with the verified partition; otherwise retain the published figure. const annotations = figure.layout['annotations']; const total = children.reduce((sum, c) => sum + c.value, 0); if (Array.isArray(annotations) && annotations.some(a => centerCount(a) && Number(a.text.slice(3, -4)) !== total)) return; const groupIds = new Set(Object.values(categories).map(c => record(c) ? c['grupo'] : undefined)); const groupNames = [...groupIds].map(id => groups[id as string]); if (new Set(groupNames).size !== groupNames.length) return; // Verify labels AND counts; never infer hierarchy from colors or equal sums. const matches = figure.data.flatMap((t, index) => labels(t) && t.labels.length === children.length && children.every(c => t.values[t.labels.indexOf(c.label)] === c.value) ? [index] : []); if (matches.length !== 1) return; const categoryTrace = matches[0], outer = figure.data[categoryTrace]; if (!labels(outer)) return; const ordered = outer.labels.map(label => children.find(c => c.label === label)!); const parents = [...new Set(ordered.map(c => c.parent))]; const parentTrace = figure.data.length === 2 ? 1 - categoryTrace : undefined; if (parentTrace !== undefined) { const inner = figure.data[parentTrace]; if (!labels(inner) || inner.labels.length !== parents.length || inner.labels.some((p, i) => !parents.includes(p) || children.filter(c => c.parent === p).reduce((n, c) => n + c.value, 0) !== inner.values[i])) return; return { parents: [...inner.labels], children: ordered, categoryTrace, parentTrace }; } return { parents, children: ordered, categoryTrace }; } // Each view starts from the current presentation of the original HTTP figure. // The inner ring retains ALL parents so another can be selected directly. Its // denominator is the full verified partition; the outer ring is within-parent. export function donutView(source: PlotlyFigure, hierarchy: DonutHierarchy, parent?: string, _availableWidth?: number): PlotlyFigure { const figure = donutCanvas(source); const meta = figure.layout['meta']; const unit = record(meta) && typeof meta['unit'] === 'string' && !/[<>&]/.test(meta['unit']) ? ' ' + meta['unit'] : ''; const outer = figure.data[hierarchy.categoryTrace]; if (!outer || !labels(outer)) return figure; const marker = record(outer['marker']) ? outer['marker'] : {}; const colors = marker['colors']; const publishedParent = hierarchy.parentTrace === undefined ? undefined : figure.data[hierarchy.parentTrace]; const inner: Record = publishedParent ?? { ...outer, labels: [...hierarchy.parents], values: hierarchy.parents.map(p => hierarchy.children.filter(c => c.parent === p).reduce((sum, c) => sum + c.value, 0)), // Reuse received category colors; no new institutional palette. marker: { ...marker, ...(Array.isArray(colors) ? { colors: hierarchy.parents.map(p => colors[hierarchy.children.findIndex(c => c.parent === p)]) } : {}) }, }; // HTML owns the independent, bounded legend. Plotly gets the same full area // in every state, including on narrow cards; it cannot move the circle. const plotDomain = { x: [0, 1], y: [0, 1] }; const center = { x: (plotDomain.x[0] + plotDomain.x[1]) / 2, y: (plotDomain.y[0] + plotDomain.y[1]) / 2, }; const annotations = figure.layout['annotations']; if (Array.isArray(annotations)) figure.layout['annotations'] = annotations.map(a => centerCount(a) ? { ...a, x: center.x, y: center.y, xanchor: 'center', yanchor: 'middle' } : a); const parentView = { ...inner, domain: plotDomain, hole: 0.55, sort: false, textinfo: 'none', showlegend: false, legendgroup: 'grupos', legendgrouptitle: { text: 'Grupos' }, hovertemplate: '%{label}
%{value}' + unit + ' (%{percent} del total de esta dona)' }; if (!parent || !hierarchy.parents.includes(parent)) { figure.data = [parentView]; return figure; } const indices = outer.labels.flatMap((label, i) => hierarchy.children.some(c => c.label === label && c.parent === parent) ? [i] : []); const value = indices.reduce((sum, i) => sum + outer.values[i], 0); figure.data = [ { ...outer, labels: indices.map(i => outer.labels[i]), values: indices.map(i => outer.values[i]), domain: plotDomain, hole: 0.70, sort: false, showlegend: false, textinfo: 'none', legendgroup: 'categorias', legendgrouptitle: { text: 'Categorías de ' + parent }, marker: { ...marker, ...(Array.isArray(colors) ? { colors: indices.map(i => colors[i]) } : {}) }, hovertemplate: '%{label}
%{value}' + unit + ' (%{percent} del grupo)' }, { ...parentView, domain: { x: [0.17, 0.83], y: [0.17, 0.83] } }, ]; const finalAnnotations = figure.layout['annotations']; if (Array.isArray(finalAnnotations)) figure.layout['annotations'] = finalAnnotations.map(a => centerCountAt(a, center.x, center.y) ? { ...a, x: center.x, y: center.y, xanchor: 'center', yanchor: 'middle', text: '' + value + '' } : a); return figure; }