ce2e86c045
El resumen ya no repite el porcentaje publicado; pacientes y mastografías se leen en su propia gráfica. Co-authored-by: Cursor <cursoragent@cursor.com>
200 lines
14 KiB
TypeScript
200 lines
14 KiB
TypeScript
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
|
import { c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
|
|
import { percentNumber } from './indicadores-format';
|
|
|
|
// Two C2 indicators of the same finding: the exams by BI-RADS category and the patients by their most severe one.
|
|
//
|
|
// What the kit publishes (indicadores_kit, cama/familias/birads, version 0.2.0 of both):
|
|
// - exams: each exam counts once, in its own category;
|
|
// - patients: each patient counts once per period, in the category of the most severe exam of that period,
|
|
// so the patient categories are mutually exclusive and their sum is a number of different patients.
|
|
// Adding categories inside one indicator is therefore a count of the same unit. What is not allowed is mixing
|
|
// the two: the exams of a category include those of patients whose most severe exam is another category, so
|
|
// no ratio of exams to patients is computed, and patients are never derived from exams.
|
|
export interface GrupoConteo { id: string; etiqueta: string; categorias: readonly string[]; }
|
|
export interface ParConteos {
|
|
dominio: Dominio;
|
|
examenes: string;
|
|
pacientes: string;
|
|
// Exam categories in severity order, as the donut draws them.
|
|
categoriasExamen: readonly string[];
|
|
// Rows of the bars: a BI-RADS family and the categories of both indicators that add up to it.
|
|
grupos: readonly GrupoConteo[];
|
|
// Versions of the patient indicator whose definition was checked as above; another version is not added up.
|
|
versionesPacientes: readonly string[];
|
|
unidades: { examenes: string; pacientes: string };
|
|
}
|
|
export const PARES_CONTEOS: readonly ParConteos[] = [
|
|
{ dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente',
|
|
categoriasExamen: ['B4', 'B4A', 'B4B', 'B4C', 'B5', 'B6'],
|
|
grupos: [
|
|
{ id: 'BIRADS_4', etiqueta: 'BI-RADS 4', categorias: ['B4', 'B4A', 'B4B', 'B4C'] },
|
|
{ id: 'BIRADS_5', etiqueta: 'BI-RADS 5', categorias: ['B5'] },
|
|
{ id: 'BIRADS_6', etiqueta: 'BI-RADS 6', categorias: ['B6'] },
|
|
],
|
|
versionesPacientes: ['0.2.0'],
|
|
unidades: { examenes: 'mastografías', pacientes: 'pacientes' } },
|
|
];
|
|
// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own.
|
|
export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id);
|
|
export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) =>
|
|
PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes));
|
|
|
|
// The kit publishes a 4 without subcategory as «B4», with no colour.
|
|
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
|
|
// The categories a response lists only when some unit falls in them: a period set without any has none, not an unknown.
|
|
const OPCIONALES: ReadonlySet<string> = new Set(Object.keys(ETIQUETA_RESPALDO));
|
|
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
|
|
const COLOR_NEUTRO = '#8A9199';
|
|
|
|
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
|
|
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
|
export interface ModeloConteos {
|
|
periodo: string; examenes: CategoriaConteo[]; pacientes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[];
|
|
// False when the patients' version is not one whose definition was checked: their cells stay unknown.
|
|
pacientesVerificados: boolean; notas: string[];
|
|
}
|
|
export class ConteosIncompatibles extends Error {}
|
|
|
|
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
const fail = (message: string): never => { throw new ConteosIncompatibles(message); };
|
|
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
const miles = (v: number) => v.toLocaleString('es-MX');
|
|
// A suppressed, unpublished or invalid cell is unknown, never zero.
|
|
function cuenta(filas: Record<string, unknown>[], periodo: string, categoria: string): number | null {
|
|
const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria && f['grupo'] === 'TOTAL' && (f['estrato'] ?? null) === null);
|
|
return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null;
|
|
}
|
|
const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce<number>((s, v) => s + v!, 0);
|
|
|
|
/** One model per period both responses publish, in chronological order. */
|
|
export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] {
|
|
for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) {
|
|
if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) {
|
|
fail('Los datos no corresponden a los conteos por mastografía y por paciente.');
|
|
}
|
|
}
|
|
if (examenes['unidad'] !== 'examen' || pacientes['unidad'] !== 'paciente') fail('Las unidades publicadas no son mastografías y pacientes.');
|
|
const catExamenes = examenes['categorias'] as Record<string, unknown>, catPacientes = pacientes['categorias'] as Record<string, unknown>;
|
|
const etiqueta = (cat: Record<string, unknown>, id: string) => {
|
|
const publicada = registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : '';
|
|
return publicada && publicada !== id ? publicada : ETIQUETA_RESPALDO[id] ?? id;
|
|
};
|
|
const color = (id: string, index: number) => {
|
|
const publicado = registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
|
|
return c2Color(publicado, index, tonoDe(id));
|
|
};
|
|
const todas = par.grupos.flatMap(g => g.categorias);
|
|
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|
|
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
|
|
fail('Las categorías de mastografías y pacientes no coinciden.');
|
|
}
|
|
const verificados = par.versionesPacientes.includes(String(pacientes['version'] ?? ''));
|
|
const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort();
|
|
const filasE = examenes.filas as Record<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
|
|
const de = (filas: Record<string, unknown>[], cat: Record<string, unknown>, periodo: string, id: string) =>
|
|
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
|
|
return periodos.map(periodo => ({
|
|
periodo,
|
|
examenes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id, index), n: de(filasE, catExamenes, periodo, id) })),
|
|
// The same published cells the family rows add up, kept by category for the patients' donut.
|
|
pacientes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catPacientes, id), color: color(id, index), n: verificados ? de(filasP, catPacientes, periodo, id) : null })),
|
|
// Only the exams the response reports apart; an indicator that lists no such category has none.
|
|
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
|
filas: par.grupos.map(g => ({
|
|
id: g.id, etiqueta: g.etiqueta,
|
|
pacientes: verificados ? sumar(g.categorias.map(id => de(filasP, catPacientes, periodo, id))) : null,
|
|
examenes: sumar(g.categorias.map(id => de(filasE, catExamenes, periodo, id))),
|
|
})),
|
|
pacientesVerificados: verificados,
|
|
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
|
|
}));
|
|
}
|
|
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
|
|
export const totalPacientes = (m: ModeloConteos) => m.pacientesVerificados ? sumar(m.pacientes.map(c => c.n)) : null;
|
|
|
|
const ALTO_DONA = 400, MARGEN_DONA = 8;
|
|
const DIAMETRO_MAXIMO_DONA = 270;
|
|
|
|
function donaDe(categorias: CategoriaConteo[], unidad: string, tema: Tema, ancho: number): PlotlyFigure {
|
|
const total = sumar(categorias.map(c => c.n));
|
|
if (!total) return { data: [], layout: {} };
|
|
const p = c2Theme(tema), n = categorias.map(c => c.n!);
|
|
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines.
|
|
const margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
|
|
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
|
|
const radio = diametro / 2;
|
|
const fraccionVertical = radio / (ALTO_DONA - 2 * MARGEN_DONA);
|
|
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
|
|
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
|
|
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
|
|
const etiquetas = categorias.map(c => escapar(c.etiqueta));
|
|
const porcentajes = n.map(v => percentNumber(100 * v / total));
|
|
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
|
|
// The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
|
|
// so even several adjacent slivers get separate labels and their guide lines keep the same order.
|
|
let acumulado = 0;
|
|
const puntos = n.flatMap((valor, i) => {
|
|
const angulo = 2 * Math.PI * (acumulado + valor / 2) / total;
|
|
acumulado += valor;
|
|
if (!valor) return [];
|
|
const x = radio * Math.sin(angulo), y = radio * Math.cos(angulo);
|
|
return [{ i, x, y }];
|
|
});
|
|
const llamadas = [-1, 1].flatMap(lado => {
|
|
const columna = puntos.filter(punto => (punto.x < 0 ? -1 : 1) === lado).sort((a, b) => b.y - a.y);
|
|
return columna.map(({ i, x, y }, fila) => {
|
|
const altura = (columna.length - 1 - 2 * fila) * 24;
|
|
const texto = etiquetas[i].replace(' (sin subcategoría)', '<br>(sin<br>subcategoría)');
|
|
return {
|
|
annotation: { ...centro, xshift: lado * (radio + 10), yshift: altura,
|
|
xanchor: lado < 0 ? 'right' : 'left', align: lado < 0 ? 'right' : 'left',
|
|
font: { size: fuenteEtiqueta, color: p.text }, text: texto + '<br>' + porcentajes[i] + ' %' },
|
|
shape: { type: 'path', xref: 'paper', yref: 'paper', xsizemode: 'pixel', ysizemode: 'pixel',
|
|
xanchor: .5, yanchor: .5, line: { color: p.text, width: 1 },
|
|
path: 'M ' + Math.round(x) + ',' + Math.round(y) + ' L ' + lado * (radio + 3) + ',' + y + ' L ' + lado * (radio + 8) + ',' + altura },
|
|
};
|
|
});
|
|
});
|
|
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
|
|
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
|
|
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
|
|
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
|
|
hovertemplate: '%{value}<extra></extra>' }],
|
|
layout: { autosize: true, height: ALTO_DONA, showlegend: false, paper_bgcolor: p.background, font: { color: p.text },
|
|
margin: { t: MARGEN_DONA, b: MARGEN_DONA, l: MARGEN_DONA, r: MARGEN_DONA },
|
|
shapes: llamadas.map(({ shape }) => shape),
|
|
annotations: [
|
|
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
|
|
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: unidad },
|
|
...llamadas.map(({ annotation }) => annotation),
|
|
] }, config: { displayModeBar: false } };
|
|
}
|
|
|
|
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
|
return donaDe(m.examenes, par.unidades.examenes, tema, ancho);
|
|
}
|
|
|
|
/** Patients in the most severe BI-RADS category of the period. Same slices as the exams' donut; no ratio. */
|
|
export function donaPacientes(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
|
return donaDe(m.pacientes, par.unidades.pacientes, tema, ancho);
|
|
}
|
|
|
|
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
|
|
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
|
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
|
|
const nombres = { pacientes: `${par.unidades.pacientes} (su categoría más alta)`, examenes: par.unidades.examenes };
|
|
const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') =>
|
|
v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato';
|
|
const traza = (clave: 'pacientes' | 'examenes', color: string) => ({
|
|
type: 'bar', orientation: 'h', name: nombres[clave], y, x: m.filas.map(f => f[clave]), marker: { color },
|
|
text: m.filas.map(f => textoDe(f[clave], clave)), textposition: 'outside', cliponaxis: false,
|
|
hovertemplate: `%{y}: %{x} ${nombres[clave]}<extra></extra>` });
|
|
const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0));
|
|
return { data: [traza('pacientes', '#7A8794'), traza('examenes', '#C26A2B')],
|
|
layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
|
margin: { t: 16, l: 96, r: 70, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false },
|
|
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
|
xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true } }, config: { displayModeBar: false } };
|
|
}
|