Merge feature/cama-roundtrip

This commit is contained in:
rockdrigo
2026-11-21 02:51:31 -06:00
20 changed files with 553 additions and 18 deletions
@@ -0,0 +1,60 @@
import { PlotlyFigure, Tema } from '../indicadores.models';
import { CurvasSupervivencia, SerieDeSupervivencia } from './cama-supervivencia.service';
/** The clinicians' wording of the chart: what the model's run published (`[config.etiquetas]`), and these defaults for
* a label it leaves out. The labels are settings, not code, so they can be defined with the clinicians. */
export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor',
eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia',
km_crudo: 'Kaplan-Meier (observada)', km_ajustada: 'Kaplan-Meier ajustada por covariables',
weibull: 'Weibull ajustada', weibull_fraccional: 'Weibull fraccional ajustada',
puntos: 'Modelo (LR + red bayesiana) con IC 95 %', LR: 'Regresión logística', HBN: 'Red bayesiana', COMB: 'Modelo combinado',
};
export const COLORES = { km_crudo: '#9aa5b1', km_ajustada: '#3d4852', weibull: '#e0a060', fraccional: '#d1495b', modelo: '#6a3d9a', lr: '#1f77b4', hbn: '#2a9d8f' } as const;
export const etiquetaDe = (curvas: CurvasSupervivencia, clave: string) => curvas.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave;
function puntos(curvas: CurvasSupervivencia, serie: SerieDeSupervivencia, nombre: string, color: string, visible: true | 'legendonly', tamano: number): Record<string, unknown> {
const h = curvas.horizons_months;
return {
type: 'scatter', mode: 'markers', name: nombre, x: h, y: serie.S, visible, legendgroup: nombre,
marker: { symbol: 'diamond', size: tamano, color, line: { color: 'white', width: 1 } },
error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 1.8, width: 5,
array: serie.high.map((hi, i) => hi - serie.S[i]), arrayminus: serie.S.map((s, i) => s - serie.low[i]) },
customdata: serie.low.map((lo, i) => [lo, serie.high[i]]),
hovertemplate: `${nombre}<br>%{x} meses: %{y:.1%}<br>IC 95 %: %{customdata[0]:.1%} a %{customdata[1]:.1%}<extra></extra>`,
};
}
/** The figure of the model's results: the cohort's Kaplan-Meier with its band, the covariate-adjusted curve, the fitted
* Weibull curves, and the model's survival at each horizon as diamonds with their bootstrap interval. */
export function figuraSupervivencia(curvas: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure {
const km = curvas.km, ajustada = curvas.km_adjusted, t = (clave: string) => etiquetaDe(curvas, clave);
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
const todos = [...km.low, ...ajustada.S, ...curvas.weibull_fractional.S, ...curvas.points.COMB.low];
const minimo = Math.max(0, Math.min(...todos) - 0.03);
const data: Record<string, unknown>[] = [
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: 'rgba(154,165,177,.35)', line: { width: 0, shape: 'hv' },
name: `${t('km_crudo')}, IC 95 %`, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km_crudo, width: 1.4, dash: 'dot', shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km',
hovertemplate: '%{x} meses: %{y:.1%}<extra>' + t('km_crudo') + '</extra>' },
{ type: 'scatter', mode: 'lines', x: ajustada.months, y: ajustada.S, line: { color: COLORES.km_ajustada, width: 2, shape: 'hv' }, name: t('km_ajustada'),
hovertemplate: '%{x} meses: %{y:.1%}<extra>' + t('km_ajustada') + '</extra>' },
{ type: 'scatter', mode: 'lines', x: curvas.weibull.t, y: curvas.weibull.S, line: { color: COLORES.weibull, width: 2, dash: 'dash' }, name: t('weibull'), visible: 'legendonly' },
{ type: 'scatter', mode: 'lines', x: curvas.weibull_fractional.t, y: curvas.weibull_fractional.S, line: { color: COLORES.fraccional, width: 2.6 }, name: t('weibull_fraccional'),
hovertemplate: '%{x:.1f} meses: %{y:.1%}<extra>' + t('weibull_fraccional') + '</extra>' },
puntos(curvas, curvas.points.LR, t('LR'), COLORES.lr, 'legendonly', 9),
puntos(curvas, curvas.points.HBN, t('HBN'), COLORES.hbn, 'legendonly', 9),
puntos(curvas, curvas.points.COMB, t('puntos'), COLORES.modelo, true, 12),
];
const layout: Record<string, unknown> = {
title: { text: `${t('titulo')} (n = ${curvas.n.toLocaleString('es-MX')})`, x: 0, xanchor: 'left', font: { size: 16, color: texto } },
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
xaxis: { title: { text: t('eje_x') }, range: [0, curvas.months_max + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false },
yaxis: { title: { text: t('eje_y') }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false },
legend: { orientation: 'h', y: -0.22, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 110 }, hovermode: 'closest',
};
return { data, layout, config: { responsive: true, displaylogo: false } };
}
@@ -0,0 +1,39 @@
<h2 id="supervivencia-titulo">Supervivencia</h2>
@let l = lectura();
@switch (l.tipo) {
@case ('cargando') { <p role="status">Cargando resultados del modelo…</p> }
@case ('no-disponible') {
<p role="status">Todavía no hay un modelo de supervivencia en producción. Cuando se entrene y se promueva en Gobernanza, sus resultados aparecerán aquí.</p>
}
@case ('error') { <p role="alert">No se pudieron cargar los resultados del modelo. Intenta nuevamente más tarde.</p> }
@case ('listo') {
@let c = l.datos.curvas;
@if (l.datos.simulado) { <p class="simulated-label">Información simulada · Entorno DEV · Sin evaluación clínica</p> }
<dl class="metadata">
<div><dt>Modelo</dt><dd>{{ l.datos.modelo.nombre }}, versión {{ l.datos.modelo.version }}</dd></div>
<div><dt>Pacientes en la cohorte</dt><dd>{{ c.n }}</dd></div>
<div><dt>Defunciones</dt><dd>{{ c.events }}</dd></div>
<div><dt>Seguimiento mediano (meses)</dt><dd>{{ c.median_follow_up_months | number:'1.0-1' }}</dd></div>
<div><dt>Réplicas bootstrap</dt><dd>{{ c.bootstrap_replicas }}</dd></div>
</dl>
@if (figura(); as figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" [label]="etiquetaDe(c, 'titulo')" />
}
<div class="points-scroll" role="region" aria-label="Supervivencia por horizonte, tabla desplazable" tabindex="0">
<table>
<caption>{{ etiquetaDe(c, 'puntos') }}</caption>
<thead><tr><th scope="col">Meses desde el reporte</th><th scope="col">Supervivencia (%)</th><th scope="col">IC 95 % (%)</th></tr></thead>
<tbody>
@for (fila of filas(l.datos); track fila.meses) {
<tr>
<th scope="row">{{ fila.meses }}</th>
<td class="percentage">{{ fila.S | number:'1.1-1' }} %</td>
<td class="interval">{{ fila.low | number:'1.1-1' }} % – {{ fila.high | number:'1.1-1' }} %</td>
</tr>
}
</tbody>
</table>
</div>
@if (c.etiquetas['nota']; as nota) { <p class="note">{{ nota }}</p> }
}
}
@@ -0,0 +1,11 @@
:host { display: block; padding: 1rem 0; }
h2 { font-size: 1.25rem; margin: 0 0 .75rem; }
.simulated-label { font-weight: 600; margin: 0 0 .75rem; }
.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: .5rem 1.25rem; margin: 0 0 1rem;
div { display: flex; flex-direction: column; } dt { font-size: .8rem; opacity: .8; } dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; } }
.points-scroll { overflow-x: auto; margin-top: 1rem; &:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } }
table { border-collapse: collapse; min-width: 22rem; }
caption { text-align: left; font-weight: 600; padding-bottom: .4rem; }
th, td { padding: .4rem .75rem; border-bottom: 1px solid rgba(128, 128, 128, .35); text-align: left; }
.percentage, .interval { font-variant-numeric: tabular-nums; }
.note { margin-top: 1rem; font-size: .85rem; opacity: .85; }
@@ -0,0 +1,84 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of, throwError } from 'rxjs';
// The survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the
// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the
// version they come from and says when the data are simulated. A 404 is "no model in production yet".
export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; }
export interface CurvasSupervivencia {
n: number; events: number; median_follow_up_months: number;
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
km: { months: number[]; S: number[]; low: number[]; high: number[] };
km_adjusted: { months: number[]; S: number[] };
weibull: { t: number[]; S: number[] };
weibull_fractional: { t: number[]; S: number[] };
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
etiquetas: Record<string, string>;
}
export interface RespuestaCurvas {
simulado: boolean;
modelo: { nombre: string; version: string; mlflow_run_id: string };
curvas: CurvasSupervivencia;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length);
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
function invalid(): never {
throw new Error('Respuesta de curvas de supervivencia inválida');
}
function serie(v: unknown, horizons: number): SerieDeSupervivencia {
if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid();
const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[];
if (low.some((l, i) => l > high[i])) invalid();
return { S: s, low, high };
}
/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */
export function respuestaCurvas(v: unknown): RespuestaCurvas {
if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid();
const m = v['modelo'] as Record<string, unknown>, c = v['curvas'] as Record<string, unknown>;
if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid();
const horizons = c['horizons_months'];
if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events'])
|| !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid();
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
for (const curve of [weibull, fractional]) {
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
}
if (!record(points)) invalid();
const p = points as Record<string, unknown>, h = (horizons as number[]).length;
const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record<string, string> : {};
return {
simulado: v['simulado'] === true,
modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string },
curvas: {
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
},
};
}
@Injectable({ providedIn: 'root' })
export class CamaSupervivenciaService {
private readonly http = inject(HttpClient);
/** The production version's curves, or `null` when there is none (a 404). */
curvas(): Observable<RespuestaCurvas | null> {
return this.http.get<unknown>('/cama/modelo/curvas').pipe(
map(respuestaCurvas),
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
);
}
}
@@ -0,0 +1,157 @@
// Covers CaMa's survival tab: the boundary validation of `GET /cama/modelo/curvas` (a malformed record never draws a partial
// curve), the figure built from the record (the model's diamonds at 6, 12 and 18 months with their interval, the curves,
// the labels from the model's settings), and the component's states and table. Fixtures: `curvasEjemplo`, a record like a
// training run publishes; a stub Plotly runtime, so the chart is not drawn for real.
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
import { CamaSupervivencia } from './cama-supervivencia';
import { respuestaCurvas } from './cama-supervivencia.service';
import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivencia } from './cama-supervivencia-figura';
const meses = Array.from({ length: 25 }, (_, i) => i);
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
function curvasEjemplo(): any {
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
return {
simulado: true,
modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' },
curvas: {
version: 1, n: 245, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200,
km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) },
km_adjusted: { months: meses, S: decreciente(0.72) },
weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] },
points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) },
etiquetas: { eje_x: 'Meses desde la biopsia', nota: 'Datos simulados. Sin validación clínica.' },
},
};
}
describe('Supervivencia CaMa: respuesta', () => {
// Fails if a record with an impossible value is accepted and drawn.
it('accepts a record as published and keeps it', () => {
const r = respuestaCurvas(curvasEjemplo());
expect(r.modelo.version).toBe('3');
expect(r.curvas.points.COMB.S).toEqual([0.925, 0.845, 0.775]);
});
it.each([
['a probability above 1', (d: any) => { d.curvas.km.S[3] = 1.2; }],
['a curve shorter than its months', (d: any) => { d.curvas.km_adjusted.S.pop(); }],
['an inverted interval', (d: any) => { d.curvas.points.COMB.low[0] = 0.99; }],
['a series with another number of horizons', (d: any) => { d.curvas.points.LR.S.pop(); }],
['no model version', (d: any) => { delete d.modelo.version; }],
['a missing curve', (d: any) => { delete d.curvas.weibull_fractional; }],
])('rejects %s', (_, estropear) => {
const d = curvasEjemplo();
estropear(d);
expect(() => respuestaCurvas(d)).toThrow('Respuesta de curvas de supervivencia inválida');
});
});
describe('Supervivencia CaMa: figura', () => {
const figura = () => figuraSupervivencia(respuestaCurvas(curvasEjemplo()).curvas);
const traza = (nombre: string) => figura().data.find(t => t['name'] === nombre) as any;
// Fails if the diamonds move off 6, 12 and 18 months, or their interval bars stop being the record's interval.
it('draws the combined model as diamonds at the horizons with its interval', () => {
const rombos = traza(ETIQUETAS_PREDETERMINADAS['puntos']);
expect(rombos.x).toEqual([6, 12, 18]);
expect(rombos.y).toEqual([0.925, 0.845, 0.775]);
expect(rombos.marker).toMatchObject({ symbol: 'diamond', color: COLORES.modelo });
expect(rombos.error_y.array.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]);
expect(rombos.error_y.arrayminus.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]);
});
// Fails if the observed and adjusted curves, the band and the fractional Weibull are not all there, or LR and HBN start visible.
it('draws the Kaplan-Meier with its band, the adjusted curve and the fractional Weibull; LR and HBN start hidden', () => {
const f = figura(), nombres = f.data.map(t => t['name']);
expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_crudo']);
expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_ajustada']);
expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['weibull_fraccional']);
expect(f.data.some(t => t['fill'] === 'tonexty')).toBe(true);
expect(traza(ETIQUETAS_PREDETERMINADAS['LR']).visible).toBe('legendonly');
expect(traza(ETIQUETAS_PREDETERMINADAS['HBN']).visible).toBe('legendonly');
});
// Fails if the axis titles stop coming from the model's settings, or a label it leaves out stops falling back.
it('takes the labels from the record and falls back for the ones it leaves out', () => {
const l = figura().layout as any;
expect(l.xaxis.title.text).toBe('Meses desde la biopsia');
expect(l.yaxis.title.text).toBe(ETIQUETAS_PREDETERMINADAS['eje_y']);
expect(l.title.text).toContain('(n = 245)');
});
// Fails if the y axis hides a curve or an interval below its range, or leaves survival above 100 %.
it('fits the y range to the lowest curve or interval and stops at 100 %', () => {
const [bajo, alto] = (figura().layout as any).yaxis.range;
expect(bajo).toBeLessThan(0.6);
expect(bajo).toBeGreaterThanOrEqual(0);
expect(alto).toBeCloseTo(1.005);
});
});
describe('Supervivencia CaMa: componente', () => {
let http: HttpTestingController;
beforeEach(() => {
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); vi.unstubAllGlobals(); });
const montar = (active: boolean) => {
const f = TestBed.createComponent(CamaSupervivencia);
f.componentRef.setInput('active', active);
f.detectChanges();
return f;
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if the tab asks for the results before it is shown, or asks again when it is shown again.
it('asks once, the first time the tab is shown', () => {
const f = montar(false);
http.expectNone('/cama/modelo/curvas');
f.componentRef.setInput('active', true);
f.detectChanges();
http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo());
f.componentRef.setInput('active', false);
f.detectChanges();
f.componentRef.setInput('active', true);
f.detectChanges();
http.expectNone('/cama/modelo/curvas');
});
// Fails if the model, its version, the counts, the simulated label, the table of the diamonds or the note are not shown.
it('shows the model, the counts, the simulated label, the table of the horizons and the note', () => {
const f = montar(true);
http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo());
f.detectChanges();
const t = texto(f);
expect(t).toContain('cama-survival, versión 3');
expect(t).toContain('245');
expect(t).toContain('Información simulada');
expect(t).toContain('92.5 %');
expect(t).toContain('88.5 % – 96.5 %');
expect(t).toContain('Datos simulados. Sin validación clínica.');
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['6', '12', '18']);
});
// Fails if no model in production is shown as an error, or a failed or malformed answer as a chart.
it('says there is no model yet on a 404 and fails closed on an error or a malformed record', () => {
const sinModelo = montar(true);
http.expectOne('/cama/modelo/curvas').flush({ error: 'sin curvas' }, { status: 404, statusText: 'Not Found' });
sinModelo.detectChanges();
expect(texto(sinModelo)).toContain('Todavía no hay un modelo de supervivencia en producción');
const roto = montar(true);
http.expectOne('/cama/modelo/curvas').flush({ curvas: {} });
roto.detectChanges();
expect(texto(roto)).toContain('No se pudieron cargar los resultados del modelo');
expect((roto.nativeElement as HTMLElement).querySelector('app-plotly-chart')).toBeNull();
});
});
@@ -0,0 +1,51 @@
import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { DecimalPipe } from '@angular/common';
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
import { Tema } from '../indicadores.models';
import { CamaSupervivenciaService, RespuestaCurvas } from './cama-supervivencia.service';
import { etiquetaDe, figuraSupervivencia } from './cama-supervivencia-figura';
type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaCurvas };
/**
* CaMa's survival results: the cohort's survival curves and the model's survival at 6, 12 and 18 months with its
* interval, as the production version of the model published them. Population results, never a patient's: a patient's own
* risk is in her record. Loads once, the first time the tab is shown.
*/
@Component({
selector: 'app-cama-supervivencia',
imports: [PlotlyChart, DecimalPipe],
templateUrl: './cama-supervivencia.html',
styleUrl: './cama-supervivencia.scss',
})
export class CamaSupervivencia {
readonly active = input(false);
readonly tema = input<Tema>('claro');
private readonly service = inject(CamaSupervivenciaService);
private readonly destroy = inject(DestroyRef);
readonly lectura = signal<Lectura>({ tipo: 'cargando' });
private pedido = false;
readonly figura = computed(() => {
const l = this.lectura();
return l.tipo === 'listo' ? figuraSupervivencia(l.datos.curvas, this.tema()) : null;
});
readonly etiquetaDe = etiquetaDe;
constructor() {
effect(() => {
if (!this.active() || this.pedido) return;
this.pedido = true;
this.service.curvas().pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }),
error: () => this.lectura.set({ tipo: 'error' }),
});
});
}
/** The combined model's survival at each horizon, for the table that says what the figure's diamonds say. */
filas(datos: RespuestaCurvas) {
const c = datos.curvas, p = c.points.COMB;
return c.horizons_months.map((meses, i) => ({ meses, S: p.S[i] * 100, low: p.low[i] * 100, high: p.high[i] * 100 }));
}
}
@@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => {
http.match(() => true);
}
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
it('CaMa oculta Análisis y conserva Histórico, Supervivencia y Análisis de Riesgos', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
fixture.componentInstance.changeSection('analisis');
fixture.detectChanges();
@@ -138,6 +138,12 @@
</section>
}
@if (conSupervivencia) {
<section id="panel-supervivencia" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-supervivencia" tabindex="0" [hidden]="activeSection() !== 'supervivencia'">
<app-cama-supervivencia [active]="activeSection() === 'supervivencia'" [tema]="tema" />
</section>
}
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
[seleccion]="seleccionSeguimiento()" (volverAlAnalisis)="volverAlAnalisis()"
@@ -31,10 +31,11 @@ import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { CamaSupervivencia } from './cama-supervivencia/cama-supervivencia';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'supervivencia' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' },
@@ -48,17 +49,19 @@ export const CAMA_ANALYSIS_ENABLED = false;
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
{ id: 'supervivencia' as const, label: 'Supervivencia' },
{ id: 'seguimiento', label: 'Análisis de Riesgos' }, SECTIONS_WITH_HISTORY[3]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
get conSupervivencia() { return this.dominio === 'cama'; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
@@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos and adds Supervivencia; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
@@ -33,6 +33,12 @@
</ul>
</mat-card-content>
</mat-card>
<mat-card class="risk-card" appearance="outlined" aria-labelledby="riesgo-individual-title">
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
<mat-card-content>
<app-paciente-riesgo-tabla [pacId]="p.idField === 'pac_id' ? p.patientId : null" dominio="cama" />
</mat-card-content>
</mat-card>
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
<mat-card-content>
@@ -2,6 +2,8 @@
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { PACIENTE_RIESGO_PROVIDER } from '../paciente-riesgo.provider';
import fixtureData from '../../fixtures/cama_seguimiento.json';
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
import { CamaPatientCard } from './cama-patient-card';
@@ -39,6 +41,8 @@ describe('Ficha CaMa: resumen', () => {
describe('Ficha CaMa: componente', () => {
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
const root = () => fixture.nativeElement as HTMLElement;
// The record asks for the patient's risk; here she has none, so the card shows what the list carries.
beforeEach(() => TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] }));
function montar(summary: CamaPatientSummary) {
fixture = TestBed.createComponent(CamaPatientCard);
fixture.componentRef.setInput('summary', summary);
@@ -3,6 +3,7 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { PacienteRiesgoTabla } from '../paciente-riesgo-tabla';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
@@ -13,7 +14,7 @@ import {
*/
@Component({
selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule],
imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla],
templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss',
})
@@ -0,0 +1,98 @@
// Covers the patient's risk in CaMa's record: the table asks the CaMa endpoint (and CaCu's calls stay as they were), says
// whose model scored her, shows the mortality at the horizons the model gives (6, 12 and 18 months) and the model's
// index date, and the CaMa card carries the panel. Fixtures: a Bundle like `GET /cama/fhir/RiskAssessment?subject=
// Patient/7` answers it (`riesgoCamaEjemplo`), and a provider that returns it.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { CamaPatientCard } from './cama/cama-patient-card';
import { CamaPatientSummary } from './cama/cama-patient.models';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { INTERVALO, prediccion } from './paciente-riesgo.testing';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
/** TEST ONLY. Patient 7's current CaMa `RiskAssessment`: mortality at 6, 12 and 18 months from the model's index date. */
function riesgoCamaEjemplo(): any {
const muerte = (p: number, fin: string) => {
const item = prediccion(p, '2025-06-19', fin);
item.outcome = { coding: [{ system: `${CS}/desenlace`, code: 'muerte', display: 'Muerte por cualquier causa' }] };
return item;
};
return {
resourceType: 'Bundle', type: 'searchset', total: 1,
entry: [{
fullUrl: 'http://localhost/cama/fhir/RiskAssessment/3-7',
resource: {
resourceType: 'RiskAssessment', id: '3-7', status: 'final',
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
subject: { reference: 'Patient/7' }, occurrenceDateTime: '2026-01-02T10:00:00Z',
method: { coding: [{ system: `${CS}/modelo`, code: 'cama-survival', version: '1' }] },
prediction: [muerte(0.07, '2025-12-19'), muerte(0.178, '2026-06-19'), muerte(0.251, '2026-12-19')],
},
search: { mode: 'match' },
}],
};
}
const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({
patientId: '7', idField, idLabel: 'pac_id', cutoff: '2026-01-01', ageGroup: '50-59', status: null, priority: null,
birads: 'B5', mammographyDate: '2025-06-01', histopathology: 'CARCINOMA_INVASOR', biopsyDate: '2025-06-19',
daysMammographyToDiagnosis: null,
});
describe('Riesgo individual de la paciente CaMa', () => {
const obtener = vi.fn();
beforeEach(() => {
obtener.mockReset().mockImplementation(() => of(riesgoCamaEjemplo()));
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } }] });
});
// Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only).
it('asks its domain for the patient, and CaCu with the id alone', () => {
const cama = TestBed.createComponent(PacienteRiesgoTabla);
cama.componentRef.setInput('pacId', '7');
cama.componentRef.setInput('dominio', 'cama');
cama.detectChanges();
const cacu = TestBed.createComponent(PacienteRiesgoTabla);
cacu.componentRef.setInput('pacId', '7');
cacu.detectChanges();
expect(obtener).toHaveBeenNthCalledWith(1, '7', 'cama');
expect(obtener).toHaveBeenNthCalledWith(2, '7');
expect(cama.nativeElement.textContent).toContain('Riesgo individual CaMa');
expect(cacu.nativeElement.textContent).toContain('Riesgo individual CaCu');
});
// Fails if the mortality, its outcome, the model or the index date of the Bundle are not what the card shows.
it('shows the model, the index date, the outcome and the mortality at each horizon', () => {
const f = TestBed.createComponent(PacienteRiesgoTabla);
f.componentRef.setInput('pacId', '7');
f.componentRef.setInput('dominio', 'cama');
f.detectChanges();
const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
expect(text).toContain('cama-survival');
expect(text).toContain('2025-06-19');
expect(text).toContain('Muerte por cualquier causa');
expect(text).toContain('7 %');
expect(text).toContain('17.8 %');
expect(text).toContain('25.1 %');
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
});
// Fails if the record asks for a risk by a row that has no `pac_id` (a legacy pseudonym), or does not ask when it has one.
it('is asked for by the patient\'s pac_id, and not by a pseudonym', () => {
const conPacId = TestBed.createComponent(CamaPatientCard);
conPacId.componentRef.setInput('summary', resumen('pac_id'));
conPacId.detectChanges();
const conSeudonimo = TestBed.createComponent(CamaPatientCard);
conSeudonimo.componentRef.setInput('summary', resumen('id_seudonimo'));
conSeudonimo.detectChanges();
expect(obtener).toHaveBeenCalledExactlyOnceWith('7', 'cama');
expect(conPacId.nativeElement.querySelector('.risk-card')).not.toBeNull();
expect(conSeudonimo.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(INTERVALO).toContain('intervalo-confianza');
});
});
@@ -1,4 +1,4 @@
<h4>Riesgo individual CaCu</h4>
<h4>Riesgo individual {{ rotulo() }}</h4>
@let lectura = estado();
@switch (lectura.tipo) {
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@@ -1,5 +1,6 @@
import { Component, effect, inject, input } from '@angular/core';
import { Component, computed, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { DominioRiesgo } from './paciente-riesgo.models';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@@ -13,11 +14,14 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
export class PacienteRiesgoTabla {
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>();
/** The domain whose model scored her: CaCu unless said otherwise. */
readonly dominio = input<DominioRiesgo>('cacu');
readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu');
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
constructor() {
effect(() => this.state.pacId.set(this.pacId()));
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
}
}
@@ -2,6 +2,9 @@ import { Observable } from 'rxjs';
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
/** The domain whose patient's risk is read: its FHIR endpoint is `/<dominio>/fhir`. CaCu unless said otherwise. */
export type DominioRiesgo = 'cacu' | 'cama';
export interface HorizonteRiesgoCacu {
/** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */
horizonte_anios: number;
@@ -35,7 +38,7 @@ export interface RiesgoPacienteCacu {
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(pacId: string): Observable<unknown>;
obtener(pacId: string, dominio?: DominioRiesgo): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -4,12 +4,13 @@ import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/<pac_id>`, the identifier a follow-up row
// carries as `pac_id`; an empty Bundle (or a 404) is a patient without risk data.
// carries as `pac_id`, in the domain's endpoint (`/cacu/fhir`, or `/cama/fhir`); an empty Bundle (or a 404) is a patient
// without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>('/cacu/fhir/RiskAssessment', {
obtener: (pacId: string, dominio = 'cacu') => http.get<unknown>(`/${dominio}/fhir/RiskAssessment`, {
params: new HttpParams().set('subject', `Patient/${pacId}`),
}).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
@@ -1,7 +1,7 @@
import { Injectable, inject, signal } from '@angular/core';
import { Injectable, computed, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { DominioRiesgo, PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
@@ -12,8 +12,11 @@ export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
// `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
readonly dominio = signal<DominioRiesgo>('cacu');
// The patient and her domain are one query, so changing both never asks for the patient in the wrong domain.
private readonly consulta = computed(() => ({ id: this.pacId(), dominio: this.dominio() }));
readonly estado = toSignal(toObservable(this.consulta).pipe(
switchMap(({ id, dominio }) => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => dominio === 'cacu' ? this.provider.obtener(id) : this.provider.obtener(id, dominio)).pipe(
map((respuesta): PacienteRiesgoEstado => {
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
@@ -72,7 +72,11 @@ describe('Tabla de seguimiento con pac_id', () => {
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
// Opening a CaMa record asks for the patient's risk; in these tests nobody has one.
afterEach(() => {
http.match(r => r.url === '/cama/fhir/RiskAssessment').forEach(r => { if (!r.cancelled) r.flush({ resourceType: 'Bundle', type: 'searchset', total: 0 }); });
fixture.destroy(); http.verify();
});
const root = () => fixture.nativeElement as HTMLElement;
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];