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
@@ -1,7 +1,9 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
export interface SeguimientoPaciente {
id_seudonimo: string;
pac_id?: string;
id_seudonimo?: string;
grupo_edad: string;
estatus: SeguimientoStatus;
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
@@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
import { identidadDe, identidadesDe } from './paciente-identidad';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
@@ -19,12 +20,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
const c = item['ultima_citologia'], h = item['ultimo_vph'];
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
})) throw new Error('Respuesta de seguimiento inválida');
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
return v as unknown as SeguimientoResponse;
}
@Injectable({ providedIn: 'root' })
@@ -1,5 +1,6 @@
import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs';
import { Dominio } from '../indicadores.models';
import { identidadesDe } from '../paciente-identidad';
import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service';
import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models';
@@ -50,8 +51,8 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi
startWith<TrackingExportEvent>({ kind: 'progress', fetched: first.items.length, total }),
concatWith(defer(() => {
const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows);
const ids = new Set(items.map(item => item['id_seudonimo']));
if (items.length !== total || ids.size !== total) throw new ExportInconsistent('The pages do not add up to the announced total');
// Every row has the identity the table shows, and no patient (or episode) appears on two pages.
if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total');
return of<TrackingExportEvent>({
kind: 'done',
snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items },
@@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { Dominio } from './indicadores.models';
import { columnaEnlace, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { TrackingExportBar } from './export/tracking-export-bar';
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
@@ -95,10 +96,10 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
<caption>Resultados disponibles por paciente</caption>
<thead><tr>@for (c of respuesta.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
<tbody>
@for (item of respuesta.items; track item['id_seudonimo']) {
<tr tabindex="-1" [attr.data-paciente]="item['id_seudonimo']" (click)="abrirFicha(item, $event)">
@for (item of respuesta.items; track identidad(item).id) {
<tr tabindex="-1" [attr.data-paciente]="identidad(item).id" (click)="abrirFicha(item, $event)">
@for (c of respuesta.columnas; track c.clave) {
<td>@if (c.clave === 'id_seudonimo') { <button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item['id_seudonimo']" (click)="abrirFicha(item, $event)">{{ texto(item[c.clave]) }}</button> } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
<td>@if (c.clave === claveEnlace(respuesta, item)) { <button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirFicha(item, $event)">{{ texto(item[c.clave]) }}</button> } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ texto(item[d.clave]) }}</small> } }</td>
}
</tr>
} @empty { <tr><td [attr.colspan]="respuesta.columnas.length">{{ textoVacio(respuesta) }}</td></tr> }
@@ -352,6 +353,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
return r.cohorte && r.ventana.meses === 0 && sinFiltros ? 'Sin pacientes para el corte seleccionado.' : 'No hay registros para los filtros aplicados.';
}
detalles(c: SeguimientoColumna) { return c.detalles ?? []; }
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(item: Record<string, SeguimientoValor>): IdentidadPaciente { return identidadDe(item)!; }
claveEnlace(r: SeguimientoTablaResponse, item: Record<string, SeguimientoValor>) { return columnaEnlace(r.columnas, this.identidad(item).campo); }
texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); }
}
@@ -41,11 +41,11 @@
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
<tbody>
@for (item of response.items; track item.id_seudonimo) {
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="item.id_seudonimo">
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirPaciente(item, $event)">{{ item.id_seudonimo }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
@for (item of response.items; track identidad(item).id) {
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
@@ -10,6 +10,7 @@ import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service';
@Component({
@@ -97,6 +98,10 @@ export class IndicadoresTracking implements OnChanges {
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
this.load({ ...this.applied, page });
}
// Every row of a shown answer has an identity: the answer is validated before it reaches the view.
identidad(paciente: SeguimientoPaciente): IdentidadPaciente { return identidadDe(paciente)!; }
// The rows of a page identify their patient by one field; an empty page keeps the legacy wording.
etiquetaIdentidad(respuesta: SeguimientoResponse) { return ETIQUETA_IDENTIDAD[respuesta.items[0] ? this.identidad(respuesta.items[0]).campo : 'id_seudonimo']; }
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return;
evento.stopPropagation();
@@ -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' })),
@@ -0,0 +1,215 @@
// Covers how a follow-up row identifies its patient (`pac_id`, or the legacy `id_seudonimo`): the rule itself, the CaMa
// table and record, the files built from the same rows, and CaCu's risk request. Fixtures: fixtures/cama_seguimiento.json
// (27 synthetic rows) rewritten to carry `pac_id`, and fixtures/cacu_seguimiento.json.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { lastValueFrom, Observable, of, toArray } from 'rxjs';
import camaData from './fixtures/cama_seguimiento.json';
import cacuData from './fixtures/cacu_seguimiento.json';
import { ExportInconsistent } from './export/tracking-export.models';
import { fetchAllTracking } from './export/tracking-export-source';
import { flatTable } from './export/tracking-export-table';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresTracking } from './indicadores-tracking';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-detalle/paciente-riesgo.provider';
import { columnaEnlace, identidadDe, identidadesDe } from './paciente-identidad';
import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service';
describe('Identidad de un renglón', () => {
// Fails if `pac_id` stops winning over the legacy field, or stops being kept as the text the server sent.
it('uses pac_id when the row has it, and the legacy id_seudonimo otherwise', () => {
expect(identidadDe({ pac_id: '42', id_seudonimo: 'P-X' })).toEqual({ campo: 'pac_id', id: '42' });
expect(identidadDe({ id_seudonimo: 'P-X' })).toEqual({ campo: 'id_seudonimo', id: 'P-X' });
expect(identidadDe({ pac_id: null, id_seudonimo: 'P-X' })?.campo).toBe('id_seudonimo');
});
// Fails if a number, a padded value or a pseudonym in `pac_id` is accepted, or if an invalid pac_id falls back to the pseudonym.
it('refuses a pac_id that is not a plain decimal string, without falling back to id_seudonimo', () => {
for (const malo of [42, '042', '-1', '4 2', '1e3', '', 'P-X', '12345678901234567890', {}]) expect(identidadDe({ pac_id: malo, id_seudonimo: 'P-X' })).toBeNull();
expect(identidadDe({ pac_id: '0' })?.id).toBe('0');
});
// Fails if a row with no identifier opens a record for nobody.
it('has no identity without an identifier', () => {
expect(identidadDe({})).toBeNull();
expect(identidadDe({ id_seudonimo: '' })).toBeNull();
expect(identidadDe({ id_seudonimo: 7 })).toBeNull();
});
// Fails if a page that repeats a patient, or identifies rows by different fields, can be shown.
it('refuses a page with a repeated patient or with mixed identifier fields', () => {
expect(identidadesDe([{ pac_id: '7' }, { pac_id: '8' }])).toHaveLength(2);
expect(identidadesDe([{ pac_id: '7' }, { pac_id: '7' }])).toBeNull();
expect(identidadesDe([{ pac_id: '7' }, { id_seudonimo: 'P-8' }])).toBeNull();
expect(identidadesDe([])).toEqual([]);
});
// Fails if the link moves to a column that is not the identifier when the answer announces it.
it('puts the link on the identifier column of the row, else on any identifier column, else on the first', () => {
expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }, { clave: 'pac_id' }], 'pac_id')).toBe('pac_id');
expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }], 'pac_id')).toBe('id_seudonimo');
expect(columnaEnlace([{ clave: 'a' }, { clave: 'b' }], 'pac_id')).toBe('a');
});
});
/** The CaMa fixture with `pac_id` (1..n) instead of the pseudonym. */
function conPacId(): Record<string, any> {
const d = structuredClone(camaData) as unknown as Record<string, any>;
d['columnas'][0] = { clave: 'pac_id', etiqueta: 'Identificador de paciente' };
d['items'] = (d['items'] as Record<string, any>[]).map((item, i) => {
const { id_seudonimo: _, ...rest } = item;
return { pac_id: String(i + 1), ...rest };
});
return d;
}
describe('Tabla de seguimiento con pac_id', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const cargar = (respuesta: Record<string, any>) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); };
const enlaces = () => [...root().querySelectorAll<HTMLButtonElement>('tbody button.patient-link')];
// Fails if the header or the link stop following the column the answer announces for the identifier.
it('shows the announced pac_id column and links each row by it', () => {
cargar(conPacId());
expect([...root().querySelectorAll('thead th')][0].textContent!.trim()).toBe('Identificador de paciente');
expect(enlaces().slice(0, 3).map(b => b.textContent!.trim())).toEqual(['1', '2', '3']);
expect(enlaces()[0].getAttribute('aria-label')).toBe('Ver ficha del paciente 1');
expect(root().querySelector('tbody tr')?.getAttribute('data-paciente')).toBe('1');
});
// Fails if the row that was used opens the record of another row, shows the legacy label, or the focus does not go
// back to the control that was used.
it('opens the record of the row that was used and returns focus to it', async () => {
const datos = conPacId(), items = datos['items'] as Record<string, any>[];
cargar(datos);
for (const indice of [2, 0]) {
enlaces()[indice].click(); fixture.detectChanges();
const ficha = root().querySelector('app-cama-patient-card')!;
expect(ficha.querySelector('h2')!.textContent!.trim()).toBe(`Paciente ${items[indice]['pac_id']}`);
expect(ficha.textContent).toContain(items[indice]['birads']);
expect(ficha.textContent).toContain('Identificador de paciente');
expect(ficha.textContent).not.toContain('Identificador seudónimo');
ficha.querySelector<HTMLButtonElement>('.back-button')!.click(); fixture.detectChanges();
await fixture.whenStable(); fixture.detectChanges();
expect(document.activeElement).toBe(enlaces()[indice]);
}
});
// Fails if a page that repeats a patient, or mixes pac_id with the legacy field, is drawn: its rows would open the same record.
it('does not draw an answer whose rows cannot be told apart or identify patients by different fields', () => {
const repetida = conPacId(); repetida['items'][1]['pac_id'] = repetida['items'][0]['pac_id'];
cargar(repetida);
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
expect(enlaces()).toHaveLength(0);
});
// Fails if a numeric pac_id is accepted: the contract is a decimal string.
it('does not draw an answer whose pac_id is a number', () => {
const numerica = conPacId(); numerica['items'][0]['pac_id'] = 1;
cargar(numerica);
expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado');
});
// Fails if the legacy contract stops working while the server still sends only id_seudonimo.
it('still draws and opens a row that only has id_seudonimo', () => {
cargar(structuredClone(camaData) as unknown as Record<string, any>);
enlaces()[0].click(); fixture.detectChanges();
expect(root().querySelector('app-cama-patient-card h2')!.textContent).toContain('Paciente ' + (camaData.items[0] as any).id_seudonimo);
expect(root().querySelector('app-cama-patient-card')!.textContent).toContain('Identificador seudónimo');
});
});
describe('Archivos con pac_id', () => {
// A server over `todas`, `tam` rows a page.
function servidor(todas: Record<string, any>[], tam: number) {
return {
consultar(_d: string, q: SeguimientoTablaQuery): Observable<SeguimientoTablaResponse> {
const d = conPacId(); d['items'] = todas.slice((q.page - 1) * tam, q.page * tam);
d['paginacion'] = { page: q.page, page_size: tam, total_items: todas.length, total_pages: Math.ceil(todas.length / tam) };
return of(seguimientoTablaResponse(d));
},
} as unknown as SeguimientoTablaService;
}
const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5 };
// Fails if the file holds other rows, or the same rows in another order, than the pages of the table.
it('hands the files the same rows in the same order as the pages of the table', async () => {
const todas = conPacId()['items'] as Record<string, any>[];
const salida = await lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()));
const hecho = salida.at(-1)!;
expect(hecho.kind).toBe('done');
if (hecho.kind !== 'done') return;
expect(hecho.snapshot.items.map(i => i['pac_id'])).toEqual(todas.map(i => i['pac_id']));
const plana = flatTable(hecho.snapshot);
expect(plana.columns[0]).toMatchObject({ key: 'pac_id', label: 'Identificador de paciente' });
expect(plana.rows.map(f => f[0])).toEqual(todas.map(i => i['pac_id']));
});
// Fails if a patient that appears on two pages is exported twice as if it were two patients.
it('refuses a list in which the same patient is on two pages', async () => {
const todas = conPacId()['items'] as Record<string, any>[];
todas[7] = { ...todas[7], pac_id: todas[0]['pac_id'] };
await expect(lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()))).rejects.toBeInstanceOf(ExportInconsistent);
});
});
describe('Riesgo de CaCu por pac_id', () => {
let http: HttpTestingController;
const solicitudes: string[] = [];
function montar(items: Record<string, any>[]) {
solicitudes.length = 0;
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: (id: string) => { solicitudes.push(id); return of(null); } } }] });
const fixture = TestBed.createComponent(IndicadoresTracking);
http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('domainLabel', 'CaCu'); fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...structuredClone(cacuData), items });
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
fixture.detectChanges();
return fixture;
}
const filas = () => (structuredClone(cacuData) as unknown as { items: Record<string, any>[] }).items;
const primerEncabezado = (f: ReturnType<typeof montar>) => [...f.nativeElement.querySelectorAll('thead th')][0].textContent.trim();
const abrirSegunda = (f: ReturnType<typeof montar>) => { (f.nativeElement.querySelectorAll('tbody button.patient-link')[1] as HTMLButtonElement).click(); f.detectChanges(); };
afterEach(() => http.verify());
// Fails if the record asks for the risk with something other than the row's pac_id, or shows the legacy label for it.
it('requests the risk with the pac_id of the row and labels the identifier as the patient identifier', () => {
const items = filas().slice(0, 2).map(({ id_seudonimo: _, ...r }, i) => ({ pac_id: String(40 + i), ...r }));
const fixture = montar(items);
expect(primerEncabezado(fixture)).toBe('Identificador de paciente');
abrirSegunda(fixture);
expect(solicitudes).toEqual(['41']);
expect(fixture.nativeElement.querySelector('app-paciente-detalle h2').textContent).toContain('Paciente 41');
fixture.destroy();
});
// Fails if the migration alias wins over pac_id: a hash kept in id_seudonimo must never reach the risk route.
it('prefers pac_id over the legacy alias that rows carry during the migration', () => {
const items = filas().slice(0, 2).map((r, i) => ({ ...r, pac_id: String(40 + i) }));
const fixture = montar(items);
expect(primerEncabezado(fixture)).toBe('Identificador de paciente');
abrirSegunda(fixture);
expect(solicitudes).toEqual(['41']);
fixture.destroy();
});
// Fails if a legacy value is sent to the risk route, which only accepts a pac_id.
it('does not request the risk of a row that only has id_seudonimo', () => {
const fixture = montar(filas().slice(0, 2));
expect(primerEncabezado(fixture)).toBe('Identificador seudónimo');
abrirSegunda(fixture);
expect(solicitudes).toEqual([]);
expect(fixture.nativeElement.querySelector('app-paciente-riesgo-tabla').textContent).toContain('Riesgo individual no disponible');
fixture.destroy();
});
});
@@ -0,0 +1,54 @@
// How a follow-up row says who its patient is: `pac_id`, or the legacy `id_seudonimo` that servers may still send.
/** The fields that can identify a patient on a row, in order of precedence. */
export const CAMPOS_IDENTIDAD = ['pac_id', 'id_seudonimo'] as const;
export type CampoIdentidad = typeof CAMPOS_IDENTIDAD[number];
export interface IdentidadPaciente {
/** The field the identifier came from: `pac_id` wins over the legacy `id_seudonimo`. */
campo: CampoIdentidad;
/** The identifier as sent, scoped to the domain it was read in. `pac_id` is a decimal string. */
id: string;
}
/** What the row's identifier is called on screen and in the files, by the field it comes from. */
export const ETIQUETA_IDENTIDAD: Readonly<Record<CampoIdentidad, string>> = {
pac_id: 'Identificador de paciente',
id_seudonimo: 'Identificador seudónimo',
};
// No leading zeros and no sign: the value is compared and sent as text, so it has one spelling.
const PAC_ID = /^(0|[1-9][0-9]{0,17})$/;
/** The fields of a row that matter here; a typed row or a plain record both fit. */
export interface FilaConIdentidad { readonly pac_id?: unknown; readonly id_seudonimo?: unknown }
const texto = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
/**
* The identity of a row, or `null` when it has none that can be trusted: a `pac_id` that is not a decimal string
* (a number is refused, not converted) or no identifier at all. A present `pac_id` is never replaced by
* `id_seudonimo` when it is invalid.
*/
export function identidadDe(fila: FilaConIdentidad): IdentidadPaciente | null {
const pacId = fila.pac_id;
if (pacId !== undefined && pacId !== null) return typeof pacId === 'string' && PAC_ID.test(pacId) ? { campo: 'pac_id', id: pacId } : null;
return texto(fila.id_seudonimo) ? { campo: 'id_seudonimo', id: fila.id_seudonimo } : null;
}
/**
* The identities of a page of rows, or `null` when the page cannot be shown: a row without identity, rows that do not
* identify their patient by the same field, or two rows of the same patient (they would open the same record).
*/
export function identidadesDe(filas: readonly FilaConIdentidad[]): IdentidadPaciente[] | null {
const identidades = filas.map(identidadDe);
if (identidades.some(i => i === null)) return null;
const validas = identidades as IdentidadPaciente[];
if (validas.some(i => i.campo !== validas[0].campo)) return null;
return new Set(validas.map(i => i.id)).size === validas.length ? validas : null;
}
/** The column that holds the link to the record: the one of the row's own field, else any identifier column, else the first. */
export function columnaEnlace(columnas: readonly { clave: string }[], campo: CampoIdentidad): string | undefined {
return columnas.find(c => c.clave === campo)?.clave
?? columnas.find(c => (CAMPOS_IDENTIDAD as readonly string[]).includes(c.clave))?.clave
?? columnas[0]?.clave;
}
@@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { Dominio, requireDominio } from './indicadores.models';
@@ -30,7 +31,7 @@ export interface SeguimientoTablaResponse extends Partial<ContextoLista> {
filtros_disponibles: SeguimientoFiltro[];
columnas: SeguimientoColumna[];
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
// Every item names its patient (`pac_id`, or the legacy `id_seudonimo`); the rest are the columns' keys and their details.
items: Record<string, SeguimientoValor>[];
}
export class SeguimientoInvalido extends Error {}
@@ -92,7 +93,7 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|| !filtrosOk || !columnasOk
|| !record(filters) || !Object.entries(filters).every(([k, f]) => (f === null || typeof f === 'string') && (available as Record<string, unknown>[]).some(a => a['clave'] === k))
|| !Array.isArray(v['items']) || v['items'].length > p['page_size']
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
}
const respuesta = v as unknown as SeguimientoTablaResponse;