e1a8127c22
Horizontal bars of the days from the sample to each event of the route (cytology result, colposcopy, biopsy result and diagnosis), cumulative with the Q1 to Q3 interval or step by step with each step starting where the previous one ends. It reads the seven duration measures of the route and shows up in CaCu's page once the catalog publishes all of them; the measures only it draws get no card of their own.
121 lines
6.9 KiB
TypeScript
121 lines
6.9 KiB
TypeScript
import { Dominio, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
|
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
|
|
|
// Two C3r indicators that share the sample date (toma) and differ in their end
|
|
// event: the lab result and the diagnosis note. They are drawn side by side per
|
|
// period so the slower stretch is visible. C3r publishes only Q1, median and Q3:
|
|
// no individual observations, so boxes have no whiskers and no violin is possible.
|
|
export interface ParTiempos {
|
|
dominio: Dominio;
|
|
reporte: string;
|
|
diagnostico: string;
|
|
estudios: string;
|
|
etiquetas: { reporte: string; diagnostico: string };
|
|
// Only connected pairs replace the diagnosis card in the catalog.
|
|
conectado: boolean;
|
|
}
|
|
export const PARES_TIEMPOS: readonly ParTiempos[] = [
|
|
{ dominio: 'cacu', reporte: 'cacu_eu_tiempo_reporte', diagnostico: 'cacu_dias_toma_diagnostico', estudios: 'citologías',
|
|
etiquetas: { reporte: 'Días de toma a resultado (laboratorio)', diagnostico: 'Días de toma a diagnóstico' }, conectado: true },
|
|
{ dominio: 'cama', reporte: 'cama_eu38a', diagnostico: 'cama_dias_toma_diagnostico', estudios: 'mastografías',
|
|
etiquetas: { reporte: 'Días de toma a resultado', diagnostico: 'Días de toma a diagnóstico' }, conectado: false },
|
|
];
|
|
export function parTiempos(dominio: Dominio, id: string): ParTiempos | undefined {
|
|
return PARES_TIEMPOS.find(par => par.conectado && par.dominio === dominio && par.diagnostico === id);
|
|
}
|
|
export const FIGURA_C3R = 'fig_c3r_caja';
|
|
|
|
export type Clave = 'reporte' | 'diagnostico';
|
|
export const CLAVES: readonly Clave[] = ['reporte', 'diagnostico'];
|
|
export interface Caja {
|
|
estado: 'Publicado' | 'Suprimido' | 'No disponible';
|
|
n?: number; q1?: number; mediana?: number; q3?: number;
|
|
}
|
|
export interface ModeloTiempos { periodos: string[]; cajas: Record<Clave, Record<string, Caja>>; notas: string[]; }
|
|
export class TiemposIncompatibles extends Error {}
|
|
|
|
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
|
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
|
|
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
|
|
|
|
export function caja(fila: Record<string, unknown> | undefined): Caja {
|
|
if (!fila) return { estado: 'No disponible' };
|
|
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
|
|
const { n, q1, mediana, q3 } = fila;
|
|
// Null quantiles are not zeros: without a complete published box nothing is drawn.
|
|
if (fila['suprimido'] !== 0 || !conteo(n) || n === 0 || !finito(q1) || !finito(mediana) || !finito(q3)
|
|
|| q1 < 0 || q1 > mediana || mediana > q3) return { estado: 'No disponible' };
|
|
return { estado: 'Publicado', n, q1, mediana, q3 };
|
|
}
|
|
|
|
/** Two immutable C3r /datos payloads -> boxes per period, without mixing groups or strata. */
|
|
export function modeloTiempos(par: ParTiempos, datos: Record<Clave, IndicadorDatos>, tipo: TipoPeriodo,
|
|
solicitados?: readonly string[]): ModeloTiempos {
|
|
const cajas = { reporte: {}, diagnostico: {} } as Record<Clave, Record<string, Caja>>;
|
|
for (const clave of CLAVES) {
|
|
const d = datos[clave];
|
|
if (d.id !== par[clave] || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
|
|| new Set(d.periodos).size !== d.periodos.length
|
|
|| (solicitados && d.periodos.some(p => !solicitados.includes(p)))) {
|
|
fail('Los datos de tiempos no corresponden al indicador o al periodo aplicado.');
|
|
}
|
|
for (const fila of d.filas) {
|
|
if (!registro(fila) || typeof fila['periodo'] !== 'string' || !d.periodos.includes(fila['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
|
|
if (fila['grupo'] !== 'TOTAL' || fila['estrato'] != null) continue;
|
|
if (fila['unidad'] !== undefined && fila['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
|
|
const periodo = fila['periodo'] as string;
|
|
if (cajas[clave][periodo]) fail('Más de una fila total por periodo.');
|
|
cajas[clave][periodo] = caja(fila);
|
|
}
|
|
for (const periodo of d.periodos) cajas[clave][periodo] ??= { estado: 'No disponible' };
|
|
}
|
|
const periodos = solicitados ? [...solicitados]
|
|
: [...new Set([...datos.reporte.periodos, ...datos.diagnostico.periodos])].sort();
|
|
for (const clave of CLAVES) for (const periodo of periodos) cajas[clave][periodo] ??= { estado: 'No disponible' };
|
|
return { periodos, cajas, notas: [...new Set([...(datos.reporte.notas ?? []), ...(datos.diagnostico.notas ?? [])])] };
|
|
}
|
|
|
|
export function hayCajas(m: ModeloTiempos): boolean {
|
|
return CLAVES.some(clave => m.periodos.some(p => m.cajas[clave][p].estado === 'Publicado'));
|
|
}
|
|
|
|
const COLORES: Record<Clave, string> = { reporte: C2_PALETTE.series[0], diagnostico: C2_PALETTE.series[2] };
|
|
function rgba(hex: string, alfa: number): string {
|
|
const v = parseInt(hex.slice(1), 16);
|
|
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
|
}
|
|
const dias = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
|
|
|
|
/** Grouped boxes from published quartiles; whiskers equal the box (fences are unknown). */
|
|
export function figuraTiempos(m: ModeloTiempos, par: ParTiempos, tema: Tema): PlotlyFigure {
|
|
const p = c2Theme(tema);
|
|
const data = CLAVES.map(clave => {
|
|
const periodos = m.periodos.filter(periodo => m.cajas[clave][periodo].estado === 'Publicado');
|
|
const cajas = periodos.map(periodo => m.cajas[clave][periodo]);
|
|
return {
|
|
type: 'box', name: par.etiquetas[clave], legendgroup: clave, x: periodos,
|
|
q1: cajas.map(c => c.q1), median: cajas.map(c => c.mediana), q3: cajas.map(c => c.q3),
|
|
lowerfence: cajas.map(c => c.q1), upperfence: cajas.map(c => c.q3),
|
|
marker: { color: COLORES[clave] }, line: { color: COLORES[clave], width: 2 }, fillcolor: rgba(COLORES[clave], .35),
|
|
customdata: cajas.map(c => [c.n!.toLocaleString('es-MX'), dias(c.q1!), dias(c.mediana!), dias(c.q3!)]),
|
|
hoveron: 'boxes',
|
|
hovertemplate: `${par.etiquetas[clave]}<br>%{x}<br>n = %{customdata[0]} ${par.estudios}`
|
|
+ '<br>Q1: %{customdata[1]} días<br>Mediana: %{customdata[2]} días<br>Q3: %{customdata[3]} días<extra></extra>',
|
|
};
|
|
});
|
|
return { data, layout: {
|
|
boxmode: 'group', autosize: true, height: 440, showlegend: true,
|
|
legend: { orientation: 'h', x: 0, y: 1.02, xanchor: 'left', yanchor: 'bottom' },
|
|
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
|
margin: { t: 48, l: 64, r: 16, b: 56 },
|
|
xaxis: { type: 'category', categoryorder: 'array', categoryarray: m.periodos, title: { text: 'Periodo' } },
|
|
yaxis: { title: { text: 'días' }, rangemode: 'tozero', gridcolor: p.grid, zeroline: false },
|
|
}, config: { displayModeBar: false } };
|
|
}
|
|
|
|
export function cajaTexto(c: Caja): string {
|
|
return c.estado !== 'Publicado' ? c.estado
|
|
: `n = ${c.n!.toLocaleString('es-MX')}, Q1 ${dias(c.q1!)}, mediana ${dias(c.mediana!)}, Q3 ${dias(c.q3!)} días`;
|
|
}
|