From 3b246b4f1f94b4b4259816da5824d8a9a02f2d22 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 18:19:27 -0600 Subject: [PATCH] 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. --- .../indicadores/cacu-seguimiento.models.ts | 4 +- .../indicadores/cacu-seguimiento.service.ts | 5 +- .../export/tracking-export-source.ts | 5 +- .../indicadores-seguimiento-tabla.ts | 10 +- .../indicadores/indicadores-tracking.html | 8 +- .../indicadores/indicadores-tracking.ts | 5 + .../cama/cama-patient-card.html | 4 +- .../cama/cama-patient-card.spec.ts | 4 +- .../cama/cama-patient-pdf.spec.ts | 2 +- .../paciente-detalle/cama/cama-patient-pdf.ts | 4 +- .../cama/cama-patient.models.ts | 20 +- .../paciente-detalle/paciente-detalle.html | 6 +- .../paciente-detalle.models.ts | 6 +- .../paciente-detalle.provider.ts | 4 +- .../paciente-detalle/paciente-detalle.spec.ts | 28 +-- .../paciente-detalle.state.ts | 15 +- .../paciente-detalle/paciente-detalle.ts | 12 +- .../paciente-registro-dialog.html | 2 +- .../paciente-registro-dialog.ts | 3 +- .../paciente-registro-integracion.spec.ts | 11 +- .../paciente-registro.models.ts | 6 +- .../paciente-registro.spec.ts | 7 +- .../paciente-registros-sesion.ts | 14 +- .../paciente-detalle/paciente-riesgo-tabla.ts | 5 +- .../paciente-riesgo.models.ts | 2 +- .../paciente-riesgo.provider.ts | 4 +- .../paciente-detalle/paciente-riesgo.spec.ts | 4 +- .../paciente-detalle/paciente-riesgo.state.ts | 7 +- .../indicadores/paciente-identidad.spec.ts | 215 ++++++++++++++++++ .../indicadores/paciente-identidad.ts | 54 +++++ .../indicadores/seguimiento-tabla.service.ts | 5 +- 31 files changed, 392 insertions(+), 89 deletions(-) create mode 100644 src/app/features/indicadores/paciente-identidad.spec.ts create mode 100644 src/app/features/indicadores/paciente-identidad.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index d6f1b6c..bba0ea8 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -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; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index a9d9924..53cf2da 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -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 => !!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' }) diff --git a/src/app/features/indicadores/export/tracking-export-source.ts b/src/app/features/indicadores/export/tracking-export-source.ts index a778405..c88b023 100644 --- a/src/app/features/indicadores/export/tracking-export-source.ts +++ b/src/app/features/indicadores/export/tracking-export-source.ts @@ -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({ 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({ kind: 'done', snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items }, diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index a63cde9..db63208 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -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, b: RecordResultados disponibles por paciente @for (c of respuesta.columnas; track c.clave) { {{ c.etiqueta }} } - @for (item of respuesta.items; track item['id_seudonimo']) { - + @for (item of respuesta.items; track identidad(item).id) { + @for (c of respuesta.columnas; track c.clave) { - @if (c.clave === 'id_seudonimo') { } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { {{ d.etiqueta }}: {{ texto(item[d.clave]) }} } } + @if (c.clave === claveEnlace(respuesta, item)) { } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { {{ d.etiqueta }}: {{ texto(item[d.clave]) }} } } } } @empty { {{ textoVacio(respuesta) }} } @@ -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): IdentidadPaciente { return identidadDe(item)!; } + claveEnlace(r: SeguimientoTablaResponse, item: Record) { return columnaEnlace(r.columnas, this.identidad(item).campo); } texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); } } diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 1b537dc..b6c3e8e 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -41,11 +41,11 @@
- + - @for (item of response.items; track item.id_seudonimo) { - - + @for (item of response.items; track identidad(item).id) { + + diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 2547a5a..d2c1ae2 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -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(); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 4c5807f..1fef561 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -6,10 +6,10 @@ @if (failed()) { }
-

Paciente {{ p.pseudonymId }}

+

Paciente {{ p.patientId }}

Fecha de corte: {{ p.cutoff }}.

-
Identificador seudónimo
{{ p.pseudonymId }}
+
{{ p.idLabel }}
{{ p.patientId }}
Grupo de edad
{{ p.ageGroup ?? notAvailable }}
Estatus de seguimiento
{{ p.status ?? notAvailable }}
Prioridad
{{ p.priority ?? notAvailable }}
diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 9792500..4b413d7 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -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); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts index cbb3188..fc49e84 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts @@ -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); }); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts index 1251ee4..bb7c405 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts @@ -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], diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index f11d59f..311f9b6 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -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']), diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html index 00f6bd0..06b31d1 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html @@ -1,10 +1,10 @@ @if (estado.tipo !== 'cerrado') {
-

Paciente {{ estado.resumen.id_seudonimo }}

