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 new file mode 100644 index 0000000..cb6363f --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -0,0 +1,137 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +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 { 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'; + +// What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons. +describe('Riesgo individual: qué se estima y su curva', () => { + function setup(data: unknown) { + const react = vi.fn(() => Promise.resolve()); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), + { provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } }, + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react, purge: vi.fn(), Plots: { resize: vi.fn() }, + addFrames: vi.fn(), deleteFrames: vi.fn() }) }] }); + const fixture = TestBed.createComponent(PacienteRiesgoTabla); + fixture.componentRef.setInput('pacId', '42'); + fixture.detectChanges(); + fixture.detectChanges(); + return { fixture, root: fixture.nativeElement as HTMLElement }; + } + + 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' }); + expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista()); + }); + + it('rechaza un estimando mal formado', () => { + const data = riesgoCacuConEstimando(); + data.entry[0].resource.extension[0].extension = 'texto'; + expect(() => riesgoPacienteResponse(data, '42')).toThrow(); + }); + + 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)', '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 () => { + const { fixture, root } = setup(riesgoCacuConEstimando()); + const details = root.querySelector('details.risk-curve') as HTMLDetailsElement; + expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado'); + expect(root.querySelector('app-plotly-chart')).toBeNull(); + details.open = true; + details.dispatchEvent(new Event('toggle')); + fixture.detectChanges(); + expect(root.querySelector('app-plotly-chart')).not.toBeNull(); + }); + + 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]); + 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]); + 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 new file mode 100644 index 0000000..78c08ff --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts @@ -0,0 +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'; + +/** 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 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(riesgos: LoteRiesgoCacu[]): PlotlyFigure { + const data: Record[] = []; + 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 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: 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 f04c835..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,37 +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
-
-
Modelo
{{ riesgo.modelo_nombre }}
-
Versión del modelo
{{ riesgo.modelo_version }}
-
Fecha índice
{{ riesgo.fecha_indice }}
-
Desenlace
{{ riesgo.desenlace_texto ?? riesgo.desenlace }}
-
Evaluado en
-
Estado del lote
{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}
-
- @if (riesgo.horizontes.length) { -
- - - - - - - - - @for (h of riesgo.horizontes; track h.horizonte_anios) { - - - - - - } - -
Probabilidades por horizonte desde la fecha índice
Horizonte (años)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 }
-
- } @else {

Sin horizontes evaluados en el lote vigente.

} + @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) }}
} + + } +
+ @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 90a76f3..768e31a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -18,3 +18,9 @@ thead th { position: sticky; top: 0; background: var(--issste-background, var(-- 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 4342680..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,6 +1,10 @@ -import { Component, computed, effect, inject, input } from '@angular/core'; -import { DecimalPipe } from '@angular/common'; -import { DominioRiesgo } from './paciente-riesgo.models'; +import { Component, computed, effect, inject, input, signal } from '@angular/core'; +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'; @@ -12,7 +16,7 @@ export const instanteUtc = (iso: string) => { @Component({ selector: 'app-paciente-riesgo-tabla', - imports: [DecimalPipe], + imports: [LowerCasePipe, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -27,6 +31,21 @@ export class PacienteRiesgoTabla { readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; 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); + 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() { effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); } 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 4acb7cc..9da4a44 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -14,6 +14,25 @@ export interface HorizonteRiesgoCacu { ic_alto?: number | null; } +/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */ +export interface EstimandoRiesgo { + /** e.g. "Riesgo acumulado"; also `method.text`. */ + quantity?: string; + description?: string; + outcome?: string; + index_date?: string; + /** The unit the horizons are counted in, e.g. "años". */ + horizons_unit?: 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/`). */ export interface LoteRiesgoCacu { /** The resource's id, `-`. */ @@ -28,12 +47,21 @@ export interface LoteRiesgoCacu { desenlace: string; desenlace_texto: string | null; 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 2344b80..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,7 +1,8 @@ -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'; +export const ESTIMANDO = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; /** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */ export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any { @@ -37,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: [ @@ -47,6 +46,68 @@ export function riesgoCacuVista(): RiesgoPacienteCacu { { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 }, { 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`). */ +export function riesgoCacuConEstimando(): any { + const data = riesgoCacuEjemplo(); + const resource = data.entry[0].resource; + resource.method.text = 'Riesgo acumulado'; + resource.extension = [{ url: ESTIMANDO, extension: [ + { url: 'quantity', valueString: 'Riesgo acumulado' }, + { url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' }, + { url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' }, + { url: 'horizons_unit', valueString: 'años' }, + { url: 'interval', valueString: 'IC 95 % por método delta' }, + { url: 'otra', valueString: 'se ignora' }, + ] }]; + 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 dbbade0..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 { 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); @@ -9,6 +9,11 @@ const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1; 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 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' @@ -39,6 +44,40 @@ function interval(prediction: Record): { ic_bajo: number | null return { ic_bajo: low, ic_alto: high }; } +/** 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'] === url); + if (found === undefined) return null; + if (!Array.isArray(found['extension'])) invalid(); + const result: Partial> = {}; + for (const item of found['extension']) { + if (!record(item) || !text(item['url'])) invalid(); + 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']; @@ -62,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; @@ -80,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, + horizontes, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS), + sin_estimacion: null, }; } @@ -89,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. */ diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.html b/src/app/governance/components/model-version-dialog/model-version-dialog.html index b5f74b6..eed3b70 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.html +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.html @@ -83,24 +83,25 @@

Rutinas del entrenamiento

-

Lo que cada rutina hizo, registrado por la corrida mientras entrenaba (ML-01a).

-
    - @for (routine of routineKinds; track routine.kind) { - @let record = l.routines[routine.kind]; -
  • - - {{ routine.label }} - @if (record) { +

    Lo que cada rutina hizo, registrado por la corrida mientras entrenaba. No todos los modelos + tienen cada rutina; no se piden para promover (ML-01a lo cumple la corrida misma).

    + @let recorded = recordedRoutines(l.routines); + @if (recorded.length) { +
      + @for (routine of recorded; track routine.kind) { +
    • + + {{ routine.label }}
      - {{ record['method'] ?? 'Ver registro' }} -
      {{ record | json }}
      + {{ routine.record['method'] ?? 'Ver registro' }} +
      {{ routine.record | json }}
      - } @else { - La corrida no la registró. - } -
    • - } -
    +
  • + } +
+ } @else { +

La corrida no guardó registros de rutina.

+ }
diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.ts b/src/app/governance/components/model-version-dialog/model-version-dialog.ts index 1874e32..514b675 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.ts +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.ts @@ -55,7 +55,10 @@ export class ModelVersionDialog { private readonly version = inject(MAT_DIALOG_DATA); private readonly dialog = inject(MatDialog); - readonly routineKinds = ROUTINES; + /** The routines the run recorded, in `ROUTINES`' order; the others aren't listed. */ + recordedRoutines(routines: ModelLineage['routines']) { + return ROUTINES.filter((r) => routines[r.kind]).map((r) => ({ ...r, record: routines[r.kind]! })); + } readonly lineage = signal(null); readonly busy = signal(false); readonly error = signal(null); diff --git a/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts b/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts index 5fb0ca6..46297c5 100644 --- a/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts +++ b/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts @@ -1,8 +1,8 @@ // Covers the risk batches panel's domain choice: it lists the pending batches of the domain shown (CaCu first, CaMa on -// request) and decides a batch in that domain. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call, +// request) and decides a batch in that domain, one decision at a time. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call, // and an account that reaches every domain. import { TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; +import { of, Subject } from 'rxjs'; import { vi } from 'vitest'; import { AuthService } from '../../../auth/auth.service'; import { RiskBatchesApi } from '../../api/risk-batches.api'; @@ -45,4 +45,21 @@ describe('RiskBatchesPanel domains', () => { expect(api['confirm']).toHaveBeenCalledExactlyOnceWith('cama', 5, 'revisado'); }); + + // Fails if a double click sends the decision twice: the second one finds nothing to decide or collides with the first. + it('sends one decision while another is on its way', () => { + const answer = new Subject<{ lote_id: number; evaluaciones_cambiadas: number }>(); + api['confirm'].mockReturnValue(answer); + const f = TestBed.createComponent(RiskBatchesPanel); + f.detectChanges(); + const batch = f.componentInstance.batches()[0]; + f.componentInstance.reasonFor(batch).setValue('revisado'); + + f.componentInstance.confirm(batch); + f.componentInstance.confirm(batch); + f.componentInstance.void(batch); + + expect(api['confirm']).toHaveBeenCalledTimes(1); + expect(api['void']).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts b/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts index 8a0a52e..825bb24 100644 --- a/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts +++ b/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts @@ -111,7 +111,8 @@ export class RiskBatchesPanel implements OnInit { verb: string, ): void { const reason = this.reasonFor(batch).value.trim(); - if (!reason) return; + // a double click reaches here before the disabled button is drawn: one decision at a time + if (!reason || this.deciding() !== null) return; this.deciding.set(batch.lote_id); request(reason).subscribe({ next: () => {