diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts new file mode 100644 index 0000000..09dae04 --- /dev/null +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -0,0 +1,18 @@ +// 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. +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)$/; + +/** «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; + +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad }; + +/** 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-analisis-figuras.ts b/src/app/features/indicadores/indicadores-analisis-figuras.ts index 50e5d03..a35369e 100644 --- a/src/app/features/indicadores/indicadores-analisis-figuras.ts +++ b/src/app/features/indicadores/indicadores-analisis-figuras.ts @@ -1,9 +1,9 @@ import { PlotlyFigure, Tema } from './indicadores.models'; import { C2_PALETTE, c2Theme } from './indicadores-c2-palette'; import { AnalisisAgregado } from './indicadores-analisis.service'; +import { etiquetaBirads } from './etiquetas-cohorte'; -/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». */ -export const etiquetaBirads = (codigo: string) => /^BIRADS_/.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; +export { etiquetaBirads }; const miles = (v: number) => v.toLocaleString('es-MX'); /** The code of the published bar that was clicked, from its `customdata`; a suppressed bar or an empty click gives nothing. */ diff --git a/src/app/features/indicadores/indicadores-analisis.spec.ts b/src/app/features/indicadores/indicadores-analisis.spec.ts index c4464c9..9a9629a 100644 --- a/src/app/features/indicadores/indicadores-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-analisis.spec.ts @@ -136,6 +136,15 @@ describe('Pestaña Análisis epidemiológico', () => { http.expectNone(() => true); expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte'); }); + it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => { + // Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost. + abrir(); + const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true })); + pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges(); + expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.'); + expect(text()).not.toContain('Sin pacientes'); + expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true); + }); it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => { // Fails if the table offers the patients of a hidden group. abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-analisis.testing.ts b/src/app/features/indicadores/indicadores-analisis.testing.ts index 1bf6388..8c11455 100644 --- a/src/app/features/indicadores/indicadores-analisis.testing.ts +++ b/src/app/features/indicadores/indicadores-analisis.testing.ts @@ -16,5 +16,32 @@ export const agregado = (extra: Partial = {}): AnalisisAgregad ], ...extra, }); +/** + * The answer of the cohort's list as the API sends it: only the two filters it announces, with the code as their label, + * the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown), + * and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off. + */ +export function listaCohorte(o: { corte?: string; filtros?: Record; page?: number; size?: number; n?: number; meses?: number } = {}): Record { + const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0 } = o; + const todos = Array.from({ length: n }, (_, i) => ({ + id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01', + biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null, + })); + const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c })); + return { + simulado: true, ...CONTEXTO, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha', + filtros: { birads: null, grupo_edad: null, ...filtros }, + filtros_disponibles: [ + { clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) }, + { clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: opciones(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']) }], + columnas: [ + { clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, + { clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] }, + { clave: 'biopsia', etiqueta: 'Resultado histopatológico', detalles: [{ clave: 'biopsia_fecha', etiqueta: 'Fecha de reporte' }] }], + paginacion: { page, page_size: size, total_items: n, total_pages: Math.max(1, Math.ceil(n / size)) }, + items: todos.slice((page - 1) * size, page * size), + }; +} + /** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */ export const agregadoJson = (extra: Record = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra }); diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index edde907..7898b46 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -7,7 +7,8 @@ import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { isoDate } from './cacu-seguimiento.models'; -import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; +import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; +import { etiquetaBirads } from './etiquetas-cohorte'; import { AnalisisAgregado, AnalisisService, ContextoCohorte } from './indicadores-analisis.service'; import { Dominio, Tema } from './indicadores.models'; @@ -78,6 +79,9 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement { } @if (datos(); as d) {

Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.

+ @if (todasSuprimidas()) { +

Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.

+ }

{{ aviso() }}

