import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette'; import { percentNumber, shareText } from './indicadores-format'; // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. // This boundary is intentionally specific to EU7. Unknown cells never become zero. export const ESTRATO = 'estatus_seguimiento'; const SIN_DATO = 'SIN_DATO'; export interface Seleccion { grupo?: string; categoria?: string; } export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; } export interface Grupo { id: string; etiqueta: string; color: string; } export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; } export interface Escenario { id: string; etiqueta: string; celdas: Record; den: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; } export interface Modelo { periodo: string; categorias: Categoria[]; grupos: Grupo[]; celdas: Record; total: number | null; sinDato: Celda; escenarios: Escenario[]; vacio: boolean; notas: string[]; sinDatoEtiqueta: string; } export class Eu7Incompatible extends Error {} const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); const miles = (v: number) => v.toLocaleString('es-MX'); const fail = (message: string): never => { throw new Eu7Incompatible(message); }; function celda(fila?: Record): Celda { if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' }; return typeof fila?.['n'] === 'number' && fila['suprimido'] === 0 ? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' }; } function suma(celdas: Celda[]): number | null { if (celdas.some(c => c.n === null)) return null; const value = celdas.reduce((s, c) => s + c.n!, 0); return Number.isSafeInteger(value) ? value : fail('Conteos fuera de rango.'); } function estado(celdas: Celda[]): Escenario['estado'] { return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado'; } function rgba(hex: string, alfa: number): string { const v = parseInt(hex.slice(1), 16); return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; } function catalogo(data: IndicadorDatos): Categoria[] { const cats = data['categorias'], grupos = data['grupos_de_categoria']; if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.'); const result = Object.entries(cats).map(([id, c]) => { if (!registro(c) || typeof c['etiqueta'] !== 'string' || !c['etiqueta'].trim() || typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']) || typeof c['grupo'] !== 'string' || typeof grupos[c['grupo']] !== 'string' || (id === SIN_DATO) !== (c['grupo'] === SIN_DATO)) return fail('Categorías EU7 incompatibles.'); return { id, etiqueta: c['etiqueta'], color: c['color'], grupo: c['grupo'] }; }); if (result.length < 2 || new Set(result.map(c => c.etiqueta)).size !== result.length) return fail('Categorías EU7 ambiguas.'); return result; } /** Validate the common temporal scope before exposing any period's figures. */ export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { for (const d of [general, escenarios]) { if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p)) || !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) { return fail('Los datos EU7 no corresponden al indicador o al periodo aplicado.'); } } if (general.periodos.length !== escenarios.periodos.length || general.periodos.some(p => !escenarios.periodos.includes(p)) || (solicitados && (solicitados.length !== general.periodos.length || solicitados.some(p => !general.periodos.includes(p)))) || general['version'] !== escenarios['version'] || general['unidad'] !== escenarios['unidad']) { return fail('Las respuestas general y estratificada no comparten periodos, versión o unidad.'); } return solicitados ? [...solicitados] : [...general.periodos].sort(); } /** Two immutable /datos payloads -> one safe presentation model for a single period. */ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo { periodosCompatibles(general, porEscenario, general.tipo_periodo); const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato']; if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo) || !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length || !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string') || [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) { return fail('Respuestas EU7 inválidas para el escenario clínico sin filtros locales.'); } const cats = catalogo(general), other = catalogo(porEscenario); const nombres = general['grupos_de_categoria'] as Record; const otrosNombres = porEscenario['grupos_de_categoria'] as Record; if (cats.length !== other.length || cats.some(c => { const o = other.find(v => v.id === c.id); return !o || o.etiqueta !== c.etiqueta || o.color !== c.color || o.grupo !== c.grupo || nombres[c.grupo] !== otrosNombres[c.grupo]; })) return fail('Los catálogos general y estratificado son diferentes.'); const orden = new Map(); const indexar = (d: IndicadorDatos, estratificado: boolean) => { const index = new Map>(); for (const row of d.filas.filter(f => f['periodo'] === periodo)) { const c = row['categoria'], e = row['estrato'], n = row['n'], o = row['orden']; if (row['grupo'] !== 'TOTAL' || typeof c !== 'string' || !cats.some(cat => cat.id === c) || (estratificado ? typeof e !== 'string' || !valores.includes(e) : e != null) || typeof o !== 'number' || !Number.isSafeInteger(o) || o < 0 || ![0, 1].includes(row['suprimido'] as number) || (n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) return fail('Fila EU7 inválida.'); const key = JSON.stringify([estratificado ? e : null, c]); if (index.has(key) || (orden.has(c) && orden.get(c) !== o)) return fail('Filas u orden EU7 ambiguos.'); orden.set(c, o); index.set(key, row); } return index; }; const g = indexar(general, false), e = indexar(porEscenario, true); const reporte = (d: IndicadorDatos) => { const reports = d['reportes']; if (reports === undefined) return undefined; if (!Array.isArray(reports) || !reports.every(registro)) return fail('Procedencia EU7 inválida.'); const active = reports.filter(r => r['periodo'] === periodo); if (active.length !== 1) return fail('Procedencia del periodo EU7 ambigua.'); return active[0]; }; const rg = reporte(general), re = reporte(porEscenario); // With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's // `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there. // Without ids, the generation time is still part of the provenance. const identificados = rg?.['report_id'] != null && re?.['report_id'] != null; const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha']; if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.'); if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.'); // Missing rows remain unavailable. Catalog order is used only for the accessible // list of missing categories; a partial distribution is never drawn as a donut. const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity)); const claves = baseCategorias.map(c => c.grupo); const bases = basesPorGrupo(claves); const colores = paintByGroup(claves); const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] })); const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! })); const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))])); const totals = porEscenario['totales_estrato']; if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.'); const escenarios: Escenario[] = (valores as string[]).filter(v => [...e.values()].some(row => row['estrato'] === v)).map(id => { const cells = Object.fromEntries(cats.map(c => [c.id, celda(e.get(JSON.stringify([id, c.id])))])); const matches = (totals as Record[] | undefined)?.filter(t => t['periodo'] === periodo && t['estrato'] === id) ?? []; if (matches.length > 1 || matches.some(t => t['grupo'] !== 'TOTAL' || ![0, 1].includes(t['suprimido'] as number) || (t['n'] !== null && (typeof t['n'] !== 'number' || !Number.isSafeInteger(t['n']) || t['n'] < 0)))) return fail('Total de escenario ambiguo.'); const total = matches[0] && celda(matches[0]); const estadoEscenario = estado([...Object.values(cells), ...(total ? [total] : [])]); const completo = suma(Object.values(cells)); if (completo !== null && total?.n != null && completo !== total.n) return fail('El total del escenario difiere de sus categorías.'); return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario, den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null }; }); // A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no // scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one. const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0); // Compare only fully published sums. Never derive a hidden value by subtraction. if (escenarios.length) { for (const c of cats) { const total = suma(escenarios.map(s => s.celdas[c.id])); if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.'); } } else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.'); if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.'); return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO], sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta, total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length), notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] }; } const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo); const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id])); export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string { return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta : sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL'; } /** Same state machine as the deliverable, with guards for unrelated/stale events. */ export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number): Seleccion { if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {}; if (traza === 'grupos') { const g = m.grupos[indice]?.id; return !g ? sel : sel.grupo === g ? {} : { grupo: g }; } if (traza !== 'categorias') return sel; const c = m.categorias[indice]; if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel; return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id }; } export function porcentaje(s: Escenario, categoria: string): number | null { const n = s.celdas[categoria]?.n; return s.den !== null && s.den > 0 && n != null ? 100 * n / s.den : null; } /** Three pies share one square plot area; SIN_DATO never enters their values. */ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { if (m.total === null || m.total === 0) return { data: [], layout: {} }; const p = c2Theme(tema); const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0); const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0); const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total; const rotulos = (values: number[], labels: string[], pct: boolean) => { const total = values.reduce((s, n) => s + n, 0); return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `
${shareText(v, total)}` : '')); }; const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text', insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' }; // A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead. const hover = { hovertemplate: '%{label}
%{hovertext}' }; const hoverText = (values: number[]) => values.map(n => `${miles(n)} pacientes, ${percentNumber(100 * n / m.total!)} % del total con resultado`); return { data: [ { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, text: [`${miles(centro)}
${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text }, marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '' }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false), textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior), marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true), textfont: { size: 11 }, hovertext: hoverText(exterior), marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, ], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } /** Selection never changes the original denominator or renormalizes a subset. */ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const p = c2Theme(tema); const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id); const y = m.escenarios.map(s => escapar(s.etiqueta)); const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0)); // Every category keeps its trace (same uid and count) so a selection animates; // an unselected category is a zero-width bar without text or hover, never data. return { data: m.categorias.map(c => { const visible = visibles.includes(c.id); const x = m.escenarios.map(s => { const value = porcentaje(s, c.id); return value === null ? null : visible ? value : 0; }); return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x, marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } }, text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [], ...(visible ? { hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` } : { hoverinfo: 'skip' }) }; }), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false, yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true }, xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid, range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112], tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] }, annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false, font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' : sel.grupo || sel.categoria ? `${percentNumber(sumas[i]!)} % (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})` : miles(s.den) })), }, config: { displayModeBar: false } }; }