+

Paciente {{ estado.resumen.identidad.id }}

Fecha de corte: {{ estado.resumen.corte }}.

-
Identificador seudónimo
{{ estado.resumen.id_seudonimo }}
+
{{ etiquetaIdentidad }}
{{ estado.resumen.identidad.id }}
Grupo de edad
{{ estado.resumen.grupoEdad ?? 'No disponible' }}
Estatus de seguimiento
{{ estado.resumen.estatus ?? 'No disponible' }}
Días de toma a diagnóstico
{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}
@@ -79,7 +79,7 @@

Riesgos y recomendaciones

- +
} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts index fe7b778..bbbde94 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts @@ -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; + /** `id` is the patient identifier of the row; a patient the provider does not know is `null`. */ + obtener(id: string): Observable; } export type PacienteDetalleEstado = diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts index c7e6601..bf3e563 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts @@ -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); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts index 7f6ad00..c9eb230 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts @@ -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(); } }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts index e223be2..b323aa1 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts @@ -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); } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts index e3d2a75..d9b38c3 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts @@ -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, { - data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh', + const paciente = this.estado.resumen.identidad; + const ref = this.dialog.open(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) { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html index f4f82cc..3b40c1b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html @@ -1,7 +1,7 @@

{{ titulo }}

-

Paciente {{ data.id_seudonimo }}

+

Paciente {{ data.paciente.id }}

{{ etiquetaTipo }} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts index 0e5f813..5c2fa08 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts @@ -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>): ValidatorFn => control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts index 853caeb..47fb10b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -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(); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts index 0f72c23..8fd7b2b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts @@ -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; export interface AltaRegistroTemporal { - id_seudonimo: string; + paciente: IdentidadPaciente; registro: NuevoRegistroTemporal; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts index 8fb331b..cc78875 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts @@ -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); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts b/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts index 8198377..4708ed6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts @@ -11,21 +11,21 @@ export class PacienteRegistrosSesion { private readonly registros = signal>(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; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 2b69b01..bf02e1a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -11,12 +11,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation'; styleUrl: './paciente-riesgo-tabla.scss', }) export class PacienteRiesgoTabla { - readonly idSeudonimo = input.required(); + /** 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(); 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())); } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 0ff9cec..b7ff381 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -42,7 +42,7 @@ export interface RiesgoPacienteCacu { /** `null` when the patient has no risk data. */ export interface PacienteRiesgoProvider { - obtener(idSeudonimo: string): Observable; + obtener(pacId: string): Observable; } export type PacienteRiesgoEstado = diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 70a3092..0749c29 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -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', { providedIn: 'root', factory: () => { const http = inject(HttpClient); return { - obtener: (idSeudonimo: string) => http.get(`/cacu/pacientes/${encodeURIComponent(idSeudonimo)}/riesgo`).pipe( + obtener: (pacId: string) => http.get(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe( catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), ), }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 20caa5f..4eea34d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -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); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index 9a9e868..b5a08d5 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -10,9 +10,10 @@ const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' }; @Injectable() export class PacienteRiesgoState { private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); - readonly idSeudonimo = signal(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(undefined); + readonly estado = toSignal(toObservable(this.pacId).pipe( + switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe( map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), catchError(() => of({ tipo: 'error' })), diff --git a/src/app/features/indicadores/paciente-identidad.spec.ts b/src/app/features/indicadores/paciente-identidad.spec.ts new file mode 100644 index 0000000..a87835e --- /dev/null +++ b/src/app/features/indicadores/paciente-identidad.spec.ts @@ -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 { + const d = structuredClone(camaData) as unknown as Record; + d['columnas'][0] = { clave: 'pac_id', etiqueta: 'Identificador de paciente' }; + d['items'] = (d['items'] as Record[]).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>, 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) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); }; + const enlaces = () => [...root().querySelectorAll('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[]; + 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('.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); + 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[], tam: number) { + return { + consultar(_d: string, q: SeguimientoTablaQuery): Observable { + 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[]; + 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[]; + 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[]) { + 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[] }).items; + const primerEncabezado = (f: ReturnType) => [...f.nativeElement.querySelectorAll('thead th')][0].textContent.trim(); + const abrirSegunda = (f: ReturnType) => { (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(); + }); +}); diff --git a/src/app/features/indicadores/paciente-identidad.ts b/src/app/features/indicadores/paciente-identidad.ts new file mode 100644 index 0000000..403d153 --- /dev/null +++ b/src/app/features/indicadores/paciente-identidad.ts @@ -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> = { + 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; +} diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index f523b2f..bf53616 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -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 { 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[]; } 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[]).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[])) { throw new SeguimientoInvalido('Respuesta de seguimiento inválida'); } const respuesta = v as unknown as SeguimientoTablaResponse;
Resultados disponibles por paciente
Identificador seudónimoGrupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }}
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible } {{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}