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
@@ -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();
});
});