import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { DonutSelection } from './indicadores-donut-drilldown'; import { c2Theme, seriesColors } from './indicadores-c2-palette'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); // The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut. const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'estadio', 'tamano', 'etapa']; /** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */ export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string { if (d === 'grupo_edad') return 'Por grupo de edad'; if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento'; const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta; return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d); } export type MedidaEstrato = 'conteo' | 'porcentaje'; export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] { return item.contrato === 'C2' && Array.isArray(item.filtros) ? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; } // Whether a composition declares `estrato` among its strata: the catalog from FHIR carries the Measure's declared strata // (`estratos`) and no local filters. Only views that read one fixed stratum use it (CaCu's EU7 by follow-up status); // it doesn't turn on stratified figures or filters for other C2 measures. export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): boolean { const declarados = (item as Indicador & { estratos?: unknown }).estratos; return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato); } /** A stratum a reader can show or hide: its published value and label, in the published order. */ export interface StratumOption { valor: string; etiqueta: string; } export function stratumOptions(data: IndicadorDatos): StratumOption[] { const valores = Array.isArray(data['valores_estrato']) ? data['valores_estrato'] as unknown[] : []; const etiquetas = record(data['etiquetas_estrato']) ? data['etiquetas_estrato'] : {}; return valores.filter((v): v is string => typeof v === 'string') .map(valor => ({ valor, etiqueta: typeof etiquetas[valor] === 'string' ? etiquetas[valor] as string : valor })); } // `percent`: the cell's share of its stratum, when the stratum's total is known. export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } /** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells, * unless that would leave none. */ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } { if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos']) || Object.keys(data['grupos']).length !== 1 || !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length || !data['valores_estrato'].every(v => typeof v === 'string') || new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida'); const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; const shown = published.filter(s => !hidden.has(s)); const strata = shown.length ? shown : published; const statisticalGroup = Object.keys(data['grupos'])[0]; if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); const catalog = data['categorias'], groups = data['grupos_de_categoria']; const entries = new Map(); const rows = new Map>(); for (const row of data.filas) { const id = row['categoria'], stratum = row['estrato'], n = row['n']; if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id || typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) || ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida'); const key = JSON.stringify([id, stratum]); if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas'); rows.set(key, row); const meta = record(catalog[id]) ? catalog[id] : {}; entries.set(id, { order: row['orden'], label: typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id, color: typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined, parent: typeof meta['grupo'] === 'string' && typeof groups[meta['grupo']] === 'string' ? groups[meta['grupo']] as string : undefined }); } // Unknown categories are appended, retaining their published relative order. const categories = [...entries].sort(([a, x], [b, y]) => Number(!Object.hasOwn(catalog, a)) - Number(!Object.hasOwn(catalog, b)) || x.order - y.order) .filter(([, c]) => (!selection.parent || c.parent === selection.parent) && (!selection.category || c.label === selection.category)); if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas'); const cells: StratifiedCell[] = []; const theme = c2Theme(tema); const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id)); // The stratum's total: the one published, or else the sum of its cells when every one is published. A share is // only drawn over a known total; a suppressed or missing total leaves the stratum without percentages. const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record[] : []; const totalDe = (s: string): number | null => { const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup); if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null; const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s]))); if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null; const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0); return suma > 0 ? suma : null; }; const porcentaje = medida === 'porcentaje'; const figure: PlotlyFigure = { data: strata.map(s => { const series = published.indexOf(s); // a stratum keeps its pattern when others are hidden const selected = categories.map(([id, c]) => { const row = rows.get(JSON.stringify([id, s])); const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible'; const value = status === 'Publicado' ? row!['n'] as number : null; const total = totalDe(s); const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null; cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status }); return { value, percent, total }; }); const x = selected.map(v => porcentaje ? v.percent : v.value); return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)), customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']), marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, hovertemplate: porcentaje ? '%{y}
%{x:.1f} % (%{customdata[0]} de %{customdata[1]})%{fullData.name}' : '%{y}
%{x}%{fullData.name}' }; }), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true, height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 }, xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid } : { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true }, legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } }; return { figure, cells }; }