Identify follow-up patients by pac_id

Rows name their patient with pac_id (a decimal string) or the legacy
id_seudonimo. pac_id wins; an invalid pac_id is never replaced by the
legacy field, and a page that repeats a patient or mixes both fields is
not drawn or exported. The table, patient record, PDF and spreadsheet
follow the announced identifier column and label. CaCu requests risk
only with a pac_id.
This commit is contained in:
Angel Capetillo Zavala
2026-11-13 18:19:27 -06:00
parent caf5f954b7
commit 3b246b4f1f
31 changed files with 392 additions and 89 deletions
@@ -6,10 +6,10 @@
@if (failed()) { <p class="toolbar-message" role="alert">No se pudo generar el PDF. Intenta nuevamente.</p> }
</div>
<header>
<h2 #title tabindex="-1">Paciente {{ p.pseudonymId }}</h2>
<h2 #title tabindex="-1">Paciente {{ p.patientId }}</h2>
<p>Fecha de corte: {{ p.cutoff }}.</p>
<dl class="summary">
<div><dt>Identificador seudónimo</dt><dd>{{ p.pseudonymId }}</dd></div>
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
@@ -16,7 +16,7 @@ describe('Ficha CaMa: resumen', () => {
it('reads every field the follow-up row carries', () => {
const row = complete();
expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({
pseudonymId: row['id_seudonimo'], cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'],
birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'],
daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'],
});
@@ -102,7 +102,7 @@ describe('Ficha CaMa: componente', () => {
for (let i = 0; i < 100 && !downloads.length; i++) await new Promise(r => setTimeout(r, 50));
expect(downloads).toHaveLength(1);
expect(downloads[0]).toMatch(/^ficha-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.pdf$/);
expect(downloads[0]).not.toContain(summary.pseudonymId);
expect(downloads[0]).not.toContain(summary.patientId);
vi.restoreAllMocks();
}, 30000);
@@ -35,7 +35,7 @@ describe('Ficha CaMa: PDF individual', () => {
it('prints each field of the record under its label', () => {
const p = complete();
const found = texts(definition(p)['content']);
for (const t of [`Paciente ${p.pseudonymId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia', 'Días de mastografía a diagnóstico']) expect(found).toContain(t);
});
@@ -16,10 +16,10 @@ const section = (title: string, rows: [string, string | number | null][]) => [
/** The document definition of one patient's record. Exported so its content can be checked without rendering. */
export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo?: string): PdfDefinition {
return institutionalDocument({ title: PATIENT_TITLE, logo, now, orientation: 'portrait' }, [
{ text: `Paciente ${patient.pseudonymId}`, style: 'h1' },
{ text: `Paciente ${patient.patientId}`, style: 'h1' },
{ text: `Fecha de corte: ${patient.cutoff}`, style: 'muted' },
...section('Resumen', [
['Identificador seudónimo', patient.pseudonymId],
[patient.idLabel, patient.patientId],
['Grupo de edad', patient.ageGroup],
['Estatus de seguimiento', patient.status],
['Prioridad', patient.priority],
@@ -1,13 +1,17 @@
import { TrackingRow } from '../../export/tracking-export.models';
import { CampoIdentidad, ETIQUETA_IDENTIDAD, identidadDe } from '../../paciente-identidad';
export const NOT_AVAILABLE = 'No disponible';
/**
* What the CaMa follow-up list says about one patient, read from the row that was clicked. `pseudonymId` is the
* synthetic `M-…` identifier of the list; it is not a platform identifier and is never sent anywhere.
* What the CaMa follow-up list says about one patient, read from the row that was clicked. `patientId` is the
* identifier the row carries (`idField` says which field); the record only shows it.
*/
export interface CamaPatientSummary {
pseudonymId: string;
patientId: string;
idField: CampoIdentidad;
/** What the identifier is called on screen and in the file. */
idLabel: string;
cutoff: string;
ageGroup: string | null;
status: string | null;
@@ -33,16 +37,18 @@ export const RECOMMENDATIONS_UNAVAILABLE = 'Recomendaciones no disponibles.';
const text = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : null);
/**
* The patient summary of a follow-up row, or `null` when the row has no identifier to show. `columnas` are the ones the
* The patient summary of a follow-up row, or `null` when the row has no identity that can be trusted. `columnas` are the ones the
* list announced: the label it gives to the biopsy date is kept, so the record says the same as the list.
*/
export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: readonly { clave: string; detalles?: readonly { clave: string; etiqueta: string }[] }[] = []): CamaPatientSummary | null {
const pseudonymId = text(row['id_seudonimo']);
if (!pseudonymId) return null;
const identity = identidadDe(row);
if (!identity) return null;
const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta;
const days = row['dias_mastografia_diagnostico'];
return {
pseudonymId,
patientId: identity.id,
idField: identity.campo,
idLabel: ETIQUETA_IDENTIDAD[identity.campo],
cutoff,
ageGroup: text(row['grupo_edad']),
status: text(row['estatus']),
@@ -1,10 +1,10 @@
@if (estado.tipo !== 'cerrado') {
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
<header>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.id_seudonimo }}</h2>
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.identidad.id }}</h2>
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
<dl class="summary">
<div><dt>Identificador seudónimo</dt><dd>{{ estado.resumen.id_seudonimo }}</dd></div>
<div><dt>{{ etiquetaIdentidad }}</dt><dd>{{ estado.resumen.identidad.id }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
@@ -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 [idSeudonimo]="estado.resumen.id_seudonimo" /></mat-card-content>
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
</mat-card>
</div>
}
@@ -1,8 +1,9 @@
import { Observable } from 'rxjs';
import { IdentidadPaciente } from '../paciente-identidad';
/** Snapshot of the received row, independent of the Seguimiento transport contract. */
export interface PacienteResumen {
id_seudonimo: string;
identidad: IdentidadPaciente;
grupoEdad: string | null;
estatus: string | null;
corte: string;
@@ -27,7 +28,8 @@ export interface PacienteDetalle {
}
export interface PacienteDetalleProvider {
obtener(idSeudonimo: string): Observable<PacienteDetalle | null>;
/** `id` is the patient identifier of the row; a patient the provider does not know is `null`. */
obtener(id: string): Observable<PacienteDetalle | null>;
}
export type PacienteDetalleEstado =
@@ -5,9 +5,9 @@ import { PacienteDetalleProvider } from './paciente-detalle.models';
@Injectable({ providedIn: 'root' })
export class PacienteDetalleMockProvider implements PacienteDetalleProvider {
obtener(idSeudonimo: string) {
obtener(id: string) {
return defer(() => {
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo);
const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === id);
// Each read owns its data; consumers cannot mutate another selection or the fixtures.
return of(detalle ? structuredClone(detalle) : null);
});
@@ -3,6 +3,7 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Subject, of, throwError } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
@@ -10,9 +11,9 @@ import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.mod
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;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
describe('Proveedor de detalle sintético', () => {
it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => {
@@ -59,7 +60,7 @@ describe('Estado de selección del paciente', () => {
const estado = state.estado();
expect(estado.tipo).toBe('no-disponible');
if (estado.tipo !== 'cerrado') {
expect(estado.resumen.id_seudonimo).toBe('001');
expect(estado.resumen.identidad.id).toBe('001');
expect(estado.resumen.vph?.resultado).toBe('NEGATIVO');
expect(estado.resumen.vph?.genotipo16y18).toBeNull();
expect(estado.resumen.diasTomaDiagnostico).toBe(0);
@@ -167,7 +168,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
fixture.detectChanges();
const estado = fixture.componentInstance.pacienteDetalle.estado();
expect(estado.tipo).toBe('disponible');
if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo);
if (estado.tipo === 'disponible') expect(estado.resumen.identidad.id).toBe(pacientes[1].id_seudonimo);
volver();
expect(row).toBe(document.activeElement);
http.expectNone(() => true);
@@ -239,20 +240,15 @@ 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', () => {
// Fails if a row that only has id_seudonimo asks the risk route (which takes a pac_id) or leaves no «no disponible» state.
it('una ficha de un renglón con solo id_seudonimo no consulta el riesgo y lo declara no disponible', () => {
const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER);
const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo()));
const obtener = vi.spyOn(provider, 'obtener');
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(pacientes[0].id_seudonimo);
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();
const tarjeta = abrir().querySelector('app-paciente-riesgo-tabla')!;
expect(tarjeta.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(tarjeta.querySelector('table')).toBeNull();
expect(obtener).not.toHaveBeenCalled();
http.expectNone(() => true);
} finally { obtener.mockRestore(); }
});
@@ -2,6 +2,7 @@ import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core'
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, catchError, defer, map, of, switchMap } from 'rxjs';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { identidadDe } from '../paciente-identidad';
import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models';
import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider';
import { AltaRegistroTemporal } from './paciente-registro.models';
@@ -17,14 +18,14 @@ export class PacienteDetalleState {
readonly estado = this.actual.asReadonly();
readonly registrosTemporales = computed(() => {
const estado = this.actual();
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo);
return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.identidad.id);
});
constructor() {
this.seleccion.pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe(
switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.identidad.id)).pipe(
map(detalle => {
if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) {
if (detalle && (detalle.id_seudonimo !== resumen.identidad.id || detalle.origen !== 'sintetico')) {
throw new Error('Detalle incompatible con la selección');
}
return detalle
@@ -38,8 +39,10 @@ export class PacienteDetalleState {
}
abrir(paciente: SeguimientoPaciente, corte: string) {
const identidad = identidadDe(paciente);
if (!identidad) return;
const resumen: PacienteResumen = {
id_seudonimo: paciente.id_seudonimo,
identidad,
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
estatus: paciente.estatus.etiqueta,
corte,
@@ -65,7 +68,7 @@ export class PacienteDetalleState {
agregarRegistro(alta: AltaRegistroTemporal) {
const estado = this.actual();
if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false;
return this.sesion.agregar(alta.id_seudonimo, alta.registro);
if (estado.tipo === 'cerrado' || estado.resumen.identidad.id !== alta.paciente.id) return false;
return this.sesion.agregar(alta.paciente.id, alta.registro);
}
}
@@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente } from '../paciente-identidad';
import { PacienteDetalleEstado } from './paciente-detalle.models';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
@@ -31,19 +32,22 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
ngAfterViewInit() { this.titulo?.nativeElement.focus(); }
ngOnDestroy() { this.dialogoActivo?.close(); }
get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; }
/** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */
get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; }
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
abrirRegistro(tipo: TipoRegistroTemporal) {
if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return;
const id_seudonimo = this.estado.resumen.id_seudonimo;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; id_seudonimo: string }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
const paciente = this.estado.resumen.identidad;
const ref = this.dialog.open<PacienteRegistroDialog, { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente }, NuevoRegistroTemporal>(PacienteRegistroDialog, {
data: { tipo, paciente }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh',
autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false,
});
this.dialogoActivo = ref;
ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => {
this.dialogoActivo = undefined;
if (registro) this.registroAgregado.emit({ id_seudonimo, registro });
if (registro) this.registroAgregado.emit({ paciente, registro });
});
}
etiquetaCitologia(resultado: string | null, calidad: string | null) {
@@ -1,7 +1,7 @@
<h2 mat-dialog-title>{{ titulo }}</h2>
<form [formGroup]="form" (ngSubmit)="agregar()">
<mat-dialog-content>
<p>Paciente {{ data.id_seudonimo }}</p>
<p>Paciente {{ data.paciente.id }}</p>
<div class="fields">
<mat-form-field appearance="outline">
<mat-label>{{ etiquetaTipo }}</mat-label>
@@ -1,4 +1,5 @@
import { Component, DestroyRef, inject } from '@angular/core';
import { IdentidadPaciente } from '../paciente-identidad';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
@@ -10,7 +11,7 @@ import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO,
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; }
export interface RegistroDialogData { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente; }
const opcionValida = (catalogo: Readonly<Record<string, string>>): ValidatorFn =>
control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true };
@@ -9,6 +9,7 @@ import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
import { MatDialog } from '@angular/material/dialog';
import { firstValueFrom, of } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
@@ -16,9 +17,11 @@ 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 { identidadDe } from '../paciente-identidad';
import { TipoRegistroTemporal } from './paciente-registro.models';
const pacientes = seguimientoResponse(fixtureData).items;
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
@@ -132,7 +135,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo);
expect(almacenado.paciente).toBe(pacientes[0].id_seudonimo);
expect(almacenado.origen).toBe('sesion-demostracion');
expect(almacenado.fecha).toBe('2026-10-26');
http.expectNone(() => true);
@@ -276,7 +279,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
const a = primero.get(PacienteDetalleState);
const b = segundo.get(PacienteDetalleState);
a.abrir(pacientes[0], fixtureData.corte);
expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
expect(a.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
a.cerrar();
expect(a.registrosTemporales()).toEqual([]);
primero.destroy();
@@ -284,7 +287,7 @@ describe('Vida de la selección y de la memoria de sesión', () => {
expect(b.registrosTemporales()).toHaveLength(1);
b.abrir(pacientes[1], fixtureData.corte);
expect(b.registrosTemporales()).toEqual([]);
expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
expect(b.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
} finally {
if (!primero.destroyed) primero.destroy();
segundo.destroy();
@@ -1,3 +1,4 @@
import { IdentidadPaciente } from '../paciente-identidad';
import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos';
type ResultadoDemo = {
@@ -14,11 +15,12 @@ export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo'];
/** Independiente del resumen recibido y del historial inicial del proveedor. */
export type RegistroTemporal = Readonly<NuevoRegistroTemporal & {
id: number;
id_seudonimo: string;
/** Identifier of the patient the record was added to. */
paciente: string;
origen: 'sesion-demostracion';
}>;
export interface AltaRegistroTemporal {
id_seudonimo: string;
paciente: IdentidadPaciente;
registro: NuevoRegistroTemporal;
}
@@ -5,6 +5,7 @@ import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models';
import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
describe('Fecha de calendario de registros temporales', () => {
it('acepta días reales, incluyendo años bisiestos y límites de año', () => {
@@ -35,7 +36,7 @@ describe.each(casos)('Formulario de $tipo', caso => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, paciente: identidadDe({ id_seudonimo: '001' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -82,7 +83,7 @@ describe('Resultados dependientes del estudio', () => {
beforeEach(() => {
cerrar = vi.fn();
TestBed.configureTestingModule({ providers: [
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } },
{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', paciente: identidadDe({ id_seudonimo: 'A' })! } },
{ provide: MatDialogRef, useValue: { close: cerrar } },
] });
const fixture = TestBed.createComponent(PacienteRegistroDialog);
@@ -132,7 +133,7 @@ describe('Memoria de registros temporales', () => {
const sesion = TestBed.inject(PacienteRegistrosSesion);
for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true);
expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']);
expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true);
expect(sesion.paraPaciente('001').every(r => r.paciente === '001' && r.origen === 'sesion-demostracion')).toBe(true);
for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]);
sesion.agregar('toString', casos[0].registro);
expect(sesion.paraPaciente('toString')).toHaveLength(1);
@@ -11,21 +11,21 @@ export class PacienteRegistrosSesion {
private readonly registros = signal<ReadonlyMap<string, readonly RegistroTemporal[]>>(new Map());
private siguienteId = 0;
paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] {
return this.registros().get(idSeudonimo) ?? SIN_REGISTROS;
paraPaciente(id: string): readonly RegistroTemporal[] {
return this.registros().get(id) ?? SIN_REGISTROS;
}
agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean {
if (!idSeudonimo || !nuevo) return false;
agregar(id: string, nuevo: NuevoRegistroTemporal): boolean {
if (!id || !nuevo) return false;
const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion
: nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio;
const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : '');
if (!validado) return false;
const registro: RegistroTemporal = Object.freeze({
...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion',
...validado, id: ++this.siguienteId, paciente: id, origen: 'sesion-demostracion',
});
this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([
...(actual.get(idSeudonimo) ?? []), registro,
this.registros.update(actual => new Map(actual).set(id, Object.freeze([
...(actual.get(id) ?? []), registro,
])));
return true;
}
@@ -11,12 +11,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
styleUrl: './paciente-riesgo-tabla.scss',
})
export class PacienteRiesgoTabla {
readonly idSeudonimo = input.required<string>();
/** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */
readonly pacId = input.required<string | null>();
private readonly state = inject(PacienteRiesgoState);
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
constructor() {
effect(() => this.state.idSeudonimo.set(this.idSeudonimo()));
effect(() => this.state.pacId.set(this.pacId()));
}
}
@@ -42,7 +42,7 @@ export interface RiesgoPacienteCacu {
/** `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(idSeudonimo: string): Observable<unknown>;
obtener(pacId: string): Observable<unknown>;
}
export type PacienteRiesgoEstado =
@@ -3,12 +3,12 @@ import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// The follow-up list identifies each patient by the `pac_id` of the risk batches; a 404 is a patient without risk data.
// 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.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (idSeudonimo: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(idSeudonimo)}/riesgo`).pipe(
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
@@ -12,7 +12,7 @@ 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.componentRef.setInput('pacId', '42');
fixture.detectChanges();
fixture.detectChanges();
return fixture;
@@ -138,7 +138,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('idSeudonimo', 'P-OTRA'); otra.detectChanges();
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);
@@ -10,9 +10,10 @@ const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' };
@Injectable()
export class PacienteRiesgoState {
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
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(
// `undefined` until the input is set; `null` is a patient without `pac_id`.
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),