Patient record reads its risk from GET /cacu/pacientes/<pac_id>/riesgo, by the id the follow-up list shows

This commit is contained in:
2026-11-11 23:25:08 -06:00
parent f4d2a3e85f
commit bfbd11beae
9 changed files with 53 additions and 27 deletions
@@ -79,7 +79,7 @@
</mat-card>
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
<mat-card-content><app-paciente-riesgo-tabla /></mat-card-content>
<mat-card-content><app-paciente-riesgo-tabla [idSeudonimo]="estado.resumen.id_seudonimo" /></mat-card-content>
</mat-card>
</div>
}
@@ -108,7 +108,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
let root: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
fixture = TestBed.createComponent(IndicadoresTracking);
root = fixture.nativeElement;
http = TestBed.inject(HttpTestingController);
@@ -247,7 +248,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
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();
expect(obtener).toHaveBeenCalledExactlyOnceWith(pacientes[0].id_seudonimo);
volver();
const otra = abrir(1);
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
@@ -7,12 +7,13 @@ import { MatSelectHarness } from '@angular/material/select/testing';
import { MatInputHarness } from '@angular/material/input/testing';
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
import { MatDialog } from '@angular/material/dialog';
import { firstValueFrom } from 'rxjs';
import { firstValueFrom, of } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { TipoRegistroTemporal } from './paciente-registro.models';
@@ -31,7 +32,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
let dialog: MatDialog;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
http = TestBed.inject(HttpTestingController);
dialog = TestBed.inject(MatDialog);
montarTracking();
@@ -4,7 +4,6 @@
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
@case ('no-disponible') {
<p role="status">Riesgo individual no disponible para esta paciente.</p>
<p class="availability">La consulta de riesgo individual aún no está habilitada.</p>
}
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
@@ -1,4 +1,4 @@
import { Component, inject } from '@angular/core';
import { Component, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@@ -11,6 +11,12 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
styleUrl: './paciente-riesgo-tabla.scss',
})
export class PacienteRiesgoTabla {
readonly estado = inject(PacienteRiesgoState).estado;
readonly idSeudonimo = input.required<string>();
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
constructor() {
effect(() => this.state.idSeudonimo.set(this.idSeudonimo()));
}
}
@@ -40,9 +40,9 @@ export interface RiesgoPacienteCacu {
riesgo: LoteRiesgoCacu | null;
}
/** Deliberately no patient argument until secure identity resolution is authorized. */
/** `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(): Observable<unknown>;
obtener(idSeudonimo: string): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -1,8 +1,16 @@
import { InjectionToken } from '@angular/core';
import { of } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
// The follow-up list identifies each patient by the `pac_id` of the risk batches; a 404 is a patient without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (idSeudonimo: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(idSeudonimo)}/riesgo`).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
},
});
@@ -12,6 +12,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
fixture.componentRef.setInput('idSeudonimo', '42');
fixture.detectChanges();
fixture.detectChanges();
return fixture;
}
@@ -20,14 +22,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify();
});
it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
it('pide el riesgo por el pac_id de los lotes a la WebApi 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' });
f.detectChanges();
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', () => {
@@ -35,7 +38,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith();
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
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);
@@ -134,7 +137,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
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();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('idSeudonimo', 'P-OTRA'); 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);
@@ -1,16 +1,22 @@
import { inject, Injectable } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of } from 'rxjs';
import { Injectable, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' };
@Injectable()
export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
readonly idSeudonimo = signal<string | null>(null);
readonly estado = toSignal(toObservable(this.idSeudonimo).pipe(
switchMap(id => id === null ? of(CARGANDO) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
), { initialValue: CARGANDO });
}