CaMa survival: the patient's own scenario, a menu only when she is in several

This commit is contained in:
Roberto Treviño Cervantes
2026-11-22 21:38:43 -06:00
parent ec8542de9f
commit 7ab2567dc9
4 changed files with 43 additions and 18 deletions
@@ -4,13 +4,16 @@
@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> }
@if (opciones().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>
@if (opciones().length === 1) { <p class="selector">Escenario clínico de la paciente: <strong>{{ escenario() }}</strong></p> }
@else {
<label class="selector">Escenarios clínicos de la paciente
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
@for (e of opciones(); 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> }
@@ -9,9 +9,9 @@ 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.
* «Análisis de supervivencia» and its «Factores de riesgo» of the clinical scenario the patient's own data place her in; when they place
* her in several, a menu of those. The scenario decides the curve and the label at once, computed from the data ingested so far with the
* model in production.
*/
@Component({
selector: 'app-cama-analisis-supervivencia',
@@ -25,6 +25,8 @@ export class CamaAnalisisSupervivencia {
/** 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);
/** Her scenarios; every scenario only if the server could not place her. */
readonly opciones = computed(() => { const m = this.menu(); return m ? (m.deLaPaciente.length ? m.deLaPaciente : m.escenarios) : []; });
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 })),
@@ -78,7 +78,8 @@ describe('Análisis de supervivencia', () => {
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 } }] });
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }, { nombre: 'Estadio IV', n: 30 }],
deLaPaciente: [{ nombre: 'Estadio I', n: 80 }, { nombre: '< 45 años', n: 100 }], predeterminado: 'Estadio I' }), consulta } }] });
});
afterEach(() => vi.unstubAllGlobals());
const montar = () => {
@@ -89,12 +90,12 @@ describe('Análisis de supervivencia', () => {
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', () => {
// Fails if the menu does not open on the patient's scenario, or offers a scenario her data do not place her in.
it('opens on the patient\'s scenario and offers only hers', () => {
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(opciones).toEqual(['Estadio I', '< 45 años']);
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']);
});
@@ -104,7 +105,7 @@ describe('Análisis de supervivencia', () => {
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');
elegir(f, 'Escenarios clínicos de la paciente', '< 45 años');
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
@@ -112,6 +113,25 @@ describe('Análisis de supervivencia', () => {
});
});
describe('Análisis de supervivencia de una paciente con un solo escenario', () => {
// Fails if a patient whose data place her in one scenario is asked to choose: the scenario is named and drawn, with no menu.
it('names her one scenario and draws it without a menu', () => {
const consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: null }));
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }],
deLaPaciente: [{ nombre: 'Toda la cohorte', n: 500 }], predeterminado: 'Toda la cohorte' }), consulta } }] });
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
f.componentRef.setInput('pacId', '9');
f.detectChanges();
f.detectChanges();
expect((f.nativeElement as HTMLElement).querySelector('select')).toBeNull();
expect(texto(f)).toContain('Escenario clínico de la paciente: Toda la cohorte');
expect(consulta).toHaveBeenCalledExactlyOnceWith('Toda la cohorte');
vi.unstubAllGlobals();
});
});
describe('Análisis de recurrencia', () => {
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
it('scales the y axis to the months it draws', () => {
@@ -87,7 +87,7 @@ export function filaFactores(v: unknown): FilaFactores {
}
/** The scenarios the menu offers, and the one the patient belongs to first. */
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; deLaPaciente: { 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. */
@@ -97,13 +97,13 @@ export class SeleccionRechazada extends Error {}
export class CamaCurvasService {
private readonly http = inject(HttpClient);
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
/** The scenarios the menu offers, the patient's own and her 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 };
const leer = (v: unknown) => (Array.isArray(v) ? v : []).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: leer(r['escenarios']), deLaPaciente: leer(r['de_la_paciente']), predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
}),
catchError(() => of(null)),
);