Files
WebApp/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts
T
edgar 73b88de0ca Patient risk: a column per outcome, the index visit's sentence, and the model's details folded
The record reads every RiskAssessment of the patient. CaCu's table always has the LIEAG+ and cancer columns, each
risk with its interval in parentheses; a column with no current model says "No disponible", and one whose model
didn't estimate her says so, with the reason under the table. Another outcome (a survival model's death) shows only
when she has its risk, with its own index date in its header. The models' details fold under the table, without the
interval's method; the collapsible curves draw one line per outcome with the index date on the x axis, under a
sentence that words the index cytology's results and each outcome's risk at the longest common horizon.
2026-11-22 09:35:01 -06:00

116 lines
6.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 { 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 '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}` : '';
return `Probabilidad a ${etiquetaDesenlace(lote)}${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)`;
}
/** 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;
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'): ColumnaRiesgo[] {
const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null;
const fijas = COLUMNAS_FIJAS[dominio] ?? [];
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 un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} `
+ `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`;
}