import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { catchError, map, Observable, of, throwError } from 'rxjs'; // The cohort's survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the // model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the // version they come from and says when the data are simulated. A 404 is "no model in production yet". export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; } export interface CurvasSupervivencia { escenario?: string; n: number; events: number; median_follow_up_months: number; horizons_months: number[]; months_max: number; bootstrap_replicas: number; km: { months: number[]; S: number[]; low: number[]; high: number[] }; km_adjusted: { months: number[]; S: number[] }; weibull: { t: number[]; S: number[] }; weibull_fractional: { t: number[]; S: number[] }; points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia }; etiquetas: Record; } export interface RespuestaCurvas { modelo: { nombre: string; version: string }; curvas: CurvasSupervivencia; } const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length); const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1); const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; function invalid(): never { throw new Error('Respuesta de curvas de supervivencia inválida'); } function serie(v: unknown, horizons: number): SerieDeSupervivencia { if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid(); const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[]; if (low.some((l, i) => l > high[i])) invalid(); return { S: s, low, high }; } /** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */ export function respuestaCurvas(v: unknown): RespuestaCurvas { if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid(); const m = v['modelo'] as Record, c = v['curvas'] as Record; if (!text(m['nombre']) || !text(m['version'])) invalid(); const horizons = c['horizons_months']; if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events']) || !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid(); const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points']; if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length) || !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid(); if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid(); for (const curve of [weibull, fractional]) { if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid(); } if (!record(points)) invalid(); const p = points as Record, h = (horizons as number[]).length; const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record : {}; return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, curvas: { escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined, n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number, horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number, km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'], weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'], points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas, }, }; } /** 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; 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 }[]; 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. */ export class SeleccionRechazada extends Error {} @Injectable({ providedIn: 'root' }) export class CamaCurvasService { private readonly http = inject(HttpClient); /** 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 { return this.http.get('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe( map(r => { if (!record(r) || !Array.isArray(r['escenarios'])) invalid(); 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)), ); } /** 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 { return this.http.post('/cama/modelo/curvas/consulta', { escenario }).pipe( 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)), ); } }