Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4c181af291 | |||
| 7d180417d8 | |||
| 00f773dd75 | |||
| 3bb1c8dd84 |
@@ -38,7 +38,13 @@
|
||||
<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>
|
||||
@if (item.key === 'recurrence' && p.idField === 'pac_id') {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><app-cama-recurrencia [pacId]="+p.patientId" /></li>
|
||||
} @else if (item.key === 'survival' && p.idField === 'pac_id') {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><app-cama-supervivencia [pacId]="+p.patientId" /></li>
|
||||
} @else {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
|
||||
}
|
||||
}
|
||||
</ul>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
|
||||
@@ -3,17 +3,19 @@ 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 { CamaRecurrencia } from './cama-recurrencia';
|
||||
import { CamaSupervivencia } from './cama-supervivencia';
|
||||
import {
|
||||
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
} from './cama-patient.models';
|
||||
|
||||
/**
|
||||
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
|
||||
* survival and prognostic factors are placeholders until a validated model supplies them.
|
||||
* Individual record of a CaMa follow-up patient: what the follow-up list carries and, in its prognosis card, the recurrence and
|
||||
* survival figures of the clinical scenarios the patient belongs to.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-patient-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule],
|
||||
imports: [CamaRecurrencia, CamaSupervivencia, MatButtonModule, MatCardModule, MatIconModule],
|
||||
templateUrl: './cama-patient-card.html',
|
||||
styleUrl: './cama-patient-card.scss',
|
||||
})
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { RecurrenciaFigura } from './cama-recurrencia.models';
|
||||
|
||||
const decimales = new Intl.NumberFormat('es-MX');
|
||||
const finitos = (valores: (number | null)[]) => valores.filter((v): v is number => v !== null && Number.isFinite(v));
|
||||
|
||||
/**
|
||||
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull (dotted past the
|
||||
* follow-up), and the combined estimate at each horizon with its bootstrap interval.
|
||||
*/
|
||||
export function figuraRecurrencia(figura: RecurrenciaFigura): PlotlyFigure {
|
||||
const km = figura.km;
|
||||
const seguimiento = km.months[km.months.length - 1];
|
||||
const combinado = figura.points.COMB;
|
||||
const tiempos = figura.weibull.t;
|
||||
const dentro = tiempos.map(t => t <= seguimiento);
|
||||
const trazo = (S: (number | null)[], dentroDelSeguimiento: boolean) =>
|
||||
S.map((v, i) => (dentro[i] === dentroDelSeguimiento || (!dentroDelSeguimiento && tiempos[i] === seguimiento) ? v : null));
|
||||
const todos = [...finitos(km.low), ...finitos(km.high), ...finitos(combinado.low), ...finitos(combinado.high),
|
||||
...finitos(figura.weibull.S), ...finitos(figura.weibull_fractional.S)];
|
||||
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
|
||||
const horizontes = figura.horizons_months;
|
||||
const S = combinado.S.map(v => v ?? NaN);
|
||||
return {
|
||||
data: [
|
||||
{ x: km.months, y: km.low, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
|
||||
{ x: km.months, y: km.high, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty',
|
||||
fillcolor: 'rgba(154,165,177,0.3)', hoverinfo: 'skip', showlegend: false },
|
||||
{ x: km.months, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
|
||||
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
|
||||
{ x: tiempos, y: trazo(figura.weibull.S, true), type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
|
||||
{ x: tiempos, y: trazo(figura.weibull.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#1f77b4', dash: 'dot' },
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: tiempos, y: trazo(figura.weibull_fractional.S, true), type: 'scatter', mode: 'lines',
|
||||
line: { width: 3, color: '#d1495b', dash: 'dash' }, name: 'Weibull fraccional' },
|
||||
{ x: tiempos, y: trazo(figura.weibull_fractional.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#d1495b', dash: 'dot' },
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: horizontes, y: S, type: 'scatter', mode: 'markers',
|
||||
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
|
||||
error_y: { type: 'data', symmetric: false, array: combinado.high.map((v, i) => (v ?? NaN) - S[i]),
|
||||
arrayminus: combinado.low.map((v, i) => S[i] - (v ?? NaN)), color: '#6a3d9a', thickness: 2, width: 5 },
|
||||
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
|
||||
],
|
||||
layout: {
|
||||
title: { text: `${figura.escenario}<br>${figura.cohorte_nombre} · n=${decimales.format(figura.n)}, recaídas=${decimales.format(figura.recaidas)}`,
|
||||
font: { size: 15 } },
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, figura.months_max + 0.8], dtick: 12, zeroline: false },
|
||||
yaxis: { title: { text: 'Libre de recaída S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
|
||||
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 },
|
||||
hovermode: 'x unified',
|
||||
},
|
||||
config: { responsive: true, displaylogo: false },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
@switch (estado()) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de recurrencia" /> }
|
||||
@case ('sin-modelo') { <p class="availability">No hay una cohorte armada para el análisis de recurrencia.</p> }
|
||||
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de recurrencia.</p> }
|
||||
@default {
|
||||
@if (!postratamiento()) {
|
||||
<p class="availability">El análisis de recurrencia es para pacientes que ya terminaron su tratamiento.</p>
|
||||
} @else {
|
||||
@if (deLaPaciente().length) {
|
||||
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico de la paciente" [value]="elegido()?.cohorte + '|' + elegido()?.escenario"
|
||||
(change)="elegirDePaciente($event.value)">
|
||||
@for (e of deLaPaciente(); track e.cohorte + e.escenario) {
|
||||
<mat-button-toggle [value]="e.cohorte + '|' + e.escenario">{{ nombreCohorte(e.cohorte) }} · {{ e.escenario }}</mat-button-toggle>
|
||||
}
|
||||
</mat-button-toggle-group>
|
||||
} @else {
|
||||
<p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo. Elige uno del menú.</p>
|
||||
}
|
||||
<div class="menu">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Cohorte</mat-label>
|
||||
<mat-select [value]="cohorteDelMenu()" (selectionChange)="elegirCohorte($event.value)">
|
||||
@for (c of cohortes(); track c.id) { <mat-option [value]="c.id">{{ c.nombre }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Escenario</mat-label>
|
||||
<mat-select [value]="elegido()?.escenario" (selectionChange)="elegir(cohorteDelMenu(), $event.value)">
|
||||
@for (e of escenariosDelMenu(); track e.nombre) { <mat-option [value]="e.nombre">{{ e.nombre }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
}
|
||||
@if (calculando()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
|
||||
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de recurrencia del escenario clínico" /> }
|
||||
@if (mensaje(); as texto) { <p class="availability" role="status">{{ texto }}</p> }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/** The recurrence analysis as `/cama/recurrencia` gives it: the scenarios of each cohort, a scenario's figure and a patient's scenarios. */
|
||||
export interface RecurrenciaEscenario { nombre: string; condiciones: Record<string, string[]>; n: number; recaidas: number; dibujable: boolean }
|
||||
export interface RecurrenciaCohorte { id: string; nombre: string; estado: 'calculando' | 'listo' | 'error'; error: string | null; escenarios: RecurrenciaEscenario[] }
|
||||
export interface RecurrenciaEscenarios { build: number; horizontes: number[]; cohortes: RecurrenciaCohorte[] }
|
||||
export interface RecurrenciaDePaciente { build: number; pac_id: number; postratamiento: boolean; escenarios: { cohorte: string; escenario: string }[] }
|
||||
|
||||
export interface RecurrenciaFigura {
|
||||
cohorte: string;
|
||||
cohorte_nombre: string;
|
||||
escenario: string;
|
||||
n: number;
|
||||
recaidas: number;
|
||||
horizons_months: number[];
|
||||
months_max: number;
|
||||
bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
weibull: { t: number[]; S: (number | null)[] };
|
||||
weibull_fractional: { t: number[]; S: (number | null)[] };
|
||||
points: { COMB: { S: (number | null)[]; low: (number | null)[]; high: (number | null)[] } };
|
||||
}
|
||||
export type RecurrenciaRespuestaFigura = { estado: 'calculando' } | { estado: 'listo'; figura: RecurrenciaFigura };
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
|
||||
|
||||
export function recurrenciaEscenarios(v: unknown): RecurrenciaEscenarios {
|
||||
if (!record(v) || typeof v['build'] !== 'number' || !numbers(v['horizontes']) || !Array.isArray(v['cohortes'])
|
||||
|| !v['cohortes'].every(c => record(c) && typeof c['id'] === 'string' && typeof c['nombre'] === 'string' && Array.isArray(c['escenarios']))) {
|
||||
throw new Error('Respuesta de escenarios de recurrencia inválida');
|
||||
}
|
||||
return v as unknown as RecurrenciaEscenarios;
|
||||
}
|
||||
|
||||
export function recurrenciaDePaciente(v: unknown): RecurrenciaDePaciente {
|
||||
if (!record(v) || typeof v['postratamiento'] !== 'boolean' || !Array.isArray(v['escenarios'])
|
||||
|| !v['escenarios'].every(e => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')) {
|
||||
throw new Error('Respuesta de recurrencia de la paciente inválida');
|
||||
}
|
||||
return v as unknown as RecurrenciaDePaciente;
|
||||
}
|
||||
|
||||
export function recurrenciaFigura(v: unknown): RecurrenciaFigura {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte'] !== 'string' || typeof v['n'] !== 'number'
|
||||
|| typeof v['recaidas'] !== 'number' || !numbers(v['horizons_months']) || !record(v['km']) || !numbers(v['km']['months'])
|
||||
|| !numbers(v['km']['S']) || !record(v['weibull']) || !record(v['weibull_fractional']) || !record(v['points'])) {
|
||||
throw new Error('Respuesta de figura de recurrencia inválida');
|
||||
}
|
||||
return v as unknown as RecurrenciaFigura;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
:host { display: block; min-width: 0; --plot-height: 420px; }
|
||||
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
|
||||
.menu { display: flex; flex-wrap: wrap; gap: 0.75rem; margin: 0.75rem 0; }
|
||||
.availability { margin: 0; }
|
||||
@@ -0,0 +1,29 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import {
|
||||
recurrenciaDePaciente, recurrenciaEscenarios, recurrenciaFigura, RecurrenciaRespuestaFigura,
|
||||
} from './cama-recurrencia.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaRecurrenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios of each cohort, with their size and whether they have enough recurrences to be drawn. */
|
||||
escenarios() {
|
||||
return this.http.get<unknown>('/cama/recurrencia/escenarios').pipe(map(recurrenciaEscenarios));
|
||||
}
|
||||
|
||||
/** The scenarios a patient's covariates meet, in each cohort; empty for a patient who is not after treatment. */
|
||||
deLaPaciente(pacId: number) {
|
||||
return this.http.get<unknown>(`/cama/recurrencia/pacientes/${pacId}`).pipe(map(recurrenciaDePaciente));
|
||||
}
|
||||
|
||||
/** The figure of one scenario; `calculando` while the cohort's models are being computed. */
|
||||
figura(cohorte: string, escenario: string) {
|
||||
const params = new HttpParams().set('cohorte', cohorte).set('escenario', escenario);
|
||||
return this.http.get<unknown>('/cama/recurrencia/figura', { params, observe: 'response' }).pipe(
|
||||
map((r: HttpResponse<unknown>): RecurrenciaRespuestaFigura =>
|
||||
r.status === 202 ? { estado: 'calculando' } : { estado: 'listo', figura: recurrenciaFigura(r.body) }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { forkJoin, Subscription, timer } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { RecurrenciaCohorte } from './cama-recurrencia.models';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
|
||||
const ESPERA_CALCULO_MS = 5000;
|
||||
|
||||
/**
|
||||
* A patient's recurrence: the clinical scenarios her covariates meet and, from a menu, any scenario of either cohort, with the
|
||||
* figure of the one chosen, computed over the live cohort.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-recurrencia',
|
||||
imports: [MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
templateUrl: './cama-recurrencia.html',
|
||||
styleUrl: './cama-recurrencia.scss',
|
||||
})
|
||||
export class CamaRecurrencia {
|
||||
readonly pacId = input.required<number>();
|
||||
readonly estado = signal<'cargando' | 'listo' | 'sin-modelo' | 'error'>('cargando');
|
||||
readonly postratamiento = signal(false);
|
||||
readonly cohortes = signal<RecurrenciaCohorte[]>([]);
|
||||
readonly deLaPaciente = signal<{ cohorte: string; escenario: string }[]>([]);
|
||||
readonly elegido = signal<{ cohorte: string; escenario: string } | null>(null);
|
||||
readonly figura = signal<PlotlyFigure | null>(null);
|
||||
readonly calculando = signal(false);
|
||||
readonly mensaje = signal<string | null>(null);
|
||||
private readonly menuCohorte = signal<string | null>(null);
|
||||
readonly cohorteDelMenu = computed(() => this.menuCohorte() ?? this.elegido()?.cohorte ?? this.cohortes()[0]?.id ?? '');
|
||||
readonly escenariosDelMenu = computed(() =>
|
||||
this.cohortes().find(c => c.id === this.cohorteDelMenu())?.escenarios.filter(e => e.dibujable) ?? []);
|
||||
private readonly servicio = inject(CamaRecurrenciaService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private pedido?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.cargar(this.pacId()));
|
||||
}
|
||||
|
||||
nombreCohorte(id: string) { return this.cohortes().find(c => c.id === id)?.nombre ?? id; }
|
||||
|
||||
private cargar(pacId: number) {
|
||||
this.estado.set('cargando'); this.limpiar(); this.elegido.set(null); this.menuCohorte.set(null);
|
||||
forkJoin({ menu: this.servicio.escenarios(), paciente: this.servicio.deLaPaciente(pacId) })
|
||||
.pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: ({ menu, paciente }) => {
|
||||
this.cohortes.set(menu.cohortes);
|
||||
this.postratamiento.set(paciente.postratamiento);
|
||||
this.deLaPaciente.set(paciente.escenarios);
|
||||
this.estado.set('listo');
|
||||
if (paciente.postratamiento && paciente.escenarios.length) this.elegir(paciente.escenarios[0].cohorte, paciente.escenarios[0].escenario);
|
||||
},
|
||||
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
|
||||
});
|
||||
}
|
||||
|
||||
private limpiar() { this.figura.set(null); this.mensaje.set(null); this.calculando.set(false); this.pedido?.unsubscribe(); }
|
||||
|
||||
elegirDePaciente(clave: string) { const [cohorte, ...resto] = clave.split('|'); this.elegir(cohorte, resto.join('|')); }
|
||||
|
||||
elegirCohorte(cohorte: string) { this.menuCohorte.set(cohorte); this.elegido.set(null); this.limpiar(); }
|
||||
|
||||
elegir(cohorte: string, escenario: string) {
|
||||
this.limpiar();
|
||||
this.elegido.set({ cohorte, escenario }); this.menuCohorte.set(cohorte); this.calculando.set(true);
|
||||
const vigente = () => this.elegido()?.cohorte === cohorte && this.elegido()?.escenario === escenario;
|
||||
const pedir = () => {
|
||||
this.pedido = this.servicio.figura(cohorte, escenario).subscribe({
|
||||
next: r => {
|
||||
if (!vigente()) return;
|
||||
if (r.estado === 'calculando') {
|
||||
this.mensaje.set('Calculando los modelos de la cohorte; la figura aparecerá en cuanto estén listos.');
|
||||
this.pedido = timer(ESPERA_CALCULO_MS).subscribe(() => { if (vigente()) pedir(); });
|
||||
return;
|
||||
}
|
||||
this.calculando.set(false); this.mensaje.set(null); this.figura.set(figuraRecurrencia(r.figura));
|
||||
},
|
||||
error: (e: { status?: number }) => {
|
||||
if (!vigente()) return;
|
||||
this.calculando.set(false);
|
||||
this.mensaje.set(e?.status === 404 ? 'El escenario tiene pocas recaídas para dibujar su curva.' : 'No se pudo calcular la figura. Intenta nuevamente.');
|
||||
},
|
||||
});
|
||||
};
|
||||
pedir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { SupervivenciaFigura } from './cama-supervivencia.models';
|
||||
|
||||
const decimales = new Intl.NumberFormat('es-MX');
|
||||
|
||||
/**
|
||||
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the
|
||||
* LR + HBN combined survival at each horizon with its bootstrap interval.
|
||||
*/
|
||||
export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure {
|
||||
const meses = figura.months ?? [];
|
||||
const km = figura.km!;
|
||||
const curvas = figura.curve_months ?? [];
|
||||
const combinados = figura.points.filter(p => p.model === 'COMB');
|
||||
const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1];
|
||||
const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])]
|
||||
.filter(v => Number.isFinite(v));
|
||||
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
|
||||
return {
|
||||
data: [
|
||||
{ x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
|
||||
{ x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)',
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
|
||||
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
|
||||
{ x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
|
||||
{ x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' },
|
||||
name: 'Weibull fraccional' },
|
||||
{ x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers',
|
||||
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
|
||||
error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low),
|
||||
color: '#6a3d9a', thickness: 2, width: 5 },
|
||||
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
|
||||
],
|
||||
layout: {
|
||||
title: { text: `${figura.scenario}<br>n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } },
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false },
|
||||
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
|
||||
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 },
|
||||
hovermode: 'x unified',
|
||||
},
|
||||
config: { responsive: true, displaylogo: false },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
@switch (estado()) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de supervivencia" /> }
|
||||
@case ('sin-modelo') { <p class="availability">No hay un modelo de supervivencia en producción.</p> }
|
||||
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de supervivencia.</p> }
|
||||
@case ('sin-escenarios') { <p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo.</p> }
|
||||
@default {
|
||||
@if (escenarios().length > 1) {
|
||||
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico" [value]="elegido()" (change)="elegir($event.value)">
|
||||
@for (nombre of escenarios(); track nombre) { <mat-button-toggle [value]="nombre">{{ nombre }}</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
}
|
||||
@if (cargandoFigura()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
|
||||
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de supervivencia del escenario clínico" /> }
|
||||
@if (sinDibujo(); as mensaje) { <p class="availability" role="status">{{ mensaje }}</p> }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */
|
||||
export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number }
|
||||
|
||||
export interface SupervivenciaFigura {
|
||||
scenario: string;
|
||||
members: number;
|
||||
deaths: number;
|
||||
drawable: boolean;
|
||||
horizons: number[];
|
||||
months?: number[];
|
||||
km?: { S: number[]; lo: number[]; hi: number[] };
|
||||
curve_months?: number[];
|
||||
weibull?: { k: number; S: number[] };
|
||||
fractional?: { k: number; alpha: number; beta: number; S: number[] };
|
||||
points: SupervivenciaPunto[];
|
||||
}
|
||||
|
||||
export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] }
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
|
||||
|
||||
export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios {
|
||||
if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string')
|
||||
|| typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') {
|
||||
throw new Error('Respuesta de escenarios de supervivencia inválida');
|
||||
}
|
||||
return v as unknown as SupervivenciaEscenarios;
|
||||
}
|
||||
|
||||
export function supervivenciaFigura(v: unknown): SupervivenciaFigura {
|
||||
if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number'
|
||||
|| typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) {
|
||||
throw new Error('Respuesta de figura de supervivencia inválida');
|
||||
}
|
||||
if (v['drawable']) {
|
||||
const km = v['km'], w = v['weibull'], f = v['fractional'];
|
||||
if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi'])
|
||||
|| !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta');
|
||||
}
|
||||
return v as unknown as SupervivenciaFigura;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
:host { display: block; min-width: 0; --plot-height: 420px; }
|
||||
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
|
||||
.availability { margin: 0; }
|
||||
@@ -0,0 +1,20 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaSupervivenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios a patient belongs to, from her variables over the timeline. */
|
||||
escenarios(pacId: number) {
|
||||
return this.http.get<unknown>(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios));
|
||||
}
|
||||
|
||||
/** The figure of one scenario over the production model and the live cohort. */
|
||||
figura(escenario: string) {
|
||||
const params = new HttpParams().set('escenario', escenario);
|
||||
return this.http.get<unknown>('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { figuraSupervivencia } from './cama-supervivencia-figura';
|
||||
import { CamaSupervivenciaService } from './cama-supervivencia.service';
|
||||
|
||||
/**
|
||||
* A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in
|
||||
* production and the live cohort.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-supervivencia',
|
||||
imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './cama-supervivencia.html',
|
||||
styleUrl: './cama-supervivencia.scss',
|
||||
})
|
||||
export class CamaSupervivencia {
|
||||
readonly pacId = input.required<number>();
|
||||
readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando');
|
||||
readonly escenarios = signal<string[]>([]);
|
||||
readonly elegido = signal<string | null>(null);
|
||||
readonly figura = signal<PlotlyFigure | null>(null);
|
||||
readonly cargandoFigura = signal(false);
|
||||
readonly sinDibujo = signal<string | null>(null);
|
||||
private readonly servicio = inject(CamaSupervivenciaService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private pedido?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.cargar(this.pacId()));
|
||||
}
|
||||
|
||||
private cargar(pacId: number) {
|
||||
this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null);
|
||||
this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: respuesta => {
|
||||
this.escenarios.set(respuesta.scenarios);
|
||||
if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; }
|
||||
this.estado.set('listo');
|
||||
this.elegir(respuesta.scenarios[0]);
|
||||
},
|
||||
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
|
||||
});
|
||||
}
|
||||
|
||||
elegir(escenario: string) {
|
||||
this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true);
|
||||
this.pedido?.unsubscribe();
|
||||
this.pedido = this.servicio.figura(escenario).subscribe({
|
||||
next: f => {
|
||||
this.cargandoFigura.set(false);
|
||||
if (this.elegido() !== escenario) return;
|
||||
if (f.drawable) this.figura.set(figuraSupervivencia(f));
|
||||
else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`);
|
||||
},
|
||||
error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,33 +8,13 @@
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
|
||||
@if (lectura.datos.cohorte; as cohorte) {
|
||||
<h5>Cohorte</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
|
||||
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
|
||||
</dl>
|
||||
<details>
|
||||
<summary>Variables del modelo PIMM</summary>
|
||||
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
|
||||
<dl class="metadata">
|
||||
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
|
||||
</dl>
|
||||
</details>
|
||||
} @else {
|
||||
<p role="status">Sin membresía en la cohorte vigente.</p>
|
||||
}
|
||||
@if (lectura.datos.riesgo; as riesgo) {
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@@ -46,7 +26,6 @@
|
||||
<th scope="col">Horizonte (años)</th>
|
||||
<th scope="col">Probabilidad (%)</th>
|
||||
<th scope="col">Intervalo de confianza (%)</th>
|
||||
<th scope="col">Estado de evaluación</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (h of riesgo.horizontes; track h.horizonte_anios) {
|
||||
@@ -54,14 +33,12 @@
|
||||
<th scope="row">{{ h.horizonte_anios }}</th>
|
||||
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
|
||||
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
|
||||
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
|
||||
@@ -1,46 +1,39 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
|
||||
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
|
||||
|
||||
export interface CohorteRiesgoCacu {
|
||||
url: string;
|
||||
version: string;
|
||||
fecha_indice: string;
|
||||
tipo_censura: TipoCensuraCacu | null;
|
||||
c: number | null;
|
||||
l: number | null;
|
||||
r: number | null;
|
||||
pap_0: string | null;
|
||||
hpv_0: string | null;
|
||||
}
|
||||
|
||||
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;
|
||||
/** Transport values remain probabilities in [0, 1], never percentages. */
|
||||
probabilidad: number;
|
||||
ic_bajo?: number | null;
|
||||
ic_alto?: number | null;
|
||||
estado: EstadoEvaluacionCacu;
|
||||
}
|
||||
|
||||
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
|
||||
export interface LoteRiesgoCacu {
|
||||
lote_id: number;
|
||||
/** The resource's id, `<lote_id>-<pac_id>`. */
|
||||
id: string;
|
||||
modelo_nombre: string;
|
||||
modelo_version: string;
|
||||
/** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */
|
||||
fecha_indice: string;
|
||||
evaluado_en: string;
|
||||
estado_lote: EstadoEvaluacionCacu;
|
||||
/** The prediction's outcome code (e.g. `cin2_mas`) and its display. */
|
||||
desenlace: string;
|
||||
desenlace_texto: string | null;
|
||||
horizontes: HorizonteRiesgoCacu[];
|
||||
}
|
||||
|
||||
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
|
||||
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
cohorte: CohorteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu | null;
|
||||
riesgo: LoteRiesgoCacu;
|
||||
}
|
||||
|
||||
/** `null` when the patient has no risk data. */
|
||||
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
|
||||
export interface PacienteRiesgoProvider {
|
||||
obtener(pacId: string): Observable<unknown>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
|
||||
import { inject, InjectionToken } from '@angular/core';
|
||||
import { catchError, of, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
|
||||
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
|
||||
// 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.
|
||||
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
|
||||
providedIn: 'root', factory: () => {
|
||||
const http = inject(HttpClient);
|
||||
return {
|
||||
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
|
||||
obtener: (pacId: string) => http.get<unknown>('/cacu/fhir/RiskAssessment', {
|
||||
params: new HttpParams().set('subject', `Patient/${pacId}`),
|
||||
}).pipe(
|
||||
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
|
||||
),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import { of, Subject, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
@@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
|
||||
it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => {
|
||||
const f = setup(), root: HTMLElement = f.nativeElement;
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
|
||||
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42')
|
||||
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' });
|
||||
f.detectChanges();
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
@@ -33,27 +33,33 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
|
||||
it('un Bundle vacío es una paciente sin riesgo confirmado', () => {
|
||||
const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) });
|
||||
expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(f.nativeElement.querySelector('table')).toBeNull();
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => {
|
||||
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
|
||||
data.riesgo!.horizontes[1].estado = 'preliminary';
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(4);
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/);
|
||||
expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
|
||||
expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
|
||||
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
|
||||
// Internal batch key stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toContain('lote_id');
|
||||
// The resource id (batch and patient) stays in the contract, never in a UI label.
|
||||
expect(root.textContent).not.toMatch(/lote_id|12-42/);
|
||||
expect(data).toEqual(baseline);
|
||||
});
|
||||
|
||||
@@ -67,17 +73,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
|
||||
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
|
||||
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
|
||||
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
|
||||
expect(root.textContent).toContain('no constituyen un diagnóstico');
|
||||
});
|
||||
|
||||
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.riesgo!.estado_lote = 'preliminary';
|
||||
data.riesgo!.horizontes = [
|
||||
{ horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
|
||||
{ horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
|
||||
{ horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
|
||||
data.entry[0].resource.status = 'preliminary';
|
||||
data.entry[0].resource.prediction = [
|
||||
prediccion(0, '2026-06-01', '2026-12-01', [0, 0]),
|
||||
prediccion(1, '2026-06-01', '2034-06-01'),
|
||||
prediccion(0.00123, '2026-06-01', '2038-09-01'),
|
||||
];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
@@ -86,31 +90,9 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
|
||||
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
|
||||
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
|
||||
});
|
||||
|
||||
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
|
||||
const data = riesgoCacuEjemplo();
|
||||
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
|
||||
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
|
||||
if (caso === 'horizontes') data.riesgo!.horizontes = [];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
|
||||
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
|
||||
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
|
||||
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
|
||||
expect(root.textContent).toContain('Información simulada');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
|
||||
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
|
||||
const data = { ...riesgoCacuEjemplo(), simulado };
|
||||
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
|
||||
@@ -118,7 +100,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
});
|
||||
|
||||
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
|
||||
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
|
||||
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12;
|
||||
const f = setup({ obtener: () => of(data) });
|
||||
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
|
||||
@@ -134,14 +116,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
it('aísla estado y fixture entre instancias sin reutilizar información', () => {
|
||||
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
|
||||
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
|
||||
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
|
||||
data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
|
||||
f.destroy();
|
||||
const otra = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
|
||||
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
|
||||
expect(otra.nativeElement.querySelector('table')).toBeNull();
|
||||
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
|
||||
expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08);
|
||||
otra.destroy(); expect(source.observed).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ export class PacienteRiesgoState {
|
||||
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(
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
map((respuesta): PacienteRiesgoEstado => {
|
||||
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
|
||||
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
|
||||
}),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
startWith(CARGANDO),
|
||||
)),
|
||||
|
||||
@@ -1,20 +1,51 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
|
||||
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
|
||||
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
|
||||
return {
|
||||
outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] },
|
||||
probabilityDecimal: p, whenPeriod: { start: inicio, end: fin },
|
||||
...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as
|
||||
* `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */
|
||||
export function riesgoCacuEjemplo(): any {
|
||||
return {
|
||||
resourceType: 'Bundle', type: 'searchset', total: 1,
|
||||
entry: [{
|
||||
fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42',
|
||||
resource: {
|
||||
resourceType: 'RiskAssessment', id: '12-42', status: 'final',
|
||||
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
|
||||
subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z',
|
||||
method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] },
|
||||
prediction: [
|
||||
prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]),
|
||||
prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]),
|
||||
prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]),
|
||||
],
|
||||
},
|
||||
search: { mode: 'match' },
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
|
||||
export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
return {
|
||||
simulado: true,
|
||||
cohorte: {
|
||||
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
|
||||
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
|
||||
},
|
||||
riesgo: {
|
||||
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
|
||||
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
|
||||
horizontes: [
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
|
||||
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,121 +1,89 @@
|
||||
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { TipoCensuraCacu } from './paciente-riesgo.models';
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
|
||||
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
|
||||
const recurso = (v: any) => v.entry[0].resource;
|
||||
|
||||
describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => {
|
||||
it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
salida.riesgo!.horizontes[0].probabilidad = 0;
|
||||
salida.cohorte!.c = -999;
|
||||
const salida = riesgoPacienteResponse(entrada, '42')!;
|
||||
expect(salida).toEqual(riesgoCacuVista());
|
||||
salida.riesgo.horizontes[0].probabilidad = 0;
|
||||
expect(entrada).toEqual(riesgoCacuEjemplo());
|
||||
});
|
||||
|
||||
it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
|
||||
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => {
|
||||
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull();
|
||||
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
|
||||
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
|
||||
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
|
||||
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.riesgo = null;
|
||||
entrada.cohorte.c = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
|
||||
recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')];
|
||||
expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]);
|
||||
});
|
||||
|
||||
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
|
||||
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.cohorte = null;
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
recurso(entrada).prediction.reverse();
|
||||
recurso(entrada).note = [{ text: 'simulado' }];
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
|
||||
});
|
||||
|
||||
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
|
||||
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
|
||||
horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
|
||||
}));
|
||||
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
|
||||
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
|
||||
])('conserva IC incompletos sin generar límites: %j', limites => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
|
||||
const p = recurso(entrada).prediction[0];
|
||||
if (ext === undefined) delete p.extension; else p.extension = ext;
|
||||
const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0];
|
||||
expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]);
|
||||
expect(tieneIntervalo(h)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
|
||||
const entrada = riesgoCacuEjemplo();
|
||||
entrada.riesgo!.estado_lote = 'preliminary';
|
||||
entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
|
||||
const salida = riesgoPacienteResponse(entrada);
|
||||
expect(salida).toEqual(entrada);
|
||||
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
|
||||
recurso(entrada).status = 'preliminary';
|
||||
recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])];
|
||||
const salida = riesgoPacienteResponse(entrada)!;
|
||||
expect(salida.riesgo.estado_lote).toBe('preliminary');
|
||||
expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p });
|
||||
expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true);
|
||||
});
|
||||
|
||||
const invalidos: [string, (v: any) => void][] = [
|
||||
['no simulado', v => v.simulado = false],
|
||||
['simulado string', v => v.simulado = 'true'],
|
||||
['sin simulado', v => delete v.simulado],
|
||||
['sin cohorte', v => delete v.cohorte],
|
||||
['sin riesgo', v => delete v.riesgo],
|
||||
['cohorte lista', v => v.cohorte = []],
|
||||
['URL ajena', v => v.cohorte.url = 'otra'],
|
||||
['versión ausente', v => delete v.cohorte.version],
|
||||
['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
|
||||
['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
|
||||
['basal string', v => v.cohorte.c = '0'],
|
||||
['variable no finita', v => v.cohorte.l = Infinity],
|
||||
['variable omitida', v => delete v.cohorte.r],
|
||||
['pap no textual', v => v.cohorte.pap_0 = 5],
|
||||
['hpv no textual', v => v.cohorte.hpv_0 = false],
|
||||
['lote fraccionario', v => v.riesgo.lote_id = 1.5],
|
||||
['lote string', v => v.riesgo.lote_id = '12'],
|
||||
['modelo omitido', v => delete v.riesgo.modelo_nombre],
|
||||
['versión no textual', v => v.riesgo.modelo_version = 2],
|
||||
['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
|
||||
['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
|
||||
['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
|
||||
['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
|
||||
['sin horizontes', v => delete v.riesgo.horizontes],
|
||||
['horizontes nulos', v => v.riesgo.horizontes = null],
|
||||
['horizonte nulo', v => v.riesgo.horizontes[0] = null],
|
||||
['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
|
||||
['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
|
||||
['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
|
||||
['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
|
||||
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
|
||||
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
|
||||
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
|
||||
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
|
||||
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
|
||||
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
|
||||
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
|
||||
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
|
||||
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
|
||||
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
|
||||
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
|
||||
['no es Bundle', v => v.resourceType = 'RiskAssessment'],
|
||||
['Bundle no searchset', v => v.type = 'collection'],
|
||||
['sin total', v => delete v.total],
|
||||
['entry no lista', v => v.entry = {}],
|
||||
['recurso ajeno', v => recurso(v).resourceType = 'Observation'],
|
||||
['no simulado', v => delete recurso(v).meta],
|
||||
['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'],
|
||||
['sin id', v => delete recurso(v).id],
|
||||
['estado desconocido', v => recurso(v).status = 'amended'],
|
||||
['estado anulado', v => recurso(v).status = 'entered-in-error'],
|
||||
['otra paciente', v => recurso(v).subject.reference = 'Patient/43'],
|
||||
['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'],
|
||||
['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'],
|
||||
['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'],
|
||||
['sin modelo', v => delete recurso(v).method],
|
||||
['modelo sin versión', v => delete recurso(v).method.coding[0].version],
|
||||
['sin predicciones', v => recurso(v).prediction = []],
|
||||
['predicción nula', v => recurso(v).prediction[0] = null],
|
||||
['sin desenlace', v => delete recurso(v).prediction[0].outcome],
|
||||
['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'],
|
||||
['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01],
|
||||
['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01],
|
||||
['sin periodo', v => delete recurso(v).prediction[0].whenPeriod],
|
||||
['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'],
|
||||
['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'],
|
||||
['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'],
|
||||
['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'],
|
||||
['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }],
|
||||
['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07],
|
||||
['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'],
|
||||
];
|
||||
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
|
||||
const entrada = riesgoCacuEjemplo(); mutar(entrada);
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida');
|
||||
});
|
||||
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
|
||||
expect(() => riesgoPacienteResponse(entrada)).toThrow();
|
||||
|
||||
@@ -1,54 +1,104 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
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 nullableNumber = (v: unknown) => v === null || finite(v);
|
||||
const nullableText = (v: unknown) => v === null || typeof v === 'string';
|
||||
const text = (v: unknown) => typeof v === 'string';
|
||||
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final';
|
||||
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
|
||||
const DAYS_PER_YEAR = 365.25;
|
||||
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
const SIMULATED = 'simulado';
|
||||
|
||||
function utcTimestamp(v: unknown) {
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
return typeof v === 'string'
|
||||
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
|
||||
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
|
||||
}
|
||||
|
||||
function cohorteValida(v: unknown) {
|
||||
return v === null || record(v)
|
||||
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
|
||||
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
|
||||
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
|
||||
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
|
||||
function invalid(): never {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
|
||||
function horizonteValido(v: unknown) {
|
||||
if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
|
||||
for (const key of ['ic_bajo', 'ic_alto']) {
|
||||
if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
|
||||
/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */
|
||||
function years(start: string, end: string): number {
|
||||
const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000;
|
||||
return Math.round(days / DAYS_PER_YEAR * 100) / 100;
|
||||
}
|
||||
|
||||
function interval(prediction: Record<string, unknown>): { ic_bajo: number | null; ic_alto: number | null } {
|
||||
const extensions = prediction['extension'];
|
||||
if (extensions === undefined) return { ic_bajo: null, ic_alto: null };
|
||||
if (!Array.isArray(extensions)) invalid();
|
||||
const found = extensions.find(e => record(e) && e['url'] === INTERVAL);
|
||||
if (found === undefined) return { ic_bajo: null, ic_alto: null };
|
||||
const range = found['valueRange'];
|
||||
const low = record(range) && record(range['low']) ? range['low']['value'] : undefined;
|
||||
const high = record(range) && record(range['high']) ? range['high']['value'] : undefined;
|
||||
if (!probability(low) || !probability(high) || low > high) invalid();
|
||||
return { ic_bajo: low, ic_alto: high };
|
||||
}
|
||||
|
||||
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
|
||||
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
|
||||
const period = prediction['whenPeriod'];
|
||||
if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid();
|
||||
const from = period['start'] as string, to = period['end'] as string;
|
||||
if (start !== undefined && from !== start) invalid(); // one index date per patient
|
||||
const h = years(from, to);
|
||||
if (h < 0) invalid();
|
||||
const ic = interval(prediction);
|
||||
const p = prediction['probabilityDecimal'];
|
||||
if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid();
|
||||
return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from };
|
||||
}
|
||||
|
||||
function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status'])
|
||||
|| !utcTimestamp(v['occurrenceDateTime'])) invalid();
|
||||
const subject = v['subject'];
|
||||
if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/')
|
||||
|| (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid();
|
||||
const method = v['method'];
|
||||
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
|
||||
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
|
||||
const predictions = v['prediction'];
|
||||
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
|
||||
let start: string | undefined;
|
||||
const horizontes: HorizonteRiesgoCacu[] = [];
|
||||
for (const prediction of predictions) {
|
||||
const found = horizon(prediction, start);
|
||||
start = found.start;
|
||||
horizontes.push(found.horizonte);
|
||||
}
|
||||
// Missing/null endpoints are preserved. A complete interval must contain the probability.
|
||||
return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
|
||||
|| v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
|
||||
horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios);
|
||||
if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid();
|
||||
const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding'])
|
||||
? predictions[0]['outcome']['coding'][0] : undefined;
|
||||
if (!record(outcome) || !text(outcome['code'])) invalid();
|
||||
return {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
|
||||
horizontes,
|
||||
};
|
||||
}
|
||||
|
||||
function riesgoValido(v: unknown) {
|
||||
if (v === null) return true;
|
||||
if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|
||||
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
|
||||
const horizontes = v['horizontes'];
|
||||
return horizontes.every(horizonteValido)
|
||||
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
|
||||
function simulated(resource: Record<string, unknown>): boolean {
|
||||
const meta = resource['meta'];
|
||||
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
|
||||
}
|
||||
|
||||
/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
|
||||
export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
|
||||
if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
|
||||
throw new Error('Respuesta de riesgo individual DEV inválida');
|
||||
}
|
||||
return structuredClone(v) as unknown as RiesgoPacienteCacu;
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only).
|
||||
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */
|
||||
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
|
||||
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
|
||||
const entries = v['entry'] ?? [];
|
||||
if (!Array.isArray(entries)) invalid();
|
||||
if (entries.length === 0) return null;
|
||||
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
|
||||
Reference in New Issue
Block a user