Keep breast follow-up on the selected cohort

This commit is contained in:
Angel Capetillo Zavala
2026-11-13 15:32:39 -06:00
parent 3f4cf2217f
commit 18e9260705
6 changed files with 38 additions and 34 deletions
@@ -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<Record<string, string>> = {
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<Record<string, string>> = {
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<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad };
const POR_CLAVE: Readonly<Record<string, (codigo: string) => 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);
@@ -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<string, unknown>[])[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' });
@@ -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<string, any>;
describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, 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();
}
});
@@ -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<HTMLButtonElement>('.patient-link')!.click();
await fixture.whenStable(); fixture.detectChanges();
@@ -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<Consulta | Resultado> {
let agregado;
try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of<Resultado>({ 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<Consulta | Resultado> => {
if (!this.contextoActivo && error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) {
this.sinCohorte = true; this.draft = { ...this.draft, meses: 3 };
return of<Consulta>({ ...c, refrescar: false, q: { ...c.q, meses: 3, corte: undefined, contexto: undefined } });
}
if (error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503))
return of<Resultado>({ 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<string, SeguimientoValor>, 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.
@@ -122,7 +122,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR
}),
};
}
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true };
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {