247 lines
17 KiB
TypeScript
247 lines
17 KiB
TypeScript
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
|
import { c2Theme } 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<string, Celda>;
|
|
den: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible';
|
|
}
|
|
export interface Modelo {
|
|
periodo: string; categorias: Categoria[]; grupos: Grupo[];
|
|
celdas: Record<string, Celda>; 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<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
const escapar = (v: string) => v.replace(/&/g, '&').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<string, unknown>): 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 promedio(colores: string[]): string {
|
|
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
|
.toString(16).padStart(2, '0')).join('');
|
|
}
|
|
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<string, string>;
|
|
const otrosNombres = porEscenario['grupos_de_categoria'] as Record<string, string>;
|
|
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<string, number>();
|
|
const indexar = (d: IndicadorDatos, estratificado: boolean) => {
|
|
const index = new Map<string, Record<string, unknown>>();
|
|
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);
|
|
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
|
|
.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 categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
|
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id],
|
|
color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) }));
|
|
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<string, unknown>[] | 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 };
|
|
});
|
|
// 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) 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,
|
|
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 ? `<br>${shareText(v, total)}` : ''));
|
|
};
|
|
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
|
|
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
|
|
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
|
|
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
|
|
return { data: [
|
|
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
|
|
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
|
|
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
|
{ ...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' }, customdata: custom(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 }, customdata: custom(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}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }
|
|
: { 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 ? `<b>${percentNumber(sumas[i]!)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
|
|
: miles(s.den) })),
|
|
}, config: { displayModeBar: false } };
|
|
}
|