From 00f773dd75396699c4a93d8c9525801d2db37ac5 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 23:11:56 -0600 Subject: [PATCH] CaCu patient record reads the patient's FHIR RiskAssessment The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/ 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 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- .../paciente-riesgo-tabla.html | 29 +--- .../paciente-riesgo.models.ts | 33 ++-- .../paciente-riesgo.provider.ts | 9 +- .../paciente-detalle/paciente-riesgo.spec.ts | 74 +++------ .../paciente-detalle/paciente-riesgo.state.ts | 6 +- .../paciente-riesgo.testing.ts | 53 ++++-- .../paciente-riesgo.validation.spec.ts | 156 +++++++----------- .../paciente-riesgo.validation.ts | 117 +++++++++---- 8 files changed, 238 insertions(+), 239 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index a2c33dc..0cf617b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -8,33 +8,13 @@ @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') {

Información simulada · Entorno DEV · Sin evaluación clínica

- @if (lectura.datos.cohorte; as cohorte) { -
Cohorte
- -
- Variables del modelo PIMM -

Códigos técnicos del modelo; no constituyen un diagnóstico.

- -
- } @else { -

Sin membresía en la cohorte vigente.

- } - @if (lectura.datos.riesgo; as riesgo) { + @let riesgo = lectura.datos.riesgo;
Modelo y evaluación
@@ -46,7 +26,6 @@ Horizonte (años) Probabilidad (%) Intervalo de confianza (%) - Estado de evaluación @for (h of riesgo.horizontes; track h.horizonte_anios) { @@ -54,14 +33,12 @@ {{ h.horizonte_anios }} {{ h.probabilidad * 100 | number:'1.0-4' }} % @if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible } - {{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }} } } @else {

Sin horizontes evaluados en el lote vigente.

} - } @else {

Sin riesgo disponible: no hay lote vigente.

} } }

Recomendaciones no disponibles.

diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index f1eb19d..dd56a2c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -1,48 +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/`). */ export interface LoteRiesgoCacu { - lote_id: number; + /** The resource's id, `-`. */ + id: string; modelo_nombre: string; modelo_version: string; - /** The model's index date for this patient (ISO date): the horizons count from it. Absent from older APIs. */ - fecha_indice?: string | null; + /** 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; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 0749c29..5b4cf95 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -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/`, 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', { providedIn: 'root', factory: () => { const http = inject(HttpClient); return { - obtener: (pacId: string) => http.get(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe( + obtener: (pacId: string) => http.get('/cacu/fhir/RiskAssessment', { + params: new HttpParams().set('subject', `Patient/${pacId}`), + }).pipe( catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), ), }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 56d0b02..76caafc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -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,29 +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', '2026-06-01', '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 index date shown is the risk's (the model's decision point), not the cohort member's. - expect(root.textContent).not.toContain('2023-04-15'); + // 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); }); @@ -69,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']); @@ -88,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'); @@ -120,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); @@ -136,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(), 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); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index b5a08d5..3a5ed61 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -14,8 +14,10 @@ export class PacienteRiesgoState { readonly pacId = signal(undefined); readonly estado = toSignal(toObservable(this.pacId).pipe( switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of({ 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({ tipo: 'error' })), startWith(CARGANDO), )), diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index ecf05cf..2344b80 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -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', fecha_indice: '2026-06-01', - 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 }, ], }, }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts index fbc8b28..238a9ec 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts @@ -1,123 +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], - ['fecha índice del riesgo inválida', v => v.riesgo.fecha_indice = '2026-02-30'], - ['fecha índice del riesgo no textual', v => v.riesgo.fecha_indice = 20260601], - ['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(); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index a920048..dbbade0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -1,55 +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 => !!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): { 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; - if (Object.hasOwn(v, 'fecha_indice') && v['fecha_indice'] !== null && !isoDate(v['fecha_indice'])) 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): 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. */