00f773dd75
The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> and validates the searchset Bundle at the boundary (simulado tag, the patient asked for, one index date, probabilities and intervals); it shows the model, the risk's index date, the outcome, the evaluation and one row per horizon from each prediction's whenPeriod. The cohort's definition and the PIMM variables are no longer shown; an empty Bundle is a patient without a confirmed risk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
109 lines
6.0 KiB
TypeScript
109 lines
6.0 KiB
TypeScript
import { isoDate } from '../cacu-seguimiento.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 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 DAYS_PER_YEAR = 365.25;
|
|
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
|
const SIMULATED = 'simulado';
|
|
|
|
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 invalid(): never {
|
|
throw new Error('Respuesta de riesgo individual DEV inválida');
|
|
}
|
|
|
|
/** 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);
|
|
}
|
|
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 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: 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. */
|
|
export function tieneIntervalo(h: HorizonteRiesgoCacu): boolean {
|
|
return probability(h.ic_bajo) && probability(h.ic_alto)
|
|
&& h.ic_bajo <= h.probabilidad && h.probabilidad <= h.ic_alto;
|
|
}
|