import { isoDate } from '../cacu-seguimiento.models'; import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice, RiesgoPacienteCacu } from './paciente-riesgo.models'; 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 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'; const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph']; const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit']; 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): { 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 }; } /** The resource's extension `url` as its known `keys` with a text value; `null` without that extension. */ function stringExtension(resource: Record, url: string, keys: readonly K[]): Partial> | null { const extensions = resource['extension']; if (extensions === undefined) return null; if (!Array.isArray(extensions)) invalid(); const found = extensions.find(e => record(e) && e['url'] === url); if (found === undefined) return null; if (!Array.isArray(found['extension'])) invalid(); const result: Partial> = {}; for (const item of found['extension']) { if (!record(item) || !text(item['url'])) invalid(); const key = item['url'] as K; if (keys.includes(key) && text(item['valueString'])) result[key] = item['valueString']; } return result; } const estimand = (resource: Record): EstimandoRiesgo | null => stringExtension(resource, ESTIMAND, ESTIMAND_KEYS); /** The `sin-estimacion` extension: the outcome of a current model that didn't score her, and why; `null` without it. */ function notScoredOutcome(resource: Record): { desenlace: string; motivo: string } | null { const extensions = resource['extension']; if (!Array.isArray(extensions)) return null; const found = extensions.find(e => record(e) && e['url'] === NOT_SCORED); if (found === undefined) return null; const items = Array.isArray(found['extension']) ? found['extension'].filter(record) : invalid(); const desenlace = items.find(i => i['url'] === 'desenlace')?.['valueCode']; const motivo = items.find(i => i['url'] === 'motivo')?.['valueString']; if (!text(desenlace)) invalid(); return { desenlace, motivo: text(motivo) ? motivo : 'el modelo no estima a esta paciente' }; } 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 notScored = notScoredOutcome(v); if (notScored !== null && v['prediction'] === undefined) { return { id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, fecha_indice: '', evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', desenlace: notScored.desenlace, desenlace_texto: null, horizontes: [], estimando: estimand(v), resultados_indice: null, sin_estimacion: notScored.motivo, }; } 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, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS), sin_estimacion: null, }; } function simulated(resource: Record): boolean { const meta = resource['meta']; return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); } /** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */ export function ordenDesenlace(desenlace: string): number { return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2; } /** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`s, one per outcome, each tagged * `simulado` (DEV only), and one with no prediction for a current model that didn't score her. `riesgo` is the first * that has a risk. `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 riesgos = entries.map(entry => { const resource = record(entry) ? entry['resource'] : undefined; if (!record(resource) || !simulated(resource)) invalid(); return riskAssessment(structuredClone(resource), pacId); }); riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace)); return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos }; } /** 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; }