@@ -150,6 +154,8 @@ export class IndicadoresAnalisis { // Why the last click on a bar opened nothing. readonly aviso = signal(''); readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; }); + // The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published. + readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido)); readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; }); constructor() { diff --git a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts new file mode 100644 index 0000000..ece261f --- /dev/null +++ b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts @@ -0,0 +1,131 @@ +// Covers how the breast cohort is written for the user (BI-RADS and age groups), that the requests keep the codes, that +// the cut-off the user chose reaches the list, the record and the files, and what the record says of a biopsy whose +// report date is known while its result is not. Fixture: listaCohorte() in 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 { Observable, of } from 'rxjs'; +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 { CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; +import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; +import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; +import { fetchAllTracking, queryOf } from './export/tracking-export-source'; +import { trackingDocument } from './export/tracking-pdf'; +import { buildTrackingXlsx } from './export/tracking-xlsx'; + +const CORTE_ELEGIDO = '2026-09-01'; +const textos = (nodo: unknown, salida: string[] = []): string[] => { + if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida)); + return salida; +}; + +describe('Etiquetas de la cohorte', () => { + it('escribe las categorías BI-RADS y los grupos de edad como en la clínica, y deja lo demás como llegó', () => { + // Fails if a confirmed code is shown raw, or a code whose meaning is not confirmed is invented. + expect(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'].map(etiquetaBirads)).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); + expect(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO'].map(etiquetaEdad)).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(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'); + }); + 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. + const r = seguimientoTablaResponse(listaCohorte()); + 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' }); + 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' }); + }); +}); + +describe('La lista de la cohorte con etiquetas legibles y el corte elegido', () => { + 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('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('active', false); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const root = () => fixture.nativeElement as HTMLElement; + const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento'); + const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); + async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } + const seleccion = (esperados = 6): SeleccionSeguimiento => ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE_ELEGIDO, esperados, contexto: CONTEXTO, id: 1 }); + const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; + const celdas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent!.replace(/\s+/g, ' ').trim())); + + it('muestra BI-RADS y grupos de edad legibles en las filas y en los filtros, pero la petición sigue enviando los códigos', async () => { + // Fails if the user reads codes, or a filter chosen by its label is sent as text instead of its code. + fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion()); fixture.detectChanges(); + let r = solicitud(); + expect(parametros(r)).toMatchObject({ corte: CORTE_ELEGIDO, birads: 'BIRADS_5', meses: '0', ...CONTEXTO }); + r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await asentar(); + expect(celdas()[1].slice(1, 3)).toEqual(['60 a 69 años', 'BI-RADS 5 Fecha: 2025-02-01']); + expect(root().textContent).not.toMatch(/BIRADS_5|60-69/); + expect([...campo('Grupo de edad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', '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']); + const s = campo('Grupo de edad').querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === '60 a 69 años')!.value; + s.dispatchEvent(new Event('change')); await asentar(); + [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); fixture.detectChanges(); + r = solicitud(); + expect(parametros(r)).toMatchObject({ grupo_edad: '60-69', birads: 'BIRADS_5', corte: CORTE_ELEGIDO }); + r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5', grupo_edad: '60-69' } })); + }); + it('el corte elegido en el análisis llega a la lista, a la ficha y a todas las páginas de la exportación', async () => { + // Fails if the list, the record or a page of the file is read at another cut-off than the one the user chose. + fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion(450)); fixture.detectChanges(); + solicitud().flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); await asentar(); + // The record, opened from the row that was clicked. + (root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar(); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE_ELEGIDO}.`); + // The files: every page asks for the same cut-off, and the answer must give it back. + const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); + const pedidas: SeguimientoTablaQuery[] = []; + const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery): Observable => { + pedidas.push(q); return of(seguimientoTablaResponse(listaCohorte({ corte: q.corte, filtros: q.filtros as Record, page: q.page, size: q.page_size, n: 450 }))); } } as unknown as SeguimientoTablaService; + expect(queryOf(respuesta)).toMatchObject({ corte: CORTE_ELEGIDO, meses: 0, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO }); + await new Promise((ok, fallo) => fetchAllTracking(servicio, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok })); + expect(pedidas.map(q => q.corte)).toEqual([CORTE_ELEGIDO, CORTE_ELEGIDO, CORTE_ELEGIDO]); + }); +}); + +describe('Ficha y archivos de una fila con biopsia reportada y resultado desconocido', () => { + const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO })); + const fila = (i: number) => respuesta.items[i]; + const NOW = new Date(Date.UTC(2026, 10, 13, 18, 0)); + + it('la ficha dice «Fecha de reporte», conserva «No disponible» para el resultado, el estatus y la prioridad, y escribe BI-RADS y edad legibles', () => { + // Fails if the date of a biopsy report is called the date of the biopsy, or an unknown result is filled in. + const resumen = toCamaPatientSummary(fila(2), CORTE_ELEGIDO, respuesta.columnas)!; + expect(resumen).toMatchObject({ birads: 'BI-RADS 5', ageGroup: '50 a 59 años', histopathology: null, biopsyDate: '2025-02-15', biopsyDateLabel: 'Fecha de reporte', status: null, priority: null }); + TestBed.configureTestingModule({ providers: [provideHttpClient()] }); + const card = TestBed.createComponent(CamaPatientCard); + card.componentRef.setInput('summary', resumen); card.detectChanges(); + const t = (card.nativeElement.textContent as string).replace(/\s+/g, ' '); + expect(t).toContain('Resultado: No disponible'); expect(t).toContain('Fecha de reporte: 2025-02-15'); + expect(t).toContain('Categoría BI-RADS: BI-RADS 5'); expect(t).toContain('50 a 59 años'); + expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).toMatch(/Prioridad\s*No disponible/); expect(t).toMatch(/Días de mastografía a diagnóstico\s*No disponible/); + expect(t).not.toContain('Fecha de biopsia'); + const pdf = textos(camaPatientDocument(resumen, NOW, 'data:image/png;base64,AAAA')); + expect(pdf).toContain('Fecha de reporte'); expect(pdf).not.toContain('Fecha de biopsia'); + // A list whose columns do not rename the date keeps the record's own wording. + expect(toCamaPatientSummary(fila(2), CORTE_ELEGIDO)!.biopsyDateLabel).toBeUndefined(); + }); + it('los archivos escriben las etiquetas, no los códigos, y la fila con fecha de reporte sin resultado sale con la celda vacía', async () => { + // Fails if a file carries codes the user cannot read, or invents a result for a report whose result is unknown. + const snapshot = { corte: respuesta.corte, ventana: respuesta.ventana, filtros: respuesta.filtros, filtros_disponibles: respuesta.filtros_disponibles, columnas: respuesta.columnas, items: respuesta.items, seleccion: 'Categoría BI-RADS: BI-RADS 5' }; + const pdf = textos(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA')); + expect(pdf).toContain('BI-RADS 5'); expect(pdf).toContain('50 a 59 años'); expect(pdf.some(t => /BIRADS_|50-59/.test(t))).toBe(false); + expect(pdf).toContain('Fecha de reporte: 2025-02-15'); + const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer())); + const cadenas = strFromU8(hojas['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|'); + expect(cadenas).toContain('|BI-RADS 5|'); expect(cadenas).toContain('|60 a 69 años|'); expect(cadenas).not.toMatch(/BIRADS_|\|50-59\|/); + expect(cadenas).toContain('Resultado histopatológico: Fecha de reporte'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 75edebb..86e447c 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -14,7 +14,7 @@ import fixtureData from './fixtures/cama_seguimiento.json'; import { IndicadoresPage } from './indicadores-page'; import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis'; import { IndicadorFigureCard } from './indicador-figure-card'; -import { agregadoJson, CONTEXTO } from './indicadores-analisis.testing'; +import { agregadoJson, CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Indicador } from './indicadores.models'; @@ -78,7 +78,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = expect(e.panel('seguimiento').hidden).toBe(false); expect(e.panel('analisis').hidden).toBe(true); expect(e.panel('seguimiento').textContent).toContain('Categoría BI-RADS: BI-RADS 5'); expect(e.panel('seguimiento').textContent).toContain('Toda la cohorte'); - expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección; la lista muestra 27.'); + expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección y la lista muestra 27. No coinciden'); expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]); // The record opens over the list and gives it back. @@ -105,6 +105,36 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectNone(q => q.url === '/cama/seguimiento'); expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5'); }); + it('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => { + // Fails if any step of the journey is read at another cut-off than the chosen one, or the file does not say it. + const ELEGIDO = '2026-09-01'; + const descargas: string[] = []; + vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test'); vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); }); + const e = await entrar(); + await abrirAnalisis(e); + const entrada = e.root.querySelector('#panel-analisis input[name="corte"]')!; + entrada.value = ELEGIDO; entrada.dispatchEvent(new Event('input')); await e.asentar(); + [...e.panel('analisis').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); e.harness.detectChanges(); + http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === ELEGIDO).flush(agregadoJson({ corte: ELEGIDO })); await e.asentar(); + e.root.querySelector('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges(); + const r = lista(); + expect(parametros(r)).toMatchObject({ corte: ELEGIDO, meses: '0', birads: 'BIRADS_5', ...CONTEXTO }); + r.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await e.asentar(); + expect(e.panel('seguimiento').textContent).toContain(`corte ${ELEGIDO}`); + // The record. + e.root.querySelector('.patient-link')!.click(); await e.asentar(); + expect(e.root.querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${ELEGIDO}.`); + [...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar(); + // The file: the pages are read at the same cut-off, and the file says so. + [...e.panel('seguimiento').querySelectorAll('app-seguimiento-exportar button')].find(b => b.textContent!.includes('Excel'))!.dispatchEvent(new Event('click')); + const pagina = http.expectOne(q => q.url === '/cama/seguimiento'); + expect(parametros(pagina)).toMatchObject({ corte: ELEGIDO, page_size: '200', meses: '0', birads: 'BIRADS_5', ...CONTEXTO }); + pagina.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' }, size: 200 })); + for (let i = 0; i < 30 && !descargas.length; i++) { await new Promise(res => setTimeout(res, 20)); e.harness.detectChanges(); } + expect(descargas).toHaveLength(1); + expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-09-01_/); + }); it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => { // Fails if a stale revision shows rows, or the way back to the analysis is lost with the error. const e = await entrar(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts index 8e61316..9770bd1 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -75,14 +75,18 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); expect(root().querySelector('.seleccion')).toBeNull(); }); - it('avisa cuando la lista no tiene tantos pacientes como contó el análisis, y calla cuando coinciden', async () => { - // Fails if a difference between the analysis' count and the list goes unsaid. + it('si la lista no tiene tantos pacientes como contó el análisis para la misma selección y revisión, lo avisa y no deja exportarla; si coinciden, calla y exporta', async () => { + // Fails if a list that breaks the contract can be exported as if it were the group that was counted. abrirCon(seleccion(1, { esperados: 30 })); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); - expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección; la lista muestra 27.'); + expect(root().querySelector('.diferencia')?.getAttribute('role')).toBe('alert'); + expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección y la lista muestra 27. No coinciden, por lo que este resultado no se puede exportar.'); + expect([...exportar()!.querySelectorAll('button')].every(b => b.disabled)).toBe(true); + expect(root().querySelector('table')).not.toBeNull(); fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges(); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(root().querySelector('.diferencia')).toBeNull(); + expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true); }); it('una respuesta que pierde el filtro, cambia la ventana o el corte, o no es la cohorte ni la revisión pedidas no se dibuja ni se puede exportar', async () => { diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 55d4f57..c332f70 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -48,7 +48,7 @@ const mismosFiltros = (a: Record, b: Record

Seguimiento de {{ domainLabel }}

@if (data(); as respuesta) { - + } @if (seleccionMostrada(); as sel) { @@ -61,7 +61,7 @@ const mismosFiltros = (a: Record, b: RecordVolver al análisis - @if (diferencia(); as d) {

{{ d }}

} + @if (diferencia(); as d) { } }
@@ -185,11 +185,15 @@ export class IndicadoresSeguimientoTabla implements OnChanges { /** «Toda la cohorte» is offered while the analysis' cohort is active (or the form still holds it), never as a plain window. */ ventanas() { return this.contextoActivo || this.draft.meses === 0 ? MESES_VENTANA : MESES_VENTANA.filter(m => m !== 0); } - /** What the list says when it does not hold as many patients as the analysis counted for the selection. */ + /** + * What the list says when it does not hold as many patients as the analysis counted for the selection. With the same + * cohort revision, cut-off and filter the server counts both from the same rows, so a difference breaks the contract: + * the list stays visible, but it is not exported as if it were the group that was counted. + */ diferencia() { const esperados = this.activa?.esperados, total = this.data()?.paginacion.total_items; if (!this.seleccionExacta() || this.estado() !== 'ready' || esperados == null || total === undefined || esperados === total) return undefined; - return `El análisis cuenta ${esperados} pacientes en esta selección; la lista muestra ${total}.`; + return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`; } constructor() { @@ -296,7 +300,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { // A click on the row opens the record unless it landed on another control; the id button always does. if (evento.currentTarget instanceof HTMLTableRowElement && origen?.closest('button, a, input, select, textarea')) return; const corte = this.data()?.corte; - const resumen = corte ? toCamaPatientSummary(item, corte) : null; + const resumen = corte ? toCamaPatientSummary(item, corte, this.data()?.columnas) : null; if (!resumen || this.estado() !== 'ready') return; evento.stopPropagation(); this.controlFicha = evento.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined; 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 842051a..4c5807f 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 @@ -29,7 +29,7 @@

Histopatología

    -
  • Resultado histopatológicoResultado: {{ p.histopathology ?? notAvailable }}Fecha de biopsia: {{ p.biopsyDate ?? notAvailable }}
  • +
  • Resultado histopatológicoResultado: {{ p.histopathology ?? notAvailable }}{{ p.biopsyDateLabel ?? 'Fecha de biopsia' }}: {{ p.biopsyDate ?? notAvailable }}
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 4a1910c..1251ee4 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 @@ -26,7 +26,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo ['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis], ]), ...section('Mastografía', [['Categoría BI-RADS', patient.birads], ['Fecha de la mastografía', patient.mammographyDate]]), - ...section('Histopatología', [['Resultado histopatológico', patient.histopathology], ['Fecha de biopsia', patient.biopsyDate]]), + ...section('Histopatología', [['Resultado histopatológico', patient.histopathology], [patient.biopsyDateLabel ?? 'Fecha de biopsia', patient.biopsyDate]]), ...section('Pronóstico y recomendaciones', [ ...PROGNOSIS_PLACEHOLDERS.map(p => [p.label, PROGNOSIS_UNAVAILABLE] as [string, string]), ['Recomendaciones', RECOMMENDATIONS_UNAVAILABLE], 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 a263b6c..f11d59f 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 @@ -16,6 +16,8 @@ export interface CamaPatientSummary { mammographyDate: string | null; histopathology: string | null; biopsyDate: string | null; + /** What the list calls that date: the cohort's list gives the date of the biopsy report, which can be known before its result is. */ + biopsyDateLabel?: string; daysMammographyToDiagnosis: number | null; } @@ -30,10 +32,14 @@ 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. */ -export function toCamaPatientSummary(row: TrackingRow, cutoff: string): CamaPatientSummary | null { +/** + * The patient summary of a follow-up row, or `null` when the row has no identifier to show. `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 etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta; const days = row['dias_mastografia_diagnostico']; return { pseudonymId, @@ -45,6 +51,7 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string): CamaPati mammographyDate: text(row['mastografia_fecha']), histopathology: text(row['biopsia']), biopsyDate: text(row['biopsia_fecha']), + ...(etiquetaFecha ? { biopsyDateLabel: etiquetaFecha } : {}), daysMammographyToDiagnosis: typeof days === 'number' && Number.isFinite(days) ? days : null, }; } diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index 6bec678..e7a9637 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 { etiquetaDeFiltro } from './etiquetas-cohorte'; import { Dominio, requireDominio } from './indicadores.models'; // A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per @@ -94,9 +95,35 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse { || !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) { throw new SeguimientoInvalido('Respuesta de seguimiento inválida'); } - return v as unknown as SeguimientoTablaResponse; + const respuesta = v as unknown as SeguimientoTablaResponse; + return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta; } +/** + * A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is + * rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays + * in `_codigo` and in the filters' options, which are what the requests send. + */ +export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaResponse { + const claves = Object.keys(ETIQUETADAS); + return { + ...r, + filtros_disponibles: r.filtros_disponibles.map(f => claves.includes(f.clave) + ? { ...f, opciones: f.opciones.map(o => o.etiqueta === o.codigo ? { ...o, etiqueta: etiquetaDeFiltro(f.clave, o.codigo) } : o) } : f), + items: r.items.map(item => { + const nuevo = { ...item }; + for (const k of claves) { + const valor = item[k]; + if (typeof valor !== 'string' || etiquetaDeFiltro(k, valor) === valor) continue; + if (nuevo[k + '_codigo'] === undefined) nuevo[k + '_codigo'] = valor; + nuevo[k] = etiquetaDeFiltro(k, valor); + } + return nuevo; + }), + }; +} +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true }; + @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService { private readonly http = inject(HttpClient);