CaMa patient record as specified: recurrence and survival analyses with a scenario selector and their risk factors

This commit is contained in:
rockdrigo
2026-11-21 14:43:46 -06:00
parent ce207a72a5
commit 08f1d812ac
27 changed files with 487 additions and 446 deletions
@@ -0,0 +1,33 @@
@let r = respuesta();
<section aria-labelledby="analisis-recurrencia-titulo">
<h5 id="analisis-recurrencia-titulo">Análisis de recurrencia</h5>
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
@if (r) {
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
@else {
<label class="selector">Cohorte
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
</select>
</label>
<label class="selector">Escenario clínico
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
</select>
</label>
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
}
}
</section>
<section aria-labelledby="factores-recurrencia-titulo">
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
@if (r && r.escenarios.length) {
<label class="selector horizons">Horizonte
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
</select>
</label>
<app-cama-factores-riesgo [fila]="factores()" />
} @else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
</section>
@@ -0,0 +1,51 @@
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
import { figuraRecurrencia } from './cama-recurrencia-figura';
import { CamaRecurrenciaService } from './cama-recurrencia.service';
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
export const HORIZONTE_PREDETERMINADO = 60;
/**
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
*/
@Component({
selector: 'app-cama-analisis-recurrencia',
imports: [PlotlyChart, CamaFactoresRiesgo],
templateUrl: './cama-analisis-recurrencia.component.html',
styleUrl: './cama-analisis.component.scss',
})
export class CamaAnalisisRecurrencia {
readonly pacId = input.required<string>();
private readonly service = inject(CamaRecurrenciaService);
readonly cohortes = COHORTES;
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
private readonly cohorteElegida = signal<string | null>(null);
private readonly escenarioElegido = signal<string | null>(null);
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
/** The scenarios of the cohort chosen, from the list of that cohort only. */
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
readonly escenario = computed(() => {
const lista = this.escenarios();
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
});
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
readonly factores = computed(() => {
const f = this.escenario();
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
});
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
}
@@ -0,0 +1,26 @@
<section aria-labelledby="analisis-supervivencia-titulo">
<h5 id="analisis-supervivencia-titulo">Análisis de supervivencia</h5>
@let m = menu();
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
@if (m) {
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
@else {
<label class="selector">Escenario clínico
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
</select>
</label>
@let l = lectura();
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
@if (l?.tipo === 'error') { <p role="alert">No se pudo calcular la supervivencia de este escenario.</p> }
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Supervivencia: ' + escenario()" /> }
}
}
</section>
<section aria-labelledby="factores-supervivencia-titulo">
<h5 id="factores-supervivencia-titulo">Factores de riesgo</h5>
@if (lectura()?.tipo === 'lista') { <app-cama-factores-riesgo [fila]="factores()" /> }
@else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
</section>
@@ -0,0 +1,37 @@
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, startWith, switchMap } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { CamaCurvasService, EscenarioConFactores, SeleccionRechazada } from './cama-curvas.service';
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
import { figuraSupervivencia } from './cama-supervivencia-figura';
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores };
/**
* «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label
* at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on
* the scenario the patient belongs to.
*/
@Component({
selector: 'app-cama-analisis-supervivencia',
imports: [PlotlyChart, CamaFactoresRiesgo],
templateUrl: './cama-analisis-supervivencia.component.html',
styleUrl: './cama-analisis.component.scss',
})
export class CamaAnalisisSupervivencia {
readonly pacId = input.required<string>();
private readonly service = inject(CamaCurvasService);
/** The menu; `undefined` while it loads, `null` when there is no model in production. */
readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
private readonly elegido = signal<string | null>(null);
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
map((datos): Lectura => ({ tipo: 'lista', datos })),
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
startWith<Lectura>({ tipo: 'cargando' })))), { initialValue: null as Lectura | null });
readonly figura = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? figuraSupervivencia(l.datos.respuesta.curvas) : null; });
readonly factores = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? l.datos.factores : null; });
elegir(nombre: string): void { this.elegido.set(nombre); }
}
@@ -0,0 +1,5 @@
:host { display: block; }
.selector { display: inline-flex; flex-direction: column; gap: .25rem; margin: 0 1.5rem .75rem 0; font-size: .85rem; }
.selector select { font: inherit; padding: .35rem .5rem; min-width: 16rem; max-width: 100%; }
.horizons { margin: 0 0 .5rem; }
.pending { color: var(--mat-sys-outline, #777); margin: 0; }
@@ -0,0 +1,168 @@
// Covers Luis's specification of CaMa's record: the risk-factor label built from a summary row (the factors present in at least 95 % and in
// 50-95 % of the scenario, robust solid and suggestive outlined, grey "none" message), the survival analysis (one menu of scenarios; the
// one chosen decides the curve and the label at once; it opens on the patient's) and the recurrence analysis (two chained menus, the
// cohorts never mixed, a horizon for the label with 60 months by default). Fixtures: stubs of `CamaCurvasService` and
// `CamaRecurrenciaService` with a record like the API answers.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
import { CamaCurvasService, respuestaCurvas } from './cama-curvas.service';
import { CamaFactoresRiesgo, entradasDe } from './cama-factores-riesgo.component';
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
const meses = Array.from({ length: 25 }, (_, i) => i);
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
const curvas = (escenario: string, n = 245) => ({ modelo: { nombre: 'cama-survival', version: '3' }, curvas: {
version: 1, escenario, n, 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: {} } });
const fila = (escenario: string, extra: object = {}) => ({ escenario, riesgo_definitorios: 'Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)', riesgo_mayoritarios: 'HER2=H3 (sugerente, 60%)',
n_factores_riesgo_incluidos: 3, incluye_factor_riesgo: true, ...extra });
const texto = (f: { nativeElement: unknown }) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
function plotly() {
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()) };
return { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) };
}
function elegir(f: { nativeElement: unknown; detectChanges(): void }, etiqueta: string, valor: string) {
const select = [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!.querySelector('select')!;
select.value = valor;
select.dispatchEvent(new Event('change'));
f.detectChanges();
}
describe('Factores de riesgo: la etiqueta', () => {
const montar = (f: object | null) => {
const fx = TestBed.createComponent(CamaFactoresRiesgo);
fx.componentRef.setInput('fila', f);
fx.detectChanges();
return fx;
};
// Fails if an entry is cut at the wrong place or its strength is read from anything but its own parentheses.
it('reads the entries of a cell and whether each is robust', () => {
expect(entradasDe('Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)')).toEqual([
{ texto: 'Grado=G3 (robusto, 97%)', robusto: true }, { texto: 'Ki67=alto (sugerente, 96%)', robusto: false }]);
expect(entradasDe('')).toEqual([]);
});
// Fails if the two groups lose their order or a robust factor is not told from a suggestive one.
it('lists the defining factors, then the majority ones, a robust one solid and a suggestive one outlined', () => {
const fx = montar(fila('< 45 años'));
const items = [...(fx.nativeElement as HTMLElement).querySelectorAll('li')];
expect(texto(fx)).toContain('Factores de riesgo de este escenario');
expect(items.map(i => i.textContent!.trim())).toEqual(['Grado=G3 (robusto, 97%)', 'Ki67=alto (sugerente, 96%)', 'HER2=H3 (sugerente, 60%)']);
expect(items.map(i => i.classList.contains('robust'))).toEqual([true, false, false]);
});
// Fails if a scenario with no factors is shown empty, or with a different message.
it.each([[null], [fila('X', { incluye_factor_riesgo: false })], [fila('X', { n_factores_riesgo_incluidos: 0 })]])('says there are none (%#)', f => {
const fx = montar(f);
expect(texto(fx)).toContain('Sin factores de riesgo identificados en este escenario.');
expect((fx.nativeElement as HTMLElement).querySelector('li')).toBeNull();
});
});
describe('Análisis de supervivencia', () => {
let consulta: ReturnType<typeof vi.fn>;
beforeEach(() => {
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
});
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
f.componentRef.setInput('pacId', '7');
f.detectChanges();
f.detectChanges();
return f;
};
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
it('opens on the patient\'s scenario with the menu the API gave', () => {
const f = montar();
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
});
// Fails if choosing a scenario changes only the curve or only the label: the selector decides both at once, one scenario at a time.
it('changes the curve and the label together when another scenario is chosen, and never draws two', () => {
const f = montar();
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
elegir(f, 'Escenario clínico', '< 45 años');
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
});
});
describe('Análisis de recurrencia', () => {
const figura = (cohorte: string, escenario: string) => ({ cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, n: 300, recaidas: 180,
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
km: { months: Array.from({ length: 61 }, (_, i) => i), S: Array.from({ length: 61 }, (_, i) => 1 - i / 200), low: Array.from({ length: 61 }, (_, i) => 1 - i / 190), high: Array.from({ length: 61 }, () => 1) },
weibull: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, weibull_fractional: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, points: { COMB: { S: [0.9, 0.8, 0.7], low: [0.85, 0.75, 0.65], high: [0.95, 0.85, 0.75] } } });
const resumen = (cohorte: string, escenario: string, h: number) => ({ cohorte, escenario, horizonte_meses: h, riesgo_definitorios: `Marca=${cohorte}-${h} (robusto, 99%)`, riesgo_mayoritarios: '',
n_factores_riesgo_incluidos: 1, incluye_factor_riesgo: true });
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaAnalisisRecurrencia);
f.componentRef.setInput('pacId', '7');
f.detectChanges();
f.detectChanges();
return f;
};
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
.querySelectorAll('option');
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
const f = montar();
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
});
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
const f = montar();
elegir(f, 'Cohorte', 'metabric');
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
expect(texto(f)).toContain('Marca=metabric-60');
expect(texto(f)).not.toContain('scanb');
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
});
// Fails if the label ignores the horizon, or does not open on 60 months.
it('shows the label at the horizon chosen, 60 months by default', () => {
const f = montar();
expect((f.nativeElement as HTMLElement).querySelector<HTMLSelectElement>('.horizons select')!.value).toBe('60');
elegir(f, 'Horizonte', '12');
expect(texto(f)).toContain('Marca=scanb-12');
expect(texto(f)).not.toContain('Marca=scanb-60');
});
});
@@ -70,6 +70,26 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
};
}
/** The scenario summary's row of a scenario: its risk factors. `riesgo_*` are entries `Variable=Categoría (robusto|sugerente, porcentaje)`
* separated by `;`; `horizonte_meses` and `cohorte` only in the recurrence analysis. */
export interface FilaFactores {
escenario: string; riesgo_definitorios: string; riesgo_mayoritarios: string;
n_factores_riesgo_incluidos: number; incluye_factor_riesgo: boolean; horizonte_meses?: number; cohorte?: string;
}
export function filaFactores(v: unknown): FilaFactores {
if (!record(v) || typeof v['escenario'] !== 'string') invalid();
const f = v as Record<string, any>;
return { escenario: f['escenario'], riesgo_definitorios: typeof f['riesgo_definitorios'] === 'string' ? f['riesgo_definitorios'] : '',
riesgo_mayoritarios: typeof f['riesgo_mayoritarios'] === 'string' ? f['riesgo_mayoritarios'] : '',
n_factores_riesgo_incluidos: Number.isFinite(f['n_factores_riesgo_incluidos']) ? f['n_factores_riesgo_incluidos'] : 0,
incluye_factor_riesgo: f['incluye_factor_riesgo'] === true || f['incluye_factor_riesgo'] === 'True',
...(Number.isFinite(f['horizonte_meses']) ? { horizonte_meses: f['horizonte_meses'] } : {}), ...(typeof f['cohorte'] === 'string' ? { cohorte: f['cohorte'] } : {}) };
}
/** The scenarios the menu offers, and the one the patient belongs to first. */
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
/** A scenario's figure with its risk factors (`null`: it has no summary row). */
export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; }
/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */
export class SeleccionRechazada extends Error {}
@@ -77,20 +97,23 @@ export class SeleccionRechazada extends Error {}
export class CamaCurvasService {
private readonly http = inject(HttpClient);
/** The clinical scenarios the patient belongs to (the whole cohort when she is in none), or `null` when there is no model in
* production or no cohort yet. */
escenarios(pacId: string): Observable<string[] | null> {
return this.http.get<{ escenarios: string[] }>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
map(r => Array.isArray(r.escenarios) ? r.escenarios.filter(e => typeof e === 'string') : null),
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
escenarios(pacId: string): Observable<MenuEscenarios | null> {
return this.http.get<unknown>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
map(r => {
if (!record(r) || !Array.isArray(r['escenarios'])) invalid();
const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
}),
catchError(() => of(null)),
);
}
/** The figure's record of one scenario (`null`: the whole cohort), scored with the production version over the data
* ingested so far. A refused scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
consulta(escenario: string | null): Observable<RespuestaCurvas> {
/** The figure of one scenario scored with the production version over the data ingested so far, and its risk factors. A refused
* scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
consulta(escenario: string): Observable<EscenarioConFactores> {
return this.http.post<unknown>('/cama/modelo/curvas/consulta', { escenario }).pipe(
map(respuestaCurvas),
map(r => ({ respuesta: respuestaCurvas(r), factores: record(r) && r['factores'] ? filaFactores(r['factores']) : null })),
catchError(error => error instanceof HttpErrorResponse && error.status === 422
? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'El escenario no se puede calcular.')))
: throwError(() => error)),
@@ -0,0 +1,17 @@
@if (hay()) {
<p class="title">Factores de riesgo de este escenario</p>
@if (definitorios().length) {
<div class="group"><span class="marker" aria-hidden="true">▲</span>
<ul aria-label="Presentes en al menos 95 % del escenario">
@for (e of definitorios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
</ul></div>
}
@if (mayoritarios().length) {
<div class="group"><span class="marker" aria-hidden="true">▲</span>
<ul aria-label="Presentes en 50 a 95 % del escenario">
@for (e of mayoritarios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
</ul></div>
}
} @else {
<p class="none">Sin factores de riesgo identificados en este escenario.</p>
}
@@ -0,0 +1,9 @@
:host { display: block; }
.title { font-weight: 600; margin: 0 0 .5rem; }
.group { display: flex; gap: .5rem; align-items: flex-start; margin: .25rem 0; }
.marker { color: var(--mat-sys-error, #b3261e); line-height: 1.9; }
ul { display: flex; flex-wrap: wrap; gap: .4rem; list-style: none; margin: 0; padding: 0; }
li { border: 1px solid var(--mat-sys-error, #b3261e); border-radius: 1rem; padding: .15rem .7rem; font-size: .9rem; }
li.robust { background: var(--mat-sys-error, #b3261e); color: var(--mat-sys-on-error, #fff); }
li.suggestive { background: transparent; color: var(--mat-sys-error, #b3261e); }
.none { color: var(--mat-sys-outline, #777); margin: 0; }
@@ -0,0 +1,26 @@
import { Component, computed, input } from '@angular/core';
import { FilaFactores } from './cama-curvas.service';
export interface EntradaFactor { texto: string; robusto: boolean; }
/** The entries of a summary cell, `Variable=Categoría (robusto|sugerente, porcentaje)` separated by `;`. */
export function entradasDe(celda: string): EntradaFactor[] {
return celda.split(';').map(e => e.trim()).filter(Boolean).map(texto => ({ texto, robusto: /\(\s*robusto\b/i.test(texto) }));
}
/**
* The risk factors of one clinical scenario, from its row of the scenario summary: the factors present in at least 95 % of the scenario
* and those in 50 to 95 %, a robust one solid and a suggestive one outlined. A scenario with none says so, in grey.
*/
@Component({
selector: 'app-cama-factores-riesgo',
templateUrl: './cama-factores-riesgo.component.html',
styleUrl: './cama-factores-riesgo.component.scss',
})
export class CamaFactoresRiesgo {
readonly fila = input<FilaFactores | null>(null);
readonly definitorios = computed(() => entradasDe(this.fila()?.riesgo_definitorios ?? ''));
readonly mayoritarios = computed(() => entradasDe(this.fila()?.riesgo_mayoritarios ?? ''));
readonly hay = computed(() => (this.fila()?.incluye_factor_riesgo ?? false) && (this.fila()?.n_factores_riesgo_incluidos ?? 0) > 0
&& this.definitorios().length + this.mayoritarios().length > 0);
}
@@ -34,27 +34,24 @@
</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>
@if (p.idField === 'pac_id') {
<mat-card class="recurrence-card" appearance="outlined" aria-labelledby="recurrencia-title">
<mat-card-header><h3 id="recurrencia-title">Recurrencia</h3></mat-card-header>
<mat-card-content><app-cama-recurrencia-paciente [pacId]="p.patientId" /></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>
<ul>
@for (item of placeholders; track item.key) {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
}
</ul>
<p class="availability">{{ recommendationsUnavailable }}</p>
@if (p.idField === 'pac_id') { <app-cama-analisis-recurrencia [pacId]="p.patientId" /> }
<section aria-labelledby="recomendaciones-pronostico-title">
<h5 id="recomendaciones-pronostico-title">Recomendaciones</h5>
<p class="availability">{{ recommendationsUnavailable }}</p>
</section>
</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>
@if (p.idField === 'pac_id') { <app-cama-analisis-supervivencia [pacId]="p.patientId" /> }
<section aria-labelledby="recomendaciones-riesgo-title">
<h5 id="recomendaciones-riesgo-title">Recomendaciones</h5>
<p class="availability">{{ recommendationsUnavailable }}</p>
</section>
</mat-card-content>
</mat-card>
</div>
@@ -1,17 +1,20 @@
// Covers CaMa's individual record: how a follow-up row becomes its summary, what the card shows (only fields the list
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
// carries, "No disponible" for the rest, the two analyses with their risk factors in the order Luis's specification gives), and its focus
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { EMPTY, of } from 'rxjs';
import { CamaCurvasService } from './cama-curvas.service';
import { CamaRecurrenciaService } from './cama-recurrencia.service';
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';
import { CamaPatientSummary, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
import { CamaPatientSummary, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
const complete = () => rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!;
const incomplete = () => rows().find(r => r['biopsia'] === null)!;
const withPacId = () => ({ ...complete(), pac_id: '7', id_seudonimo: null });
describe('Ficha CaMa: resumen', () => {
// Fails if a field of the row is mapped to another one or lost on the way to the card.
@@ -41,8 +44,11 @@ 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) } }] }));
// The record asks for the analyses; here there is no model in production, so the card shows what the list carries.
beforeEach(() => TestBed.configureTestingModule({ providers: [
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } },
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] }));
function montar(summary: CamaPatientSummary) {
fixture = TestBed.createComponent(CamaPatientCard);
fixture.componentRef.setInput('summary', summary);
@@ -75,17 +81,18 @@ describe('Ficha CaMa: componente', () => {
expect(text).toContain('Días de mastografía a diagnóstico');
});
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
it('has a placeholder, with no figures, for the prognostic factors', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const items = [...root().querySelectorAll('[data-pronostico]')];
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Factores pronóstico']);
for (const item of items) {
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
expect(item.textContent).not.toMatch(/\d/);
}
expect(root().textContent).toContain(RECOMMENDATIONS_UNAVAILABLE);
// Fails if the cards or their subsections leave the order and the names of the specification: recurrence first, then death, each with
// its risk factors, and the recommendations unchanged (not available) in both.
it('has "Pronóstico y recomendaciones" (recurrence, risk factors, recommendations) before "Riesgo de muerte" (survival, risk factors, recommendations)', () => {
montar(toCamaPatientSummary(withPacId(), '2026-10-20')!);
const card = (selector: string) => root().querySelector(selector) as HTMLElement;
const subsections = (selector: string) => [...card(selector).querySelectorAll('h5')].map(h => h.textContent!.trim());
expect([...root().querySelectorAll('mat-card h3')].map(h => h.textContent!.trim()).slice(-2)).toEqual(['Pronóstico y recomendaciones', 'Riesgo de muerte']);
expect(subsections('.prognosis-card')).toEqual(['Análisis de recurrencia', 'Factores de riesgo', 'Recomendaciones']);
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
expect(root().textContent!.split(RECOMMENDATIONS_UNAVAILABLE).length - 1).toBe(2);
expect(root().textContent).not.toMatch(/Información simulada|Entorno DEV|Riesgo individual CaMa|Probabilidad de recurrencia|Factores pronóstico/);
});
// Fails if the record opens without moving focus to its title, which strands keyboard and screen-reader users.
@@ -3,19 +3,20 @@ 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 { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component';
import { PacienteRiesgoTabla } from '../paciente-riesgo-tabla';
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
/**
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries and the patient's risk with her
* survival figure; recurrence and prognostic factors are placeholders until a validated model supplies them.
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries, the recurrence analysis with its risk
* factors ("Pronóstico y recomendaciones") and the survival analysis with its risk factors ("Riesgo de muerte"), one clinical
* scenario at a time; the recommendations are not available yet.
*/
@Component({
selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla, CamaRecurrenciaPaciente],
imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia],
templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss',
})
@@ -23,8 +24,6 @@ export class CamaPatientCard implements AfterViewInit {
readonly summary = input.required<CamaPatientSummary>();
readonly back = output<void>();
readonly notAvailable = NOT_AVAILABLE;
readonly placeholders = PROGNOSIS_PLACEHOLDERS;
readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE;
readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE;
private readonly title = viewChild<ElementRef<HTMLElement>>('title');
readonly generating = signal(false);
@@ -1,5 +1,5 @@
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
// the fields of the record, shows placeholders (no figures) for the prognostic factors (survival and recurrence are drawn in the record from the models' figures), and
// the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
import fixtureData from '../../fixtures/cama_seguimiento.json';
@@ -46,10 +46,10 @@ describe('Ficha CaMa: PDF individual', () => {
});
// Fails if a placeholder gains a figure or an explanation other than "unavailable".
it('has placeholders, with no figures, for the prognostic factors and recommendations', () => {
it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => {
const found = texts(definition()['content']);
for (const t of ['Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(1);
for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3);
});
// Fails if the document carries a platform identifier field.
@@ -27,9 +27,11 @@ export interface CamaPatientSummary {
daysMammographyToDiagnosis: number | null;
}
/** Placeholders for results that exist only once a validated model and its clinical definition do (survival and recurrence are drawn
* from the models' figures, not placeholders). */
/** Placeholders for results that exist only once a validated model and its clinical definition do: what the exported PDF of the
* record says about them (on screen, the analyses and their risk factors are drawn from the models). */
export const PROGNOSIS_PLACEHOLDERS = [
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
{ key: 'survival', label: 'Supervivencia' },
{ key: 'factors', label: 'Factores pronóstico' },
] as const;
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
@@ -1,10 +0,0 @@
<section aria-labelledby="recurrencia-paciente-titulo">
<h5 id="recurrencia-paciente-titulo">Probabilidad de recurrencia</h5>
@let r = respuesta();
@if (r === undefined) { <p role="status">Buscando los escenarios clínicos de recurrencia de la paciente…</p> }
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
@if (r) {
@if (r.escenarios.length === 0) { <p role="status">La paciente no cumple ninguno de los escenarios clínicos del análisis de recurrencia.</p> }
@for (f of r.escenarios; track f.cohorte + f.escenario) { <app-cama-figura-recurrencia [datos]="f" /> }
}
</section>
@@ -1,122 +0,0 @@
// Covers CaMa's recurrence figures in a patient's record: the boundary validation of `GET /cama/modelo/recurrencia` (a malformed
// answer never draws a partial curve), the figure of a scenario in the pipeline's style (the Greenwood band, the Kaplan-Meier steps,
// the solid and dotted Weibull, the diamonds with their interval, "Libre de recaída S(t)"), and the component's states. Fixtures: a
// figure like the recurrence version publishes, and a stub of `CamaRecurrenciaService`.
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { vi } from 'vitest';
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
import { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component';
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
import { COLORES_RECURRENCIA, ETIQUETAS_RECURRENCIA, figuraRecurrencia } from './cama-recurrencia-figura';
const meses = Array.from({ length: 61 }, (_, i) => i);
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 60));
const grilla = Array.from({ length: 289 }, (_, i) => i * 0.25);
function figura(escenario = 'RE− · grado 3', cohorte = 'metabric'): any {
return {
cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, condiciones: { Grado_histologico: ['3'] }, n: 300, recaidas: 180,
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
km: { months: meses, S: decreciente(0.5), low: decreciente(0.45), high: decreciente(0.55) },
weibull: { t: grilla, S: grilla.map(t => Math.exp(-t / 90)) }, weibull_fractional: { t: grilla, S: grilla.map(t => Math.exp(-t / 85)) },
points: { COMB: { S: [0.9, 0.7, 0.55], low: [0.88, 0.67, 0.5], high: [0.92, 0.73, 0.6] } }, bootstrap_replicas: 200,
};
}
const respuesta = (escenarios = [figura()]): any => ({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios });
describe('Recurrencia CaMa: respuesta', () => {
// Fails if a record with an impossible value is accepted and drawn.
it('accepts an answer as published', () => {
expect(respuestaRecurrencia(respuesta()).escenarios[0].escenario).toBe('RE− · grado 3');
});
it.each([
['a probability above 1', (d: any) => { d.escenarios[0].km.S[3] = 1.2; }],
['an inverted interval', (d: any) => { d.escenarios[0].points.COMB.low[0] = 0.99; }],
['a series with another number of horizons', (d: any) => { d.escenarios[0].points.COMB.S.pop(); }],
['a missing curve', (d: any) => { delete d.escenarios[0].weibull_fractional; }],
['no model version', (d: any) => { delete d.modelo.version; }],
])('rejects %s', (_, estropear) => {
const d = respuesta();
estropear(d);
expect(() => respuestaRecurrencia(d)).toThrow('Respuesta de recurrencia inválida');
});
});
describe('Recurrencia CaMa: figura', () => {
const f = () => figuraRecurrencia(respuestaRecurrencia(respuesta()).escenarios[0]);
const traza = (nombre: string) => f().data.find((t: any) => t.name === nombre) as any;
// Fails if the figure loses a piece of the pipeline's chart.
it('has the Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => {
expect(f().data.some((t: any) => t.fill === 'tonexty')).toBe(true);
expect(traza(ETIQUETAS_RECURRENCIA.km).line).toMatchObject({ color: COLORES_RECURRENCIA.km, shape: 'hv' });
expect(traza(ETIQUETAS_RECURRENCIA.weibull).line.color).toBe(COLORES_RECURRENCIA.weibull);
expect(traza(ETIQUETAS_RECURRENCIA.weibull_fraccional).line).toMatchObject({ color: COLORES_RECURRENCIA.fraccional, dash: 'dash' });
const rombos = traza(ETIQUETAS_RECURRENCIA.puntos);
expect(rombos.x).toEqual([12, 36, 60]);
expect(rombos.error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.02, 0.03, 0.05]);
});
// Fails if the Weibull stops being dotted past the follow-up the cohort has, which would present an extrapolation as observed.
it('draws the Weibull dotted past the follow-up', () => {
const punteadas = f().data.filter((t: any) => t.line?.dash === 'dot') as any[];
expect(punteadas).toHaveLength(2);
expect(punteadas.every(t => Math.min(...t.x) >= 60)).toBe(true);
});
// Fails if the labels or the title leave the pipeline's: recurrence-free S(t), the scenario, the cohort, n and recurrences.
it('is titled with the scenario, the cohort, its patients and recurrences', () => {
const l = f().layout as any;
expect(l.title.text).toBe('RE− · grado 3<br>METABRIC · n=300, recaídas=180');
expect(l.yaxis.title.text).toBe('Libre de recaída S(t)');
expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico');
});
});
describe('Recurrencia de la paciente: componente', () => {
let recurrencia: ReturnType<typeof vi.fn>;
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()) };
recurrencia = vi.fn(() => of(respuestaRecurrencia(respuesta([figura(), figura('Grado 3', 'scanb')]))));
TestBed.configureTestingModule({ providers: [{ provide: CamaRecurrenciaService, useValue: { recurrencia } },
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
});
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaRecurrenciaPaciente);
f.componentRef.setInput('pacId', '7');
f.detectChanges();
f.detectChanges();
return f;
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if a scenario she meets in either cohort has no figure.
it('draws a figure for each scenario she meets, in each cohort', () => {
const f = montar();
expect(recurrencia).toHaveBeenCalledWith('7');
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2);
});
// Fails if a patient in no scenario sees nothing, or an error.
it('says so when she meets none of the scenarios', () => {
recurrencia.mockReturnValue(of(respuestaRecurrencia(respuesta([]))));
const f = montar();
expect(texto(f)).toContain('no cumple ninguno de los escenarios clínicos');
expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull();
});
// Fails if no model in production is shown as an error or a blank.
it('says there is no recurrence model yet', () => {
recurrencia.mockReturnValue(of(null));
expect(texto(montar())).toContain('Todavía no hay un modelo de recurrencia en producción');
});
});
@@ -1,34 +0,0 @@
import { Component, computed, inject, input } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { switchMap } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service';
import { figuraRecurrencia } from './cama-recurrencia-figura';
/** One scenario's recurrence figure. */
@Component({
selector: 'app-cama-figura-recurrencia',
imports: [PlotlyChart],
template: `@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + datos().escenario + ', ' + datos().cohorte_nombre" /> }`,
})
export class CamaFiguraRecurrencia {
readonly datos = input.required<FiguraRecurrencia>();
readonly figura = computed(() => figuraRecurrencia(this.datos()));
}
/**
* The patient's probability of recurrence: the figure of each clinical scenario of the recurrence analysis that her covariates meet,
* in each external cohort (METABRIC and SCAN-B). Patients in one scenario share its figure; it describes that scenario's patients in
* the cohort the analysis was made on.
*/
@Component({
selector: 'app-cama-recurrencia-paciente',
imports: [CamaFiguraRecurrencia],
templateUrl: './cama-recurrencia-paciente.component.html',
})
export class CamaRecurrenciaPaciente {
readonly pacId = input.required<string>();
private readonly service = inject(CamaRecurrenciaService);
/** The answer; `undefined` while it loads, `null` when there is no recurrence model in production. */
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
}
@@ -1,6 +1,7 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of } from 'rxjs';
import { FilaFactores, filaFactores } from './cama-curvas.service';
// CaMa's recurrence figures of a patient, `GET /cama/modelo/recurrencia?paciente=`: the clinical scenarios her covariates meet,
// each as the recurrence analysis of an external cohort (METABRIC or SCAN-B) drew it. They describe the scenario's patients in
@@ -13,7 +14,13 @@ export interface FiguraRecurrencia {
weibull_fractional: { t: number[]; S: number[] };
points: { COMB: { S: number[]; low: number[]; high: number[] } };
}
export interface RespuestaRecurrencia { modelo: { nombre: string; version: string }; horizontes: number[]; escenarios: FiguraRecurrencia[]; }
export interface RespuestaRecurrencia {
modelo: { nombre: string; version: string }; horizontes: number[]; escenarios: FiguraRecurrencia[];
/** The summary's rows, one per cohort, scenario and horizon: the risk-factor label. */
resumen: FilaFactores[];
/** The cohort and scenario the patient's own covariates place her in first, if any. */
predeterminado: { cohorte: string; escenario: string } | null;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number' && Number.isFinite(x)) && (length === undefined || v.length === length);
@@ -39,15 +46,18 @@ export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
if (!record(v) || !record(v['modelo']) || !Array.isArray(v['escenarios']) || !numbers(v['horizontes'])) invalid();
const m = v['modelo'] as Record<string, unknown>, h = (v['horizontes'] as number[]).length;
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
if (!Array.isArray(v['resumen'])) invalid();
const d = v['predeterminado'];
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)) };
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
}
@Injectable({ providedIn: 'root' })
export class CamaRecurrenciaService {
private readonly http = inject(HttpClient);
/** The figures of the scenarios the patient meets, or `null` when there is no recurrence model in production or it fails. */
/** The recurrence analysis of both cohorts and the patient's default, or `null` when there is no recurrence model in production or it fails. */
recurrencia(pacId: string): Observable<RespuestaRecurrencia | null> {
return this.http.get<unknown>('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe(
map(respuestaRecurrencia), catchError(() => of(null)));
@@ -1,9 +0,0 @@
<section class="survival" aria-labelledby="supervivencia-paciente-titulo">
<h5 id="supervivencia-paciente-titulo">Supervivencia</h5>
@let lista = escenarios();
@if (lista === undefined) { <p role="status">Buscando los escenarios clínicos de la paciente…</p> }
@if (lista === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
@if (lista) {
@for (nombre of lista; track nombre) { <app-cama-figura-escenario [escenario]="nombre" /> }
}
</section>
@@ -1 +0,0 @@
:host { display: block; }
@@ -1,142 +0,0 @@
// Covers the patient's survival in her CaMa record: the figure of each clinical scenario she belongs to is computed live (one
// request per scenario, none for her own curve), a refused scenario says why, no model in production says so, and the figure
// has the SEER pipeline's look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds). Fixtures: a stub of
// `CamaCurvasService` that records each scenario asked, and a record like `POST /cama/modelo/curvas/consulta` answers.
import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { vi } from 'vitest';
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
import { CamaCurvasService, respuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
import { CamaSupervivenciaPaciente } from './cama-supervivencia-paciente.component';
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));
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
function respuesta(escenario = '< 45 años', n = 245): any {
return {
modelo: { nombre: 'cama-survival', version: '3' },
curvas: {
version: 1, escenario, n, 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: {},
},
};
}
describe('Figura de supervivencia de un escenario', () => {
const figura = (r: any = respuesta()) => figuraSupervivencia(respuestaCurvas(r).curvas);
const traza = (f: any, nombre: string) => f.data.find((t: any) => t.name === nombre) as any;
// Fails if the figure loses a piece of the pipeline's chart: the band, the steps, the two Weibull or the diamonds with their bars.
it('has the Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => {
const f = figura();
expect(f.data.some((t: any) => t.fill === 'tonexty')).toBe(true);
expect(traza(f, ETIQUETAS_PREDETERMINADAS['km_crudo']).line).toMatchObject({ color: COLORES.km, shape: 'hv' });
expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull']).line.color).toBe(COLORES.weibull);
expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull_fraccional']).line).toMatchObject({ color: COLORES.fraccional, dash: 'dash' });
const rombos = traza(f, ETIQUETAS_PREDETERMINADAS['puntos']);
expect(rombos.x).toEqual([6, 12, 18]);
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]);
});
// Fails if anything but the pipeline's own curves is drawn: the patient's own curve is not part of the figure.
it('draws only the pipeline\'s curves, none of the patient\'s own', () => {
expect(figura().data.map((t: any) => t.name).filter(Boolean).sort()).toEqual(
['Kaplan-Meier (IC 95 % Greenwood)', 'LR + HBN combinado (IC 95 % bootstrap)', 'Weibull', 'Weibull fraccional'].sort());
});
// Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, the scenario, n and deaths.
it('is titled with the scenario, its patients and deaths, and scaled as the pipeline\'s figure', () => {
const l = figura().layout as any;
expect(l.title.text).toBe('< 45 años<br>n=245, fallecidos=67');
expect(l.yaxis.title.text).toBe('Supervivencia S(t)');
expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico');
expect(l.yaxis.tickformat).toBe('.2f');
expect(l.legend.yanchor).toBe('bottom');
});
// Fails if a label the model's run publishes is ignored, which would take the wording out of the clinicians' hands.
it('takes the wording from the record when the model publishes it', () => {
const r = respuesta();
r.curvas.etiquetas = { eje_y: 'Probabilidad de sobrevivir' };
expect((figura(r).layout as any).yaxis.title.text).toBe('Probabilidad de sobrevivir');
});
});
describe('Supervivencia de la paciente: componente', () => {
let consulta: ReturnType<typeof vi.fn>;
let escenarios: ReturnType<typeof vi.fn>;
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()) };
consulta = vi.fn((nombre: string | null) => of(respuesta(nombre ?? 'Toda la cohorte')));
escenarios = vi.fn(() => of(['< 45 años', 'Jóvenes (<45) · HER2−']));
TestBed.configureTestingModule({ providers: [
{ provide: CamaCurvasService, useValue: { escenarios, consulta } },
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
});
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
const f = TestBed.createComponent(CamaSupervivenciaPaciente);
f.componentRef.setInput('pacId', '7');
f.detectChanges();
return f;
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if the patient's scenarios are not asked for her, or a scenario she is in has no figure.
it('draws the figure of each scenario the patient belongs to, asked live', () => {
const f = montar();
f.detectChanges();
expect(escenarios).toHaveBeenCalledWith('7');
expect(consulta.mock.calls.map(c => c[0])).toEqual(['< 45 años', 'Jóvenes (<45) · HER2−']);
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2);
});
// Fails if a patient in no scenario is left without a figure, or the whole cohort is asked as a named scenario.
it('asks for the whole cohort when the patient is in no scenario', () => {
escenarios.mockReturnValue(of(['Toda la cohorte']));
const f = montar();
f.detectChanges();
expect(consulta).toHaveBeenCalledExactlyOnceWith(null);
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
});
// Fails if the record offers choices the reader did not ask for.
it('offers no choices', () => {
const f = montar();
f.detectChanges();
expect(f.nativeElement.querySelector('input, fieldset, select')).toBeNull();
});
// Fails if a refused scenario draws a figure, or does not say why.
it('says why when a scenario is refused and draws nothing for it', () => {
escenarios.mockReturnValue(of(['Estadio IV']));
consulta.mockReturnValue(throwError(() => new SeleccionRechazada('El escenario tiene 3 pacientes y 0 defunciones.')));
const f = montar();
f.detectChanges();
expect(texto(f)).toContain('Estadio IV: El escenario tiene 3 pacientes');
expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull();
});
// Fails if no model in production is shown as an error or a blank.
it('says there is no model yet', () => {
escenarios.mockReturnValue(of(null));
const f = montar();
f.detectChanges();
expect(texto(f)).toContain('Todavía no hay un modelo de supervivencia en producción');
expect(consulta).not.toHaveBeenCalled();
});
});
@@ -1,47 +0,0 @@
import { Component, computed, inject, input } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, startWith, switchMap } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { CamaCurvasService, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
import { figuraSupervivencia } from './cama-supervivencia-figura';
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas };
/** One clinical scenario's figure, computed when it is shown. */
@Component({
selector: 'app-cama-figura-escenario',
imports: [PlotlyChart],
template: `
@let l = lectura();
@if (l.tipo === 'cargando') { <p role="status">Calculando {{ escenario() }} con los datos más recientes…</p> }
@if (l.tipo === 'rechazada') { <p role="status">{{ escenario() }}: {{ l.motivo }}</p> }
@if (l.tipo === 'error') { <p role="alert">No se pudo calcular la supervivencia de {{ escenario() }}.</p> }
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Supervivencia: ' + escenario()" /> }`,
})
export class CamaFiguraEscenario {
readonly escenario = input.required<string>();
private readonly service = inject(CamaCurvasService);
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => this.service.consulta(nombre === 'Toda la cohorte' ? null : nombre).pipe(
map((datos): Lectura => ({ tipo: 'lista', datos })),
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
startWith<Lectura>({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura });
readonly figura = computed(() => { const l = this.lectura(); return l.tipo === 'lista' ? figuraSupervivencia(l.datos.curvas) : null; });
}
/**
* The patient's survival: the figure of each clinical scenario she belongs to (the whole cohort when she is in none), as the SEER
* pipeline draws them. Patients of one scenario share its figure; it is computed from the data ingested so far with the model
* in production.
*/
@Component({
selector: 'app-cama-supervivencia-paciente',
imports: [CamaFiguraEscenario],
templateUrl: './cama-supervivencia-paciente.component.html',
styleUrl: './cama-supervivencia-paciente.component.scss',
})
export class CamaSupervivenciaPaciente {
readonly pacId = input.required<string>();
private readonly service = inject(CamaCurvasService);
/** Her scenarios; `undefined` while they load, `null` when there is no model in production yet. */
readonly escenarios = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
}
@@ -1,12 +1,15 @@
// 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=
// index date; the CaMa record does not show it (its two analyses replace it). 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 { EMPTY } from 'rxjs';
import { CamaCurvasService } from './cama/cama-curvas.service';
import { CamaRecurrenciaService } from './cama/cama-recurrencia.service';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { INTERVALO, prediccion } from './paciente-riesgo.testing';
@@ -45,7 +48,9 @@ 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 } }] });
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } },
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] });
});
// Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only).
@@ -72,7 +77,6 @@ describe('Riesgo individual de la paciente CaMa', () => {
f.detectChanges();
const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
expect(f.nativeElement.querySelector('app-cama-supervivencia-paciente')).not.toBeNull();
expect(text).toContain('cama-survival');
expect(text).toContain('2025-06-19');
expect(text).toContain('Muerte por cualquier causa');
@@ -83,18 +87,14 @@ describe('Riesgo individual de la paciente CaMa', () => {
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();
// Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace.
it('is not in the CaMa record: its analyses and their risk factors are', () => {
const f = TestBed.createComponent(CamaPatientCard);
f.componentRef.setInput('summary', resumen('pac_id'));
f.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(obtener).not.toHaveBeenCalled();
expect(f.nativeElement.querySelector('app-paciente-riesgo-tabla')).toBeNull();
expect(INTERVALO).toContain('intervalo-confianza');
});
});
@@ -38,9 +38,6 @@
</table>
</div>
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
@if (dominio() === 'cama' && pacId(); as id) {
<app-cama-supervivencia-paciente [pacId]="id" />
}
}
}
<p class="recommendations">Recomendaciones no disponibles.</p>
@@ -1,13 +1,12 @@
import { Component, computed, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { CamaSupervivenciaPaciente } from './cama/cama-supervivencia-paciente.component';
import { DominioRiesgo } from './paciente-riesgo.models';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@Component({
selector: 'app-paciente-riesgo-tabla',
imports: [DecimalPipe, CamaSupervivenciaPaciente],
imports: [DecimalPipe],
providers: [PacienteRiesgoState],
templateUrl: './paciente-riesgo-tabla.html',
styleUrl: './paciente-riesgo-tabla.scss',
@@ -75,8 +75,8 @@ describe('Tabla de seguimiento con pac_id', () => {
// 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 }); });
// The record also asks for the recurrence figures of the patient; there is no model for them here.
http.match(r => r.url === '/cama/modelo/recurrencia').forEach(r => { if (!r.cancelled) r.flush({ error: 'sin recurrencia' }, { status: 404, statusText: 'Not Found' }); });
// The record asks for the two analyses of the patient (survival's menu and recurrence's); there is no model for them here.
http.match(r => r.url.startsWith('/cama/modelo/')).forEach(r => { if (!r.cancelled) r.flush({ error: 'sin modelo' }, { status: 404, statusText: 'Not Found' }); });
fixture.destroy(); http.verify();
});
const root = () => fixture.nativeElement as HTMLElement;