From 18e92607058369a150214597a1a9cd79f9b9b203 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:32:39 -0600 Subject: [PATCH] Keep breast follow-up on the selected cohort --- .../features/indicadores/etiquetas-cohorte.ts | 12 ++++++---- .../indicadores-cohorte-etiquetas.spec.ts | 7 +++++- .../indicadores-seguimiento-cohorte.spec.ts | 18 ++++++-------- .../indicadores-seguimiento-ficha.spec.ts | 9 ++++--- .../indicadores-seguimiento-tabla.ts | 24 +++++++++---------- .../indicadores/seguimiento-tabla.service.ts | 2 +- 6 files changed, 38 insertions(+), 34 deletions(-) diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts index 09dae04..f7bdef8 100644 --- a/src/app/features/indicadores/etiquetas-cohorte.ts +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -1,18 +1,20 @@ -// How the codes of the breast cohort are written for the user. Only codes whose meaning the API's own code confirms: -// the BI-RADS categories (kit: BIRADS_4, 4A, 4B, 4C, 5, 6) and the age groups of the cohort reader (`_age_group` of -// webapi/cama_cohort.py: under 40, each decade from 40 to 69, 70 or more, and no data when the birth date is missing -// or later than the cut-off). Requests keep the codes; only what is shown changes. +// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received. const EDADES: Readonly> = { MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato', }; const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/; +const HISTOLOGIA: Readonly> = { + BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', + CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido', +}; /** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; /** «50-59» as «50 a 59 años». Any other text is returned as it came. */ export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; +export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo; -const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad }; +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia }; /** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); diff --git a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts index ece261f..82fba5a 100644 --- a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts +++ b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts @@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf'; import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; -import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad } from './etiquetas-cohorte'; +import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte'; import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; @@ -31,6 +31,8 @@ describe('Etiquetas de la cohorte', () => { ['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); expect(etiquetaBirads('BIRADS_7')).toBe('BIRADS_7'); expect(etiquetaEdad('OTRO')).toBe('OTRO'); expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA'); + expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia)) + .toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']); }); it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => { // Fails if the table, the record and the files can still show the code, or the code is lost for the requests. @@ -38,6 +40,9 @@ describe('Etiquetas de la cohorte', () => { expect(r.filtros_disponibles[0].opciones.map(o => [o.codigo, o.etiqueta]).slice(0, 2)).toEqual([['BIRADS_4', 'BI-RADS 4'], ['BIRADS_4A', 'BI-RADS 4A']]); expect(r.filtros_disponibles[1].opciones.map(o => o.etiqueta)).toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); expect(r.items[0]).toMatchObject({ birads: 'BI-RADS 5', birads_codigo: 'BIRADS_5', grupo_edad: '50 a 59 años', grupo_edad_codigo: '50-59' }); + const histo = listaCohorte(); + (histo['items'] as Record[])[0]['biopsia'] = 'CARCINOMA_INVASOR'; + expect(seguimientoTablaResponse(histo).items[0]).toMatchObject({ biopsia: 'Carcinoma invasor', biopsia_codigo: 'CARCINOMA_INVASOR' }); expect(r.filtros).toEqual({ birads: null, grupo_edad: null }); const plana = listaCohorte(); delete plana['cohorte']; expect(seguimientoTablaResponse(plana).items[0]).toMatchObject({ birads: 'BIRADS_5', grupo_edad: '50-59' }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts index 00f5196..4d22e84 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -1,17 +1,15 @@ // Covers the habitual access to Seguimiento of breast cancer: the list is read from the cohort the analysis publishes -// (its revision first, then the whole cohort at the cut-off), falls back to the plain follow-up list where the server does -// not publish it, asks for the revision again when the cut-off changes or the cohort changes under the list, and keeps the +// (its revision first, then the whole cohort at the cut-off), fails closed when the cohort is unavailable, asks for the +// revision again when the cut-off changes or the cohort changes under the list, and keeps the // filters, the cut-off and the page while the record is opened and closed. Fixtures: indicadores-analisis.testing.ts. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; -import fixtureData from './fixtures/cama_seguimiento.json'; import { agregadoJson, CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; import { hoyIso } from './indicadores-analisis.service'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; const OTRA = 'a'.repeat(64); -const base = () => structuredClone(fixtureData) as unknown as Record; describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { let fixture: ReturnType>, http: HttpTestingController; @@ -59,19 +57,17 @@ describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { expect(root().querySelector('app-seguimiento-exportar')).not.toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); }); - it('si el servidor no publica la cohorte (404 o 503), lee la lista de seguimiento sin cohorte, sin «Toda la cohorte»', async () => { - // Fails if a deployment without the cohort provider loses its follow-up list. + it('si la cohorte no está disponible (404 o 503), informa el error sin cambiar de fuente', async () => { + // Fails if an unavailable cohort can silently broaden or replace the population. for (const status of [404, 503]) { TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); agregado().flush({ error: 'x' }, { status, statusText: 'x' }); fixture.detectChanges(); - const r = lista(); - expect(parametros(r), String(status)).toEqual({ meses: '3', page: '1', page_size: '50' }); - r.flush(base()); await asentar(); - expect(ventanas(), String(status)).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); - expect(root().querySelectorAll('tbody tr').length, String(status)).toBeGreaterThan(0); + await asentar(); + http.expectNone(r => r.url === '/cama/seguimiento'); + expect(root().querySelector('[role=alert]')?.textContent, String(status)).toContain('La cohorte no está disponible'); http.verify(); } }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index e385e79..8575131 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -5,6 +5,8 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; +import { agregadoJson, listaCohorte } from './indicadores-analisis.testing'; +import { hoyIso } from './indicadores-analisis.service'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; import { IndicadoresTracking } from './indicadores-tracking'; @@ -108,9 +110,10 @@ describe('Seguimiento: ficha de CaMa y cambio de dominio', () => { fixture.componentInstance.fichaPacienteAbierta.subscribe(v => abierta.push(v)); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); - // Without the cohort published the list reads the plain follow-up endpoint. - http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); - http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina()); + // The record is opened from the same cohort that the analysis publishes. + const corte = hoyIso(); + http.expectOne(r => r.url === '/cama/analisis/indicadores').flush(agregadoJson({ corte })); + http.expectOne(r => r.url === '/cama/seguimiento').flush(listaCohorte({ corte, n: 6 })); await fixture.whenStable(); fixture.detectChanges(); (fixture.nativeElement as HTMLElement).querySelector('.patient-link')!.click(); await fixture.whenStable(); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 7f5dd0a..0b454fa 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -9,7 +9,7 @@ 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'; import { - consultaAplicada, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, + consultaAplicada, contextoDe, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor, } from './seguimiento-tabla.service'; @@ -156,7 +156,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { @Input() seleccion?: SeleccionSeguimiento; /** * Read the list from the cohort the analysis publishes (the agreed contract): the cohort's revision is asked for, then the whole - * cohort is listed at the cut-off. Where the server does not publish it (404 or 503) the plain follow-up list is read. + * cohort is listed at the cut-off. An unavailable cohort is reported without switching sources. */ @Input() cohorte = false; private readonly service = inject(SeguimientoTablaService); @@ -208,8 +208,6 @@ export class IndicadoresSeguimientoTabla implements OnChanges { // The cut-off the cohort's revision was asked at: another cut-off needs another revision. private contextoCorte?: string; - // The server does not publish the cohort (404 or 503 on its aggregate): the plain follow-up list is read. - private sinCohorte = false; // A cohort that changed under a plain list is read again once, with its new revision, before it is reported. private reintentoHecho = false; @@ -229,7 +227,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { catchError(error => of(this.fallo(error, q)))); } - /** The query with the cohort's revision at its cut-off (today's when none), or the plain list when the server does not publish the cohort. */ + /** The query with the cohort's revision at its cut-off (today's when none). */ private refrescar(c: Consulta): Observable { let agregado; try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); } @@ -239,10 +237,8 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return { ...c, refrescar: false, q: { ...c.q, corte: a.corte, contexto: this.contextoActivo } }; }), catchError((error): Observable => { - if (!this.contextoActivo && error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) { - this.sinCohorte = true; this.draft = { ...this.draft, meses: 3 }; - return of({ ...c, refrescar: false, q: { ...c.q, meses: 3, corte: undefined, contexto: undefined } }); - } + if (error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) + return of({ estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }); return of(this.fallo(error, c.q)); })); } @@ -282,7 +278,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 }; // The selection belongs to the domain it was made in. this.appliedEtiqueta = undefined; this.activa = undefined; this.contextoActivo = undefined; this.seleccionAplicada = undefined; - this.contextoCorte = undefined; this.sinCohorte = false; this.reintentoHecho = false; + this.contextoCorte = undefined; this.reintentoHecho = false; this.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined); } const sel = this.seleccion; @@ -298,7 +294,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } if (this.active && !this.iniciado) { this.iniciado = true; - if (this.cohorte && !this.sinCohorte) { + if (this.cohorte) { // The habitual access: the whole cohort at today's cut-off, with the revision the server publishes for it. this.draft = { ...this.draft, meses: 0 }; this.applied = { meses: 0, page: 1, page_size: this.applied.page_size }; this.consultas.next({ q: this.applied, refrescar: true }); @@ -311,6 +307,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado { // A first page that does not exist yet is the list's own pending state; a later page that fails is an error. + if (error instanceof HttpErrorResponse && error.status === 404 && this.cohorte) return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }; if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' }; if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' }; // A cohort's list: the group was too small to publish or access was not granted; the cohort changed after the count; or it is not configured. @@ -327,7 +324,8 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const claves = new Set(data.filtros_disponibles.map(f => f.clave)); this.draft = { ...this.draft, corte: data.corte, filtros: Object.fromEntries(Object.entries(this.draft.filtros).filter(([k]) => claves.has(k))) }; this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size, - filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) }; + filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])), + contexto: contextoDe(data) }; this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size; } // The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort @@ -361,7 +359,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); } // A retry repeats the query as it was; one that failed before the cohort's revision was known asks for it again first. - reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.sinCohorte && !this.applied.contexto }); } + reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.applied.contexto }); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index e7a9637..f523b2f 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -122,7 +122,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR }), }; } -const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true }; +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true, biopsia: true }; @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService {