From 73b88de0caf91a64c457eec0d2ac35a3591c64bc Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 09:35:01 -0600 Subject: [PATCH] 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. --- .../paciente-riesgo-estimando.spec.ts | 78 ++++++++++-- .../paciente-riesgo-figura.ts | 76 +++++++----- .../paciente-riesgo-tabla.html | 101 ++++++++------- .../paciente-riesgo-tabla.scss | 5 + .../paciente-detalle/paciente-riesgo-tabla.ts | 19 ++- .../paciente-riesgo.models.ts | 18 ++- .../paciente-riesgo.presentacion.ts | 115 ++++++++++++++++++ .../paciente-detalle/paciente-riesgo.spec.ts | 5 +- .../paciente-riesgo.testing.ts | 53 +++++++- .../paciente-riesgo.validation.ts | 69 ++++++++--- 10 files changed, 429 insertions(+), 110 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts index 30ad7ab..cb6363f 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -4,7 +4,8 @@ import { provideHttpClientTesting } from '@angular/common/http/testing'; import { of } from 'rxjs'; import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; -import { riesgoCacuConEstimando, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; +import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; +import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; @@ -24,10 +25,10 @@ describe('Riesgo individual: qué se estima y su curva', () => { return { fixture, root: fixture.nativeElement as HTMLElement }; } - it('lee el estimando conocido e ignora claves que no conoce; sin extensión queda en null', () => { + it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => { expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({ quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.', - outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', interval: 'IC 95 % por método delta' }); + outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' }); expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista()); }); @@ -40,10 +41,12 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => { const { root } = setup(riesgoCacuConEstimando()); expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) - .toEqual(['Horizonte (años)', 'Riesgo acumulado (%)', 'Intervalo de confianza (%)']); - for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma', 'IC 95 % por método delta']) { + .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); + expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo'); + for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) { expect(root.textContent).toContain(value); } + expect(root.textContent).not.toContain('método delta'); }); it('dibuja la curva solo al abrir su sección', async () => { @@ -59,15 +62,76 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('la figura une los horizontes y pone el intervalo como banda, o como barras si falta en alguno', () => { const riesgo = riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo; - const banda = figuraRiesgoPaciente(riesgo); + const banda = figuraRiesgoPaciente([riesgo]); expect(banda.data).toHaveLength(3); expect(banda.data[2]['y']).toEqual([8, 21, 34]); expect(banda.data[1]['y']).toEqual([5, 15, 26]); expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)'); const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) }; - const barras = figuraRiesgoPaciente(parcial); + const barras = figuraRiesgoPaciente([parcial]); expect(barras.data).toHaveLength(1); expect((barras.data[0]['error_y'] as any).array[0]).toBe(0); }); + + it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => { + const { root } = setup(riesgoCacuDosDesenlaces()); + expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) + .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); + const fila = [...root.querySelectorAll('tbody tr')][2]; + expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim())) + .toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']); + }); + + it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => { + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']); + expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo ' + + 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), ' + + 'respectivamente.'); + expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull(); + }); + + it('dibuja una curva por desenlace, cada una con su banda', () => { + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + const figura = figuraRiesgoPaciente(riesgos); + const lineas = figura.data.filter(t => t['mode'] === 'lines+markers'); + expect(lineas.map(t => t['name'])).toEqual(['LIEAG+', 'cáncer']); + expect((lineas[1]['y'] as number[]).map(v => Math.round(v * 10) / 10)).toEqual([0.4, 0.9, 1.5]); + expect(figura.data.filter(t => t['fill'] === 'tonexty')).toHaveLength(2); + expect((figura.layout['xaxis'] as any).title.text).toBe('Horizonte (años desde la fecha índice (2026-06-01))'); + }); + + it('escribe los porcentajes con los decimales que un riesgo pequeño necesita', () => { + expect([0.34, 0.178, 0.015, 0.004, 0.00123, 0, 0.1, 1].map(porcentaje)) + .toEqual(['34', '17.8', '1.5', '0.4', '0.123', '0', '10', '100']); + expect(conIntervalo({ horizonte_anios: 1, probabilidad: 0.2, ic_bajo: null, ic_alto: null })).toBe('20 % (IC no disponible)'); + }); + + it('un desenlace con otra fecha índice la dice en su columna y queda fuera de la frase', () => { + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' }; + expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01'); + expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) ' + + 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).'); + }); + + it('sin modelo de un desenlace su columna dice No disponible', () => { + const { root } = setup(riesgoCacuConEstimando()); + const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']); + }); + + it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => { + const data = riesgoCacuCancerSinEstimar(); + const { root } = setup(data); + const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']); + expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población'); + const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!; + expect(riesgo.desenlace).toBe('cin2_mas'); + expect(riesgos[1]).toMatchObject({ desenlace: 'cancer', horizontes: [], sin_estimacion: 'queda fuera de su población' }); + expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers')) + .toHaveLength(1); + }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts index 79797e4..78c08ff 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts @@ -1,46 +1,60 @@ import { PlotlyFigure } from '../indicadores.models'; +import { conIntervalo, etiquetaDesenlace } from './paciente-riesgo.presentacion'; import { tieneIntervalo } from './paciente-riesgo.validation'; import { LoteRiesgoCacu } from './paciente-riesgo.models'; -const COLOR = '#6a3d9a'; -const BANDA = 'rgba(106,61,154,.18)'; +/** One color per curve, in the order of the outcomes (CIN2+, cancer, any other). */ +const COLORES = ['#6a3d9a', '#b2182b', '#1f78b4']; +const BANDAS = ['rgba(106,61,154,.18)', 'rgba(178,24,43,.16)', 'rgba(31,120,180,.16)']; /** - * The patient's risk at the model's horizons as a small curve: the points joined by a line, with the interval as a - * band where every horizon has one and as error bars otherwise. In percent; the axis names follow the estimand. + * The patient's risk of each outcome at the model's horizons as small curves on one axis: the points joined by a + * line, with the interval as a band where every horizon has one and as error bars otherwise. In percent; the axis + * names follow the first model's estimand, and the x axis says the index date the horizons count from. */ -export function figuraRiesgoPaciente(riesgo: LoteRiesgoCacu): PlotlyFigure { - const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100); - const cantidad = riesgo.estimando?.quantity ?? 'Probabilidad'; - const unidad = riesgo.estimando?.horizons_unit ?? 'años'; - const conIntervalo = h.map(tieneIntervalo); - const banda = conIntervalo.length > 1 && conIntervalo.every(Boolean); +export function figuraRiesgoPaciente(riesgos: LoteRiesgoCacu[]): PlotlyFigure { const data: Record[] = []; - if (banda) { - data.push( - { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false, hoverinfo: 'skip' }, - { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty', fillcolor: BANDA, line: { width: 0 }, - name: 'Intervalo de confianza', hoverinfo: 'skip' }, - ); - } - const barras = !banda && conIntervalo.some(Boolean) ? { - error_y: { type: 'data', symmetric: false, visible: true, color: COLOR, thickness: 2, width: 6, - array: h.map((p, i) => conIntervalo[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0), - arrayminus: h.map((p, i) => conIntervalo[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) }, - } : {}; - data.push({ - type: 'scatter', mode: 'lines+markers', x, y, name: cantidad, line: { color: COLOR, width: 2 }, - marker: { color: COLOR, size: 9, line: { color: 'white', width: 2 } }, ...barras, - customdata: h.map(p => tieneIntervalo(p) ? `${(p.ic_bajo! * 100).toFixed(2)} % – ${(p.ic_alto! * 100).toFixed(2)} %` : 'sin intervalo'), - hovertemplate: `%{x} ${unidad}: %{y:.2f} %
IC: %{customdata}`, + let maximo = 0; + riesgos.forEach((riesgo, k) => { + const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100); + const color = COLORES[k % COLORES.length], nombre = etiquetaDesenlace(riesgo); + const conIc = h.map(tieneIntervalo); + const banda = conIc.length > 1 && conIc.every(Boolean); + if (banda) { + data.push( + { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false, + hoverinfo: 'skip', legendgroup: nombre }, + { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty', + fillcolor: BANDAS[k % BANDAS.length], line: { width: 0 }, name: `IC 95 % ${nombre}`, hoverinfo: 'skip', + legendgroup: nombre }, + ); + } + const barras = !banda && conIc.some(Boolean) ? { + error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 2, width: 6, + array: h.map((p, i) => conIc[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0), + arrayminus: h.map((p, i) => conIc[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) }, + } : {}; + data.push({ + type: 'scatter', mode: 'lines+markers', x, y, name: nombre, legendgroup: nombre, line: { color, width: 2 }, + marker: { color, size: 9, line: { color: 'white', width: 2 } }, ...barras, + customdata: h.map(conIntervalo), + hovertemplate: `%{x} ${riesgo.estimando?.horizons_unit ?? 'años'}: %{customdata}${nombre}`, + }); + maximo = Math.max(maximo, ...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100)); }); - const maximo = Math.max(...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100)); + const primero = riesgos[0]; + const unidad = primero?.estimando?.horizons_unit ?? 'años'; + const fechas = [...new Set(riesgos.map(r => r.fecha_indice))]; + const desde = fechas.length === 1 ? `la fecha índice (${fechas[0]})` + : `la fecha índice de cada desenlace (${riesgos.map(r => `${etiquetaDesenlace(r)}: ${r.fecha_indice}`).join('; ')})`; return { data, layout: { - margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: banda, legend: { orientation: 'h', y: -0.25 }, - xaxis: { title: { text: `Horizonte (${unidad} desde la fecha índice)` }, tickvals: x, zeroline: false }, - yaxis: { title: { text: `${cantidad} (%)` }, rangemode: 'tozero', range: [0, Math.max(maximo * 1.15, 1)], zeroline: false }, + margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: true, legend: { orientation: 'h', y: -0.25 }, + xaxis: { title: { text: `Horizonte (${unidad} desde ${desde})` }, + tickvals: [...new Set(riesgos.flatMap(r => r.horizontes.map(p => p.horizonte_anios)))], zeroline: false }, + yaxis: { title: { text: `${primero?.estimando?.quantity ?? 'Probabilidad'} (%)` }, rangemode: 'tozero', + range: [0, Math.max(maximo * 1.15, 1)], zeroline: false }, }, }; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 40b2e6a..6cbd5f0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -7,53 +7,66 @@ } @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') { + @let todos = lectura.datos.riesgos; + @let riesgos = conRiesgo(todos); @let riesgo = lectura.datos.riesgo; -
Modelo y evaluación
- - @if (riesgo.horizontes.length) { -
- - - - - - - - - @for (h of riesgo.horizontes; track h.horizonte_anios) { - - - - - - } - -
{{ riesgo.estimando?.quantity ?? 'Probabilidades' }} por horizonte desde la fecha índice
Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ riesgo.estimando?.quantity ?? 'Probabilidad' }} (%)Intervalo de confianza (%)
{{ h.horizonte_anios }}{{ h.probabilidad * 100 | number:'1.0-4' }} %@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }
-
- @if (riesgo.horizontes.length > 1) { -
- Curva de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo - @if (curvaAbierta()) { - + @let columnas = columnasDe(todos); + @let filas = filasDe(lotesDe(columnas)); + @if (filas.length) { +
+ + + + + @for (c of columnas; track c.encabezado) { } + + + @for (f of filas; track f.horizonte_anios) { + + + @for (c of f.celdas; track $index; let i = $index) { + + } + } - + +
{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice + ({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis
Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ c.encabezado }} (%)
{{ f.horizonte_anios }}@if (columnas[i].vacia; as vacia) {{{ vacia }}} @else if (c) {{{ porcentaje(c.probabilidad) }} %{{ ' ' }}@if (tieneIntervalo(c)) {({{ porcentaje(c.ic_bajo!) }} – {{ porcentaje(c.ic_alto!) }} %)} @else {(IC no disponible)}} @else {—}
+
+ @for (c of columnas; track c.encabezado) { + @if (c.lote?.sin_estimacion; as motivo) {

{{ c.encabezado }}: {{ motivo }}.

} + } +
+ Detalle del modelo + @for (r of riesgos; track r.id) { + @if (riesgos.length > 1) {
{{ encabezado(r) }}
} + } - } @else {

Sin horizontes evaluados en el lote vigente.

} +
+ @if (filas.length > 1) { +
+ Curva{{ riesgos.length > 1 ? 's' : '' }} de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo + @if (frase(riesgos); as texto) {

{{ texto }}

} + @if (curvaAbierta()) { + + } +
+ } + } @else {

Sin horizontes evaluados en el lote vigente.

} } }

Recomendaciones no disponibles.

diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss index 99d1396..768e31a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -19,3 +19,8 @@ tbody th, td { background: var(--issste-surface); } tbody tr:last-child > * { border-bottom: 0; } .percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; } .risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; } +.risk-sentence { margin: .25rem 0 .75rem; line-height: 1.5; } +.risk-details { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; } +.risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; } +.unavailable { color: var(--issste-text-secondary); } +.unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 2d4c6d6..1cb53c2 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,8 +1,9 @@ import { Component, computed, effect, inject, input, signal } from '@angular/core'; -import { DecimalPipe, LowerCasePipe } from '@angular/common'; +import { LowerCasePipe } from '@angular/common'; import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; import { PlotlyFigure } from '../indicadores.models'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; +import { ColumnaRiesgo, columnasRiesgo, conRiesgo, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -15,7 +16,7 @@ export const instanteUtc = (iso: string) => { @Component({ selector: 'app-paciente-riesgo-tabla', - imports: [DecimalPipe, LowerCasePipe, PlotlyChart], + imports: [LowerCasePipe, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -32,9 +33,17 @@ export class PacienteRiesgoTabla { readonly instante = instanteUtc; /** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */ readonly curvaAbierta = signal(false); - private figuraDe?: { riesgo: LoteRiesgoCacu; figura: PlotlyFigure }; - figura(riesgo: LoteRiesgoCacu): PlotlyFigure { - if (this.figuraDe?.riesgo !== riesgo) this.figuraDe = { riesgo, figura: figuraRiesgoPaciente(riesgo) }; + readonly porcentaje = porcentaje; + readonly encabezado = encabezado; + readonly etiqueta = etiquetaDesenlace; + readonly frase = fraseRiesgo; + readonly filasDe = filasRiesgo; + readonly conRiesgo = conRiesgo; + columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); } + lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); } + private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure }; + figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure { + if (this.figuraDe?.riesgos !== riesgos) this.figuraDe = { riesgos, figura: figuraRiesgoPaciente(riesgos) }; return this.figuraDe.figura; } constructor() { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index c140a2b..9da4a44 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -23,7 +23,14 @@ export interface EstimandoRiesgo { index_date?: string; /** The unit the horizons are counted in, e.g. "años". */ horizons_unit?: string; - interval?: string; +} + +/** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */ +export interface ResultadosIndice { + escamosas?: string; + glandulares?: string; + /** `POSITIVO`, `NEGATIVO` or `INDETERMINADO`. */ + vph?: string; } /** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/`). */ @@ -42,12 +49,19 @@ export interface LoteRiesgoCacu { horizontes: HorizonteRiesgoCacu[]; /** `null` for a model whose scenario doesn't say. */ estimando: EstimandoRiesgo | null; + /** `null` when no cytology was sampled on the index date (or the domain doesn't give it). */ + resultados_indice: ResultadosIndice | null; + /** Why a current model of this outcome has no risk for her (extension `sin-estimacion`; then `horizontes` is + * empty and `fecha_indice` too); `null` when it scored her. */ + sin_estimacion: string | null; } -/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */ +/** DEV-only: the patient's current `RiskAssessment` of each outcome, from a `searchset` Bundle tagged `simulado`. + * `riesgos` holds them CIN2+ first, then cancer, then any other; `riesgo` is the first. */ export interface RiesgoPacienteCacu { simulado: true; riesgo: LoteRiesgoCacu; + riesgos: LoteRiesgoCacu[]; } /** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */ diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts new file mode 100644 index 0000000..f31c557 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts @@ -0,0 +1,115 @@ +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 = { + 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' : ''}.`; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 2b13303..684d4e0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -44,11 +44,12 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { const baseline = structuredClone(data); const f = setup({ obtener }), root: HTMLElement = f.nativeElement; expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); + // horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval expect(root.querySelectorAll('thead th')).toHaveLength(3); expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); - expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); + expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)'); expect(root.textContent).toContain('Final (final)'); for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain(value); @@ -86,7 +87,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); - expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']); + expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']); expect(root.textContent).toContain('Preliminar (preliminary)'); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index f4332af..c3d0eea 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -1,4 +1,4 @@ -import { RiesgoPacienteCacu } from './paciente-riesgo.models'; +import { LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; const CS = 'https://isssteleon.org/fhir/CodeSystem'; export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; @@ -38,9 +38,7 @@ export function riesgoCacuEjemplo(): any { /** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */ export function riesgoCacuVista(): RiesgoPacienteCacu { - return { - simulado: true, - riesgo: { + const riesgo: LoteRiesgoCacu = { id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01', evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia', horizontes: [ @@ -49,8 +47,10 @@ export function riesgoCacuVista(): RiesgoPacienteCacu { { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }, ], estimando: null, - }, + resultados_indice: null, + sin_estimacion: null, }; + return { simulado: true, riesgo, riesgos: [riesgo] }; } /** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */ @@ -68,3 +68,46 @@ export function riesgoCacuConEstimando(): any { ] }]; return data; } + +export const RESULTADOS_INDICE = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; + +/** TEST ONLY. `riesgoCacuConEstimando()` plus a cancer `RiskAssessment` of the same visit, both with the index + * cytology's results: the Bundle a patient scored by the CIN2+ and the cancer models gets. Cancer comes first, as + * the newer batch would. */ +export function riesgoCacuDosDesenlaces(): any { + const data = riesgoCacuConEstimando(); + const cin2 = data.entry[0].resource; + const resultados = { url: RESULTADOS_INDICE, extension: [ + { url: 'escamosas', valueString: 'LIEBG' }, { url: 'vph', valueString: 'POSITIVO' }] }; + cin2.extension.push(resultados); + const cancer = structuredClone(cin2); + cancer.id = '13-42'; + cancer.method.coding[0].code = 'modelo-cacu-cancer'; + cancer.extension[0].extension = cancer.extension[0].extension.map((e: any) => + e.url === 'outcome' ? { ...e, valueString: 'Cáncer: biopsia de carcinoma' } : e); + cancer.prediction = [ + prediccion(0.004, '2026-06-01', '2027-06-01', [0.002, 0.008]), + prediccion(0.009, '2026-06-01', '2029-06-01', [0.005, 0.016]), + prediccion(0.015, '2026-06-01', '2031-06-01', [0.008, 0.028]), + ].map(p => ({ ...p, outcome: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/desenlace', code: 'cancer', + display: 'Cáncer cervicouterino por biopsia' }] } })); + data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer }); + data.total = 2; + return data; +} + +export const SIN_ESTIMACION = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; + +/** TEST ONLY. `riesgoCacuConEstimando()` plus a current cancer model that didn't score her: a `RiskAssessment` with + * no prediction, marked `sin-estimacion`. */ +export function riesgoCacuCancerSinEstimar(): any { + const data = riesgoCacuConEstimando(); + const cancer = structuredClone(data.entry[0].resource); + cancer.id = '13-42'; + delete cancer.prediction; + cancer.extension = [{ url: SIN_ESTIMACION, extension: [{ url: 'desenlace', valueCode: 'cancer' }, + { url: 'motivo', valueString: 'queda fuera de su población' }] }]; + data.entry.push({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer }); + data.total = 2; + return data; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index 446263c..932bf4b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -1,5 +1,5 @@ import { isoDate } from '../cacu-seguimiento.models'; -import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; +import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice, RiesgoPacienteCacu } from './paciente-riesgo.models'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); @@ -10,7 +10,10 @@ const DAYS_PER_YEAR = 365.25; const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; const SIMULATED = 'simulado'; const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; -const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'interval']; +const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; +const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; +const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph']; +const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit']; function utcTimestamp(v: unknown): v is string { return typeof v === 'string' @@ -41,23 +44,40 @@ function interval(prediction: Record): { ic_bajo: number | null return { ic_bajo: low, ic_alto: high }; } -/** The resource's `estimando` extension: its known keys with a text value; `null` without one. */ -function estimand(resource: Record): EstimandoRiesgo | null { +/** The resource's extension `url` as its known `keys` with a text value; `null` without that extension. */ +function stringExtension(resource: Record, url: string, + keys: readonly K[]): Partial> | null { const extensions = resource['extension']; if (extensions === undefined) return null; if (!Array.isArray(extensions)) invalid(); - const found = extensions.find(e => record(e) && e['url'] === ESTIMAND); + const found = extensions.find(e => record(e) && e['url'] === url); if (found === undefined) return null; if (!Array.isArray(found['extension'])) invalid(); - const result: EstimandoRiesgo = {}; + const result: Partial> = {}; for (const item of found['extension']) { if (!record(item) || !text(item['url'])) invalid(); - const key = item['url'] as keyof EstimandoRiesgo; - if (ESTIMAND_KEYS.includes(key) && text(item['valueString'])) result[key] = item['valueString']; + const key = item['url'] as K; + if (keys.includes(key) && text(item['valueString'])) result[key] = item['valueString']; } return result; } +const estimand = (resource: Record): EstimandoRiesgo | null => + stringExtension(resource, ESTIMAND, ESTIMAND_KEYS); + +/** The `sin-estimacion` extension: the outcome of a current model that didn't score her, and why; `null` without it. */ +function notScoredOutcome(resource: Record): { desenlace: string; motivo: string } | null { + const extensions = resource['extension']; + if (!Array.isArray(extensions)) return null; + const found = extensions.find(e => record(e) && e['url'] === NOT_SCORED); + if (found === undefined) return null; + const items = Array.isArray(found['extension']) ? found['extension'].filter(record) : invalid(); + const desenlace = items.find(i => i['url'] === 'desenlace')?.['valueCode']; + const motivo = items.find(i => i['url'] === 'motivo')?.['valueString']; + if (!text(desenlace)) invalid(); + return { desenlace, motivo: text(motivo) ? motivo : 'el modelo no estima a esta paciente' }; +} + function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } { if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid(); const period = prediction['whenPeriod']; @@ -81,6 +101,15 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu { const method = v['method']; const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined; if (!record(model) || !text(model['code']) || !text(model['version'])) invalid(); + const notScored = notScoredOutcome(v); + if (notScored !== null && v['prediction'] === undefined) { + return { + id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, + fecha_indice: '', evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', + desenlace: notScored.desenlace, desenlace_texto: null, horizontes: [], estimando: estimand(v), + resultados_indice: null, sin_estimacion: notScored.motivo, + }; + } const predictions = v['prediction']; if (!Array.isArray(predictions) || predictions.length === 0) invalid(); let start: string | undefined; @@ -99,7 +128,8 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu { id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null, - horizontes, estimando: estimand(v), + horizontes, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS), + sin_estimacion: null, }; } @@ -108,16 +138,27 @@ function simulated(resource: Record): boolean { return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); } -/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only). - * `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */ +/** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */ +export function ordenDesenlace(desenlace: string): number { + return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2; +} + +/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`s, one per outcome, each tagged + * `simulado` (DEV only), and one with no prediction for a current model that didn't score her. `riesgo` is the first + * that has a risk. `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and + * malformed fields. */ export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null { if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid(); const entries = v['entry'] ?? []; if (!Array.isArray(entries)) invalid(); if (entries.length === 0) return null; - const resource = record(entries[0]) ? entries[0]['resource'] : undefined; - if (!record(resource) || !simulated(resource)) invalid(); - return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) }; + const riesgos = entries.map(entry => { + const resource = record(entry) ? entry['resource'] : undefined; + if (!record(resource) || !simulated(resource)) invalid(); + return riskAssessment(structuredClone(resource), pacId); + }); + riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace)); + return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos }; } /** Presentation helper: an incomplete interval must never become a fabricated range. */