diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts
index b783757..ecd3f67 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts
+++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts
@@ -9,6 +9,8 @@ import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.models';
import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider';
import { PacienteDetalleState } from './paciente-detalle.state';
+import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
+import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
const pacientes = seguimientoResponse(fixtureData).items;
@@ -145,8 +147,9 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
expect(Array.from(detail.querySelectorAll('.history-card button'), button => button.textContent?.trim())).toEqual(['Agregar condición', 'Agregar procedimiento']);
expect(detail.querySelector('.history-card')!.compareDocumentPosition(detail.querySelector('.tests-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(detail.querySelector('.tests-card')!.compareDocumentPosition(detail.querySelector('.risks-card')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- expect(detail.textContent).toContain('Valores ilustrativos · Sin evaluación clínica');
- expect(detail.querySelectorAll('app-paciente-riesgo-tabla tbody tr')).toHaveLength(4);
+ expect(detail.textContent).toContain('Riesgo individual no disponible para esta paciente.');
+ expect(detail.querySelectorAll('app-paciente-riesgo-tabla table')).toHaveLength(0);
+ expect(detail.textContent).not.toContain('Valores ilustrativos');
volver();
expect(root.querySelector('app-paciente-detalle')).toBeNull();
expect(root.querySelector('form')!.closest('[hidden]')).toBeNull();
@@ -201,7 +204,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
it('muestra ausencia de ficha sin asignar a otro paciente los antecedentes anteriores', () => {
expect(abrir().textContent).toContain('Antecedente de tamizaje cervical');
- const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent;
+ const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
volver();
const detail = abrir(2);
expect(detail.textContent).toContain(pacientes[2].id_seudonimo);
@@ -211,7 +214,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
expect(detail.textContent).not.toContain('Colposcopia (demostración)');
expect(detail.textContent).toContain('Normal'); // Received study is still available.
expect(detail.textContent).not.toContain('ficha sintética');
- expect(detail.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa);
+ expect(detail.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
+ expect(detail.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
expect(detail.querySelectorAll('app-paciente-riesgo-tabla [aria-selected]')).toHaveLength(0);
http.expectNone(() => true);
});
@@ -234,6 +238,24 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
http.expectNone(() => true);
});
+ it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => {
+ const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
+ const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
+ try {
+ const detail = abrir();
+ const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!;
+ expect(tarjeta.textContent).toContain('Información simulada');
+ expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
+ expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
+ expect(obtener).toHaveBeenCalledExactlyOnceWith();
+ volver();
+ const otra = abrir(1);
+ expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
+ expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
+ http.expectNone(() => true);
+ } finally { obtener.mockRestore(); }
+ });
+
it('distingue fuentes, nulos, falsos, ceros y listas sin registros sin inferir condiciones', () => {
let detail = abrir();
expect(detail.textContent).toContain('Últimos resultados');
diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts
index 94fa339..dfdb390 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts
+++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts
@@ -218,8 +218,9 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => {
abrir(2);
- const tablaIlustrativa = root.querySelector('app-paciente-riesgo-tabla table')!.textContent;
- expect(root.querySelectorAll('app-paciente-riesgo-tabla thead th')).toHaveLength(6);
+ const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
+ expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
+ expect(riesgoNoDisponible).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('Información no disponible');
for (const tipo of acciones) {
const { ref } = await abrirDialogo(tipo.texto);
@@ -230,7 +231,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
await confirmar();
}
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
- expect(root.querySelector('app-paciente-riesgo-tabla table')!.textContent).toBe(tablaIlustrativa);
+ expect(root.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
expect(root.textContent).toContain('Recomendaciones no disponibles');
volver(); abrir(0);
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0);
@@ -257,7 +258,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
expect(root.textContent).toContain('Último resultado de VPH');
expect(root.textContent).toContain('NEGATIVO');
expect(root.textContent).toContain('VPH 16/18 detectado');
- expect(root.textContent).toContain('Valores ilustrativos · Sin evaluación clínica');
+ expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
+ expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
http.expectNone(() => true);
});
});
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 49cfa6b..a5e3c7e 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html
@@ -1,37 +1,68 @@
-
Estimaciones de riesgo
-Valores ilustrativos · Sin evaluación clínica
+Riesgo individual CaCu
@let lectura = estado();
@switch (lectura.tipo) {
- @case ('cargando') { Cargando estimaciones de riesgo…
}
- @case ('vacio') { Sin estimaciones de riesgo disponibles.
}
- @case ('no-disponible') { Estimaciones de riesgo no disponibles.
}
- @case ('error') { No se pudieron cargar las estimaciones de riesgo.
}
+ @case ('cargando') { Cargando riesgo individual…
}
+ @case ('no-disponible') {
+ Riesgo individual no disponible para esta paciente.
+ La consulta de riesgo individual aún no está habilitada.
+ }
+ @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
+
+ - Definición de cohorte
- {{ cohorte.url }}
+ - Versión de cohorte
- {{ cohorte.version }}
+ - Fecha índice
- {{ cohorte.fecha_indice }}
+
+
+ Variables del modelo PIMM
+ Códigos técnicos del modelo; no constituyen un diagnóstico.
+
+ - tipo_censura
- {{ cohorte.tipo_censura ?? 'No disponible' }}
+ - c (estado basal)
- {{ cohorte.c ?? 'No disponible' }}
+ - l (años desde índice)
- {{ cohorte.l ?? 'No disponible' }}
+ - r (años desde índice)
- {{ cohorte.r ?? 'No disponible' }}
+ - pap_0 (citología índice)
- {{ cohorte.pap_0 ?? 'No disponible' }}
+ - hpv_0 (VPH índice)
- {{ cohorte.hpv_0 ?? 'No disponible' }}
+
+
+ } @else {
+ Sin membresía en la cohorte vigente.
+ }
+ @if (lectura.datos.riesgo; as riesgo) {
+ Modelo y evaluación
+
+ - Modelo
- {{ riesgo.modelo_nombre }}
+ - Versión del modelo
- {{ riesgo.modelo_version }}
+ - Evaluado en (UTC)
- {{ riesgo.evaluado_en }}
+ - Estado del lote
- {{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}
+
+ @if (riesgo.horizontes.length) {
+
+ } @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-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss
index b5b49a3..90a76f3 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss
@@ -1,15 +1,20 @@
:host { display: block; min-width: 0; max-width: 100%; }
h4 { margin-block: 0 .5rem; font-size: 1.05rem; }
-.illustrative-label, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; }
+h5 { margin-block: 1rem .5rem; font-size: 1rem; }
+.simulated-label { border-inline-start: 3px solid var(--issste-accent); padding: .75rem; font-weight: 600; }
+.availability, .recommendations { color: var(--issste-text-secondary); font-size: .9rem; margin-block: .5rem 1rem; }
+.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr)); gap: 1rem; }
+.metadata div { min-width: 0; }
+dt { color: var(--issste-text-secondary); font-size: .9rem; }
+dd { margin: .3rem 0 0; overflow-wrap: anywhere; }
+summary { cursor: pointer; padding-block: .75rem; }
.risk-scroll { width: 100%; min-width: 0; max-width: 100%; max-height: 28rem; overflow: auto;
border: 1px solid var(--issste-border); border-radius: .5rem; box-sizing: border-box; }
-.risk-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
-table { width: 100%; min-width: 58rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; }
+.risk-scroll:focus-visible, summary:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
+table { width: 100%; min-width: 36rem; border-collapse: separate; border-spacing: 0; text-align: start; font-size: .9rem; }
caption { text-align: start; padding: .75rem; color: var(--issste-text-secondary); }
-th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: break-word; }
-th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; }
-th:nth-child(-n+2) { min-width: 10rem; }
-th:nth-child(n+3) { min-width: 7rem; }
-td { background: var(--issste-surface); }
-tbody tr:last-child td { border-bottom: 0; }
-.percentage { font-variant-numeric: tabular-nums; white-space: nowrap; }
+th, td { padding: .85rem .75rem; vertical-align: top; border-bottom: 1px solid var(--issste-border); overflow-wrap: anywhere; }
+thead th { position: sticky; top: 0; background: var(--issste-background, var(--issste-surface)); font-weight: 600; z-index: 1; }
+tbody th, td { background: var(--issste-surface); }
+tbody tr:last-child > * { border-bottom: 0; }
+.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; }
diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts
index 065729e..ed650ff 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts
@@ -1,6 +1,7 @@
import { Component, inject } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { PacienteRiesgoState } from './paciente-riesgo.state';
+import { tieneIntervalo } from './paciente-riesgo.validation';
@Component({
selector: 'app-paciente-riesgo-tabla',
@@ -11,4 +12,5 @@ import { PacienteRiesgoState } from './paciente-riesgo.state';
})
export class PacienteRiesgoTabla {
readonly estado = inject(PacienteRiesgoState).estado;
+ readonly tieneIntervalo = tieneIntervalo;
}
diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts
deleted file mode 100644
index ef5e3bc..0000000
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.fixtures.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { EstimacionesRiesgo } from './paciente-riesgo.models';
-
-/** Invented values for layout only. Not copied from CCSM, validated or patient-derived. */
-export const ESTIMACIONES_RIESGO_ILUSTRATIVAS: EstimacionesRiesgo = {
- origen: 'ilustrativo',
- filas: [
- { id: 'ejemplo-1', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa',
- resultadoVphActual: 'Positivo', citologiaActual: 'ASC-US / LSIL', riesgoInmediatoPorcentaje: 2.4, riesgoCin3A5AnosPorcentaje: 6.8 },
- { id: 'ejemplo-2', antecedentesPrecolposcopia: 'Bajo grado', antecedentesPoscolposcopia: 'Prueba conjunta negativa',
- resultadoVphActual: 'Positivo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.8, riesgoCin3A5AnosPorcentaje: 3.2 },
- { id: 'ejemplo-3', antecedentesPrecolposcopia: 'Sin información de ejemplo', antecedentesPoscolposcopia: 'Sin información de ejemplo',
- resultadoVphActual: 'Negativo', citologiaActual: 'NILM', riesgoInmediatoPorcentaje: 0.2, riesgoCin3A5AnosPorcentaje: 0.9 },
- { id: 'ejemplo-4', antecedentesPrecolposcopia: 'Alto grado', antecedentesPoscolposcopia: 'Control de ejemplo',
- resultadoVphActual: 'Positivo', citologiaActual: 'Alto grado', riesgoInmediatoPorcentaje: 7.6, riesgoCin3A5AnosPorcentaje: 12.4 },
- ],
-};
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 84c738b..832a217 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts
@@ -1,23 +1,50 @@
import { Observable } from 'rxjs';
-/** Presentation model, not a WebApi contract or a clinical decision rule. */
-export interface EstimacionRiesgo {
- id: string;
- antecedentesPrecolposcopia: string;
- antecedentesPoscolposcopia: string;
- resultadoVphActual: string;
- citologiaActual: string;
- riesgoInmediatoPorcentaje: number | null;
- riesgoCin3A5AnosPorcentaje: number | null;
+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 EstimacionesRiesgo {
- origen: 'ilustrativo';
- filas: readonly EstimacionRiesgo[];
+
+export interface HorizonteRiesgoCacu {
+ horizonte_anios: number;
+ /** Transport values remain probabilities in [0, 1], never percentages. */
+ probabilidad: number;
+ ic_bajo?: number | null;
+ ic_alto?: number | null;
+ estado: EstadoEvaluacionCacu;
}
-/** No patient input: these examples must never be matched to a selected patient. */
+
+export interface LoteRiesgoCacu {
+ lote_id: number;
+ modelo_nombre: string;
+ modelo_version: string;
+ evaluado_en: string;
+ estado_lote: EstadoEvaluacionCacu;
+ horizontes: HorizonteRiesgoCacu[];
+}
+
+/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
+export interface RiesgoPacienteCacu {
+ simulado: true;
+ cohorte: CohorteRiesgoCacu | null;
+ riesgo: LoteRiesgoCacu | null;
+}
+
+/** Deliberately no patient argument until secure identity resolution is authorized. */
export interface PacienteRiesgoProvider {
- obtener(): Observable;
+ obtener(): Observable;
}
+
export type PacienteRiesgoEstado =
- | { tipo: 'cargando' | 'vacio' | 'no-disponible' | 'error' }
- | { tipo: 'disponible'; datos: EstimacionesRiesgo };
+ | { tipo: 'cargando' | 'no-disponible' | 'error' }
+ | { tipo: 'disponible'; datos: RiesgoPacienteCacu };
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 16b95b8..c04a30a 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,8 @@
-import { Injectable, InjectionToken, inject } from '@angular/core';
-import { defer, of } from 'rxjs';
-import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures';
+import { InjectionToken } from '@angular/core';
+import { of } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
-@Injectable({ providedIn: 'root' })
-export class PacienteRiesgoIlustrativoProvider implements PacienteRiesgoProvider {
- obtener() { return defer(() => of(structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS))); }
-}
-
-// Future adapters can replace this token; no HTTP route or patient matching is assumed.
+// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', {
- providedIn: 'root', factory: () => inject(PacienteRiesgoIlustrativoProvider),
+ providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
});
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 affe99c..1cee25a 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts
@@ -2,26 +2,12 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { of, Subject, throwError } from 'rxjs';
-import { ESTIMACIONES_RIESGO_ILUSTRATIVAS } from './paciente-riesgo.fixtures';
-import { EstimacionesRiesgo, PacienteRiesgoProvider } from './paciente-riesgo.models';
-import { PACIENTE_RIESGO_PROVIDER, PacienteRiesgoIlustrativoProvider } from './paciente-riesgo.provider';
+import { PacienteRiesgoProvider } from './paciente-riesgo.models';
+import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
+import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
-describe('P0-C.2: proveedor ilustrativo independiente', () => {
- it('lee sin HttpClient ni paciente y devuelve copias independientes del fixture', () => {
- const provider = TestBed.inject(PacienteRiesgoIlustrativoProvider);
- const baseline = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS);
- provider.obtener().subscribe(data => {
- expect(data).toEqual(baseline);
- data.filas[0].riesgoInmediatoPorcentaje = 99;
- });
- provider.obtener().subscribe(data => expect(data).toEqual(baseline));
- expect(ESTIMACIONES_RIESGO_ILUSTRATIVAS).toEqual(baseline);
- expect(baseline.filas).toHaveLength(4);
- });
-});
-
-describe('P0-C.2: tabla accesible y estados de lectura', () => {
+describe('RIESGO-CACU-02: presentación y aislamiento', () => {
function setup(provider?: PacienteRiesgoProvider) {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
@@ -29,67 +15,137 @@ describe('P0-C.2: tabla accesible y estados de lectura', () => {
fixture.detectChanges();
return fixture;
}
- afterEach(() => { TestBed.inject(HttpTestingController).verify(); });
- it('renderiza seis encabezados, cuatro filas sin selección y porcentajes solo ilustrativos', () => {
- const f = setup(), root: HTMLElement = f.nativeElement;
- expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).toEqual([
- 'Antecedentes precolposcopia', 'Antecedentes poscolposcopia', 'Resultado VPH actual', 'Citología actual',
- 'Riesgo inmediato CIN3+ (%)', 'Riesgo CIN3+ a 5 años (%)',
- ]);
- expect([...root.querySelectorAll('th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
- expect(root.querySelectorAll('tbody tr')).toHaveLength(4);
- expect(root.querySelectorAll('tbody td')).toHaveLength(24);
- expect(root.querySelector('caption')!.textContent).toContain('ilustrativos');
- expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-ilustrativo');
- expect(root.querySelector('#riesgo-ilustrativo')!.textContent).toBe('Valores ilustrativos · Sin evaluación clínica');
- expect(root.querySelectorAll('[aria-selected], button, a, input')).toHaveLength(0);
- expect([...root.querySelectorAll('.percentage')].every(td => td.textContent!.trim().endsWith('%'))).toBe(true);
- expect(root.textContent).toContain('Recomendaciones no disponibles');
+ afterEach(() => {
TestBed.inject(HttpTestingController).expectNone(() => true);
+ TestBed.inject(HttpTestingController).verify();
});
- it('contiene el desplazamiento y conserva anchos mínimos y encabezados, con foco de teclado', () => {
+
+ it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
const f = setup(), root: HTMLElement = f.nativeElement;
+ expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
+ expect(root.textContent).toContain('aún no está habilitada');
+ expect(root.textContent).toContain('Recomendaciones no disponibles');
+ expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/);
+ expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
+ TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull());
+ });
+
+ it('renderiza el ejemplo contractual, estados, 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();
+ expect(root.querySelectorAll('thead th')).toHaveLength(4);
+ 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']) {
+ expect(root.textContent).toContain(value);
+ }
+ 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');
+ expect(data).toEqual(baseline);
+ });
+
+ it('mantiene tabla desplazable, foco de teclado y detalles técnicos accesibles', () => {
+ const f = setup({ obtener: () => of(riesgoCacuEjemplo()) }), root: HTMLElement = f.nativeElement;
const scroll = root.querySelector('.risk-scroll')!;
- expect(scroll.tabIndex).toBe(0); expect(scroll.getAttribute('role')).toBe('region');
+ expect(scroll.tabIndex).toBe(0);
+ expect(scroll.getAttribute('role')).toBe('region');
expect(scroll.getAttribute('aria-label')).toContain('tabla desplazable');
- // jsdom verifies the responsive CSS contract; viewport geometry still needs Chrome review.
expect(getComputedStyle(scroll).overflow).toBe('auto');
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
- expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('58rem');
- expect(getComputedStyle(root.querySelector('th')!).position).toBe('sticky');
+ 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('sustituye el fixture por inyección sin calcular porcentajes ni convertir null en cero', () => {
- const data = structuredClone(ESTIMACIONES_RIESGO_ILUSTRATIVAS);
- data.filas = [{ ...data.filas[0], riesgoInmediatoPorcentaje: 0, riesgoCin3A5AnosPorcentaje: null }];
- const obtener = vi.fn(() => of(data)), f = setup({ obtener });
- expect(obtener).toHaveBeenCalledExactlyOnceWith();
- const cells = [...f.nativeElement.querySelectorAll('.percentage')] as HTMLElement[];
- expect(cells.map(c => c.textContent)).toEqual(['0.0 %', 'No disponible']);
- TestBed.inject(HttpTestingController).expectNone(() => true);
+
+ 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' },
+ ];
+ 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']);
+ expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
+ expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']);
+ expect(root.textContent).toContain('Preliminar (preliminary)');
});
- it.each([
- { data: { origen: 'ilustrativo', filas: [] } as EstimacionesRiesgo, text: 'Sin estimaciones de riesgo disponibles.' },
- { data: null, text: 'Estimaciones de riesgo no disponibles.' },
- ])('representa ausencia explícita: $text', ({ data, text }) => {
+
+ it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
+ 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) });
- expect(f.nativeElement.textContent).toContain(text);
- expect(f.nativeElement.querySelector('table')).toBeNull();
- expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles');
+ 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('distingue carga y error sin filtrar mensajes internos, y cancela al desmontarse', () => {
- const source = new Subject();
- const f = setup({ obtener: () => source });
- expect(f.nativeElement.textContent).toContain('Cargando estimaciones de riesgo');
- source.error(new Error('private')); f.detectChanges();
- expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudieron cargar');
- expect(f.nativeElement.textContent).not.toContain('private');
+
+ 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 };
+ const f = setup({ obtener: () => of(data) });
+ expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
+ expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
expect(f.nativeElement.querySelector('table')).toBeNull();
+ });
+
+ it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
+ const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
+ const f = setup({ obtener: () => of(data) });
+ expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
+ expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
+ });
+
+ it('representa carga y cancela la suscripción al desmontarse', () => {
+ const source = new Subject(), f = setup({ obtener: () => source });
+ expect(f.nativeElement.textContent).toContain('Cargando riesgo individual');
+ expect(source.observed).toBe(true);
f.destroy(); expect(source.observed).toBe(false);
});
- it('un error inmediato del adaptador también mantiene las recomendaciones ausentes', () => {
- const f = setup({ obtener: () => throwError(() => new Error('private')) });
+
+ 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();
+ expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
+ f.destroy();
+ const otra = TestBed.createComponent(PacienteRiesgoTabla); 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);
+ otra.destroy(); expect(source.observed).toBe(false);
+ });
+
+ it.each(['observable', 'sincrono'])('oculta detalles internos del error %s', tipo => {
+ const error = new Error('private pac_id=4821');
+ const f = setup({ obtener: () => { if (tipo === 'sincrono') throw error; return throwError(() => error); } });
+ expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudo validar o cargar');
+ expect(f.nativeElement.textContent).not.toMatch(/private|4821|pac_id/);
expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles');
- expect(f.nativeElement.textContent).not.toContain('private');
- TestBed.inject(HttpTestingController).expectNone(() => true);
});
});
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 23efcd8..5a109fa 100644
--- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts
@@ -1,14 +1,16 @@
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
-import { catchError, map, of } from 'rxjs';
+import { catchError, defer, map, of } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
+import { riesgoPacienteResponse } from './paciente-riesgo.validation';
@Injectable()
export class PacienteRiesgoState {
- readonly estado = toSignal(inject(PACIENTE_RIESGO_PROVIDER).obtener().pipe(
+ private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
+ readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
- : datos.filas.length ? { tipo: 'disponible', datos } : { tipo: 'vacio' }),
+ : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of({ tipo: 'error' })),
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
}
diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts
new file mode 100644
index 0000000..511c042
--- /dev/null
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts
@@ -0,0 +1,21 @@
+import { RiesgoPacienteCacu } from './paciente-riesgo.models';
+
+/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
+export function riesgoCacuEjemplo(): 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',
+ 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' },
+ ],
+ },
+ };
+}
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
new file mode 100644
index 0000000..7716d4a
--- /dev/null
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts
@@ -0,0 +1,123 @@
+import { riesgoCacuEjemplo } 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 entrada = riesgoCacuEjemplo();
+ const salida = riesgoPacienteResponse(entrada);
+ expect(salida).toEqual(entrada);
+ salida.riesgo!.horizontes[0].probabilidad = 0;
+ salida.cohorte!.c = -999;
+ expect(entrada).toEqual(riesgoCacuEjemplo());
+ });
+
+ it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
+ const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
+ expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
+ });
+
+ 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', () => {
+ 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 });
+ });
+
+ it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
+ const entrada = riesgoCacuEjemplo();
+ entrada.cohorte = null;
+ expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
+ });
+
+ it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
+ 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);
+ });
+
+ 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);
+ });
+
+ 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],
+ ];
+ 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');
+ });
+ 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
new file mode 100644
index 0000000..e26ba5a
--- /dev/null
+++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts
@@ -0,0 +1,58 @@
+import { isoDate } from '../cacu-seguimiento.models';
+import { HorizonteRiesgoCacu, 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 probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
+const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
+
+function utcTimestamp(v: unknown) {
+ 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 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;
+ }
+ // 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'];
+}
+
+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']);
+}
+
+/** 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;
+}
+
+/** 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;
+}