Files
WebApp/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts
T
2026-11-26 12:49:10 -06:00

164 lines
9.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { COLUMNAS_DE_PROBABILIDAD, ProbabilidadClave } from '../cacu-seguimiento.models';
import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models';
import { tieneIntervalo } from './paciente-riesgo.validation';
/** How the record names an outcome in its columns, curves and sentence. */
export function etiquetaDesenlace(lote: LoteRiesgoCacu): string {
if (lote.desenlace.startsWith('cin2')) return 'LIEAG+';
if (lote.desenlace === 'cancer') return 'cáncer';
if (lote.desenlace === 'muerte') return lote.estimando?.complement === 'supervivencia' ? 'supervivencia' : 'muerte';
return lote.desenlace_texto ?? lote.desenlace;
}
/** A column's header: "Probabilidad a LIEAG+", "Probabilidad a cáncer"; with its own index date when it isn't
* `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */
export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string {
const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : '';
const etiqueta = etiquetaDesenlace(lote);
return `${etiqueta === 'supervivencia' ? 'Probabilidad de supervivencia' : `Probabilidad a ${etiqueta}`}${desde}`;
}
/** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8",
* 0.015 -> "1.5", 0.00123 -> "0.123", 0.34 -> "34". */
export function porcentaje(p: number): string {
const v = p * 100;
const decimales = v === 0 ? 0 : v < 1 ? 3 : v < 10 ? 2 : 1;
const texto = v.toFixed(decimales);
return texto.includes('.') ? texto.replace(/\.?0+$/, '') : texto;
}
/** The risk with its interval in parentheses, as the table and the sentence write it. */
export function conIntervalo(h: HorizonteRiesgoCacu): string {
const punto = `${porcentaje(h.probabilidad)} %`;
return tieneIntervalo(h) ? `${punto} (${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %)` : `${punto} (IC no disponible)`;
}
/** One point of a risk timeline: a horizon with the model's probability and interval, written as the table writes them. */
export interface NodoRiesgo {
horizonte_anios: number;
/** "Fecha índice" for the immediate risk (horizon 0), else "1 año", "3 años"... */
etiqueta: string;
probabilidad: string;
/** "a – b %", or "IC no disponible" when the model gives no interval. */
intervalo: string;
}
/** The points of one column's timeline, in horizon order: only the horizons its model gives, no interpolation. */
export function nodosRiesgo(lote: LoteRiesgoCacu): NodoRiesgo[] {
const unidad = lote.estimando?.horizons_unit ?? 'años';
return [...lote.horizontes].sort((a, b) => a.horizonte_anios - b.horizonte_anios).map(h => ({
horizonte_anios: h.horizonte_anios,
etiqueta: h.horizonte_anios === 0 ? 'Fecha índice' : `${h.horizonte_anios} ${unidad === 'años' && h.horizonte_anios === 1 ? 'año' : unidad}`,
probabilidad: `${porcentaje(h.probabilidad)} %`,
intervalo: tieneIntervalo(h) ? `${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %` : 'IC no disponible',
}));
}
/** The outcomes a domain's record always has a column for, even with no model: CaCu's CIN2+ and cancer. */
const COLUMNAS_FIJAS: Record<string, { desenlace: string; etiqueta: string }[]> = {
cacu: [{ desenlace: 'cin2', etiqueta: 'LIEAG+' }, { desenlace: 'cancer', etiqueta: 'cáncer' }],
};
const esDe = (lote: LoteRiesgoCacu, desenlace: string) =>
desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace;
/** The outcomes the record shows for each follow-up status, the same as the follow-up table's columns: a case
* already has the disease, so only her survival; a patient before colposcopy, LIEAG+ and cancer; after it, LIEAG+. */
const DESENLACE_DE_LA_COLUMNA: Record<ProbabilidadClave, string> = { lieag: 'cin2', cancer: 'cancer', supervivencia: 'muerte' };
export function desenlacesDelEstatus(estatus: string | null | undefined): string[] | null {
const columnas = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] : undefined;
return columnas ? columnas.map(c => DESENLACE_DE_LA_COLUMNA[c]) : null;
}
/** The risks of the outcomes her follow-up status shows; all of them when the status names none. */
export function delEstatus(riesgos: LoteRiesgoCacu[], estatus: string | null | undefined): LoteRiesgoCacu[] {
const desenlaces = desenlacesDelEstatus(estatus);
return desenlaces ? riesgos.filter(r => desenlaces.some(d => esDe(r, d))) : riesgos;
}
export interface ColumnaRiesgo {
encabezado: string;
/** Its model's risks; `null` when no model of the outcome is current. */
lote: LoteRiesgoCacu | null;
/** What the cells say when there's no risk: no model, or a model that doesn't estimate her. */
vacia: string | null;
}
/** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any
* other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */
export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu', estatus: string | null = null): ColumnaRiesgo[] {
riesgos = delEstatus(riesgos, estatus);
const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null;
const desenlaces = desenlacesDelEstatus(estatus);
const fijas = (COLUMNAS_FIJAS[dominio] ?? []).filter(f => !desenlaces || desenlaces.includes(f.desenlace));
const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => {
const lote = riesgos.find(r => esDe(r, desenlace)) ?? null;
if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' };
return { encabezado: encabezado(lote, fecha), lote,
vacia: lote.horizontes.length ? null : 'No estimada para su grupo' };
});
for (const lote of riesgos) {
if (fijas.some(f => esDe(lote, f.desenlace)) || !lote.horizontes.length) continue;
columnas.push({ encabezado: encabezado(lote, fecha), lote, vacia: null });
}
return columnas;
}
/** The risks the record can draw and describe: the ones with horizons. */
export const conRiesgo = (riesgos: LoteRiesgoCacu[]) => riesgos.filter(r => r.horizontes.length);
export interface FilaRiesgo {
horizonte_anios: number;
/** One cell per column, in their order; `null` where that column has no risk at this horizon. */
celdas: (HorizonteRiesgoCacu | null)[];
}
/** The table's rows: every horizon any of the columns has, ascending, with each column's risk there. */
export function filasRiesgo(lotes: (LoteRiesgoCacu | null)[]): FilaRiesgo[] {
const horizontes = [...new Set(lotes.flatMap(r => r?.horizontes.map(h => h.horizonte_anios) ?? []))]
.sort((a, b) => a - b);
return horizontes.map(horizonte_anios => ({
horizonte_anios,
celdas: lotes.map(r => r?.horizontes.find(h => h.horizonte_anios === horizonte_anios) ?? null),
}));
}
function resultado(r: ResultadosIndice | null): string | null {
if (!r) return null;
const vph = r.vph === 'POSITIVO' ? 'VPH positivo' : r.vph === 'NEGATIVO' ? 'VPH negativo'
: r.vph ? `VPH ${r.vph.toLowerCase()}` : 'sin resultado de VPH';
const citologia = [r.escamosas, r.glandulares].filter(Boolean).join(' con ');
return `Un resultado de ${vph} y una citología ${citologia || 'sin resultado'}`;
}
/**
* The sentence over the curves: the index results and, at the longest horizon the outcomes of the first one's index
* date share, each outcome's
* cumulative risk of being present at the index visit or developing afterwards, "respectivamente" when there are
* several. `null` without the index results.
*/
export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null {
const scored = conRiesgo(todos);
const riesgos = scored.filter(r => r.fecha_indice === scored[0]?.fecha_indice); // the outcomes of the same visit
const inicio = resultado(riesgos.find(r => r.resultados_indice)?.resultados_indice ?? null);
if (!inicio) return null;
const comunes = filasRiesgo(riesgos).filter(f => f.celdas.every(c => c !== null));
const ultima = comunes[comunes.length - 1];
if (!ultima) return null;
const fecha = riesgos[0].fecha_indice;
const junta = (xs: string[]) => xs.length > 1 ? `${xs.slice(0, -1).join(', ')} y ${xs[xs.length - 1]}` : xs[0];
const desenlaces = junta(riesgos.map(etiquetaDesenlace));
const valores = junta(ultima.celdas.map(c => conIntervalo(c!)));
const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`;
return `${inicio} (${fecha}) tienen una probabilidad a ${anios} de estar presente o de aparecer ${desenlaces} `
+ `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`;
}
/** The covariates under the table: each model's, by its column, or once when every model uses the same ones. */
export function covariables(riesgos: LoteRiesgoCacu[]): string | null {
const con = riesgos.filter(r => r.estimando?.covariates);
if (!con.length) return null;
const textos = [...new Set(con.map(r => r.estimando!.covariates!))];
if (textos.length === 1) return `Covariables: ${textos[0]}.`;
return `Covariables: ${con.map(r => `${encabezado(r)}: ${r.estimando!.covariates}`).join('; ')}.`;
}