From 7971a49dcda5f9759f6cf4693c1c725153172edb Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:18:11 -0600 Subject: [PATCH] feat(cama): regular follow-up read from the cohort, with the revision refreshed on a new cut-off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The follow-up tab of breast cancer now reads the cohort the analysis publishes: it asks for the cohort's revision at today's cut-off and lists the whole cohort quoting it. Where the server does not publish the cohort (404 or 503 on its aggregate) the plain follow-up list is read. - Another cut-off in the form asks for that cut-off's revision before the list; a revision that changes under the list (409) is asked for again once and the same query repeated, and a conflict that persists is reported. - "Quitar selección" returns to the whole cohort instead of another source. - An empty whole cohort says "Sin pacientes para el corte seleccionado"; filters and windows keep the text of the filters. - Filters, cut-off, page and rows are kept while a record is opened and closed. - Page specs that open CaMa follow-up answer the aggregate first. --- .../indicadores-analisis.service.ts | 6 + .../indicadores-analisis.testing.ts | 6 +- .../indicadores/indicadores-analisis.ts | 8 +- .../indicadores-initial-integration.spec.ts | 4 + .../indicadores/indicadores-sections.spec.ts | 2 + .../indicadores-seguimiento-cohorte.spec.ts | 159 ++++++++++++++++++ .../indicadores-seguimiento-ficha.spec.ts | 2 + .../indicadores-seguimiento-seleccion.spec.ts | 15 +- .../indicadores-seguimiento-tabla.ts | 122 +++++++++++--- .../indicadores/indicadores-tracking.html | 2 +- 10 files changed, 285 insertions(+), 41 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts diff --git a/src/app/features/indicadores/indicadores-analisis.service.ts b/src/app/features/indicadores/indicadores-analisis.service.ts index 3a25e35..16df001 100644 --- a/src/app/features/indicadores/indicadores-analisis.service.ts +++ b/src/app/features/indicadores/indicadores-analisis.service.ts @@ -17,6 +17,12 @@ export interface AnalisisAgregado { /** What a patients' list must quote back to open a group of the aggregate. */ export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; } +/** Today as the date input writes it, in the user's own calendar day. */ +export function hoyIso(ahora = new Date()) { + const dos = (n: number) => String(n).padStart(2, '0'); + return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`; +} + const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; // Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth. diff --git a/src/app/features/indicadores/indicadores-analisis.testing.ts b/src/app/features/indicadores/indicadores-analisis.testing.ts index 8c11455..1d9380e 100644 --- a/src/app/features/indicadores/indicadores-analisis.testing.ts +++ b/src/app/features/indicadores/indicadores-analisis.testing.ts @@ -21,15 +21,15 @@ export const agregado = (extra: Partial = {}): AnalisisAgregad * 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; +export function listaCohorte(o: { corte?: string; filtros?: Record; page?: number; size?: number; n?: number; meses?: number; revision?: string } = {}): Record { + const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0, revision = REVISION } = 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', + simulado: true, ...CONTEXTO, revision, 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']) }, diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index 7898b46..d727124 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -9,7 +9,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { isoDate } from './cacu-seguimiento.models'; import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; import { etiquetaBirads } from './etiquetas-cohorte'; -import { AnalisisAgregado, AnalisisService, ContextoCohorte } from './indicadores-analisis.service'; +import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service'; import { Dominio, Tema } from './indicadores.models'; type Carga = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' }; @@ -23,11 +23,7 @@ export interface SeleccionPacientes { filtros: Record; etiqueta: export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.'; -/** Today as the date input writes it, in the user's own calendar day. */ -export function hoyIso(ahora = new Date()) { - const dos = (n: number) => String(n).padStart(2, '0'); - return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`; -} +export { hoyIso }; /** Why a group cannot open its patients, or nothing when it can: only a published group does. */ export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined { diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 267d869..34bef33 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -84,6 +84,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const ongoing = request(periods[0]); for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { page.changeSection(section); fixture.detectChanges(); + // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. + for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.initialPeriodState()).toBe('loading'); expect(ongoing.cancelled).toBe(false); @@ -104,6 +106,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid editor().select([periods[2]]); fixture.detectChanges(); for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { page.changeSection(section); fixture.detectChanges(); + // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. + for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(editor().selectedPeriods).toEqual([periods[2]]); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 0a41c2e..272ed9b 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -55,6 +55,8 @@ describe('Secciones compartidas por dominio', () => { pestana('seguimiento').click(); harness.detectChanges(); // CaCu and CaMa request their own follow-up when the tab opens; the lab WebApi has neither yet (404). if (domain !== 'tea') { + // CaMa asks for the cohort's revision first and reads the plain list when the cohort is not published. + if (domain === 'cama') { http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Pending' }); } http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); } diff --git a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts new file mode 100644 index 0000000..00f5196 --- /dev/null +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -0,0 +1,159 @@ +// 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 +// 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; + const hoy = hoyIso(); + 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('cohorte', true); fixture.componentRef.setInput('active', false); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const root = () => fixture.nativeElement as HTMLElement; + const agregado = (corte = hoy) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte); + const lista = () => 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 abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); }; + const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined; + const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; + const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim()); + async function escribir(nombre: string, valor: string) { + const c = root().querySelector(`input[name="${nombre}"]`) as HTMLInputElement; c.value = valor; c.dispatchEvent(new Event('input')); await asentar(); + } + async function elegir(etiqueta: string, valor: string) { + const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar(); + } + // The cohort's answer opens the list on the whole cohort. + async function abierta(corte = hoy) { + abrir(); agregado(corte).flush(agregadoJson({ corte })); + lista().flush(listaCohorte({ corte, n: 27 })); await asentar(); + } + + it('al abrir pide la revisión de la cohorte a la fecha de hoy y luego toda la cohorte citándola, sin banner de selección', async () => { + // Fails if the habitual access still reads another source, opens on a window of months, or shows an analysis banner. + http.expectNone(() => true); + abrir(); + agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: hoy, ...CONTEXTO }); + r.flush(listaCohorte({ corte: hoy, n: 27 })); await asentar(); + expect(root().querySelector('.seleccion')).toBeNull(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']); + expect(root().textContent).toContain(`Ventana consultada: Toda la cohorte, al ${hoy}.`); + expect(root().querySelectorAll('tbody tr')).toHaveLength(27); + 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. + 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); + http.verify(); + } + }); + it('un error del agregado se dice y el reintento vuelve a pedir la revisión', async () => { + // Fails if a failing aggregate leaves a blank list or the retry reads the list without a revision. + abrir(); + agregado().flush('detalle interno', { status: 500, statusText: 'Error' }); await asentar(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('No se pudo consultar el seguimiento'); + expect(root().textContent).not.toContain('detalle interno'); + boton('Reintentar seguimiento')!.click(); fixture.detectChanges(); + http.expectNone(r => r.url === '/cama/seguimiento'); + // the retry repeats the query as it was: with the revision asked for first + agregado(); + }); + it('si el usuario cambia el corte, pide la revisión de ese corte antes de la lista y la cita', async () => { + // Fails if a list at another cut-off is asked for with the revision of the previous one. + await abierta(); + await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges(); + agregado('2026-09-01').flush(agregadoJson({ corte: '2026-09-01', revision: OTRA })); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toMatchObject({ corte: '2026-09-01', revision: OTRA, meses: '0' }); + r.flush(listaCohorte({ corte: '2026-09-01', n: 27, revision: OTRA })); await asentar(); + expect(root().querySelectorAll('tbody tr')).toHaveLength(27); + }); + it('si la cohorte cambia bajo la lista (409), pide la revisión de nuevo una vez y repite la misma consulta; un segundo 409 sí se dice', async () => { + // Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops. + await abierta(); + boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); + agregado(hoy).flush(agregadoJson({ corte: hoy, revision: OTRA })); fixture.detectChanges(); + let r = lista(); + expect(parametros(r)).toMatchObject({ revision: OTRA, corte: hoy }); + r.flush(listaCohorte({ corte: hoy, n: 27, revision: OTRA })); await asentar(); + expect(root().querySelector('[role=alert]')).toBeNull(); + // A conflict that persists is reported, not retried forever. + boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); + agregado(hoy).flush(agregadoJson({ corte: hoy, revision: REVISION })); fixture.detectChanges(); + r = lista(); r.flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis'); + expect(root().querySelector('table')).toBeNull(); + }); + it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => { + // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow filter as an empty cohort. + abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 0 })); await asentar(); + expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.'); + expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true); + await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar(); + expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); + }); + it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => { + // Fails if opening the record resets the form, the page or the rows the user was reading. + abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10 })); await asentar(); + await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar(); + boton('Siguiente')!.click(); fixture.detectChanges(); + const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: hoy, ...CONTEXTO }); + r.flush(listaCohorte({ corte: hoy, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar(); + const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim()); + (root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar(); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${hoy}.`); + ([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar(); + http.expectNone(() => true); + expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); + const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement; + expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años'); + expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(hoy); + }); + it('con una selección del análisis, «Quitar selección» regresa a este mismo acceso habitual', async () => { + // Fails if leaving the selection drops the user into a different source than the one the tab opens on. + abrir(); agregado().flush(agregadoJson({ corte: CORTE })); lista().flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); + fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id: 1 }); + fixture.detectChanges(); + lista().flush(listaCohorte({ corte: CORTE, n: 27, filtros: { birads: 'BIRADS_5' } })); await asentar(); + expect(root().querySelector('.seleccion')).not.toBeNull(); + boton('Quitar selección')!.click(); fixture.detectChanges(); + const r = lista(); expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); + expect(root().querySelector('.seleccion')).toBeNull(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index f6ab443..e385e79 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -108,6 +108,8 @@ 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()); await fixture.whenStable(); fixture.detectChanges(); (fixture.nativeElement as HTMLElement).querySelector('.patient-link')!.click(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts index 9770bd1..2f00a32 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -6,7 +6,7 @@ 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 { CONTEXTO, CORTE } from './indicadores-analisis.testing'; +import { agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; const base = () => structuredClone(fixtureData) as unknown as Record; @@ -118,6 +118,8 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { const c = root().querySelector('input[name="corte"]') as HTMLInputElement; c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); + // Another cut-off is another cohort at that date: its revision is asked for first. + http.expectOne(a => a.url === '/cama/analisis/indicadores' && a.params.get('corte') === c.value).flush(agregadoJson({ corte: c.value })); fixture.detectChanges(); const r = solicitud(); expect(r.request.params.get('corte'), String(status)).toBe(c.value); r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar(); @@ -193,17 +195,18 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(root().querySelector('.diferencia')).toBeNull(); expect(ventanas()).toContain('Toda la cohorte'); }); - it('«Quitar selección» sale de la cohorte: 3 meses, sin filtros y sin citar la revisión', async () => { - // Fails if removing the selection leaves its filters, the whole cohort or the cohort's revision behind. + it('«Quitar selección» vuelve a la cohorte completa, sin filtros ni nombre, y sigue citando su revisión', async () => { + // Fails if removing the selection leaves its filter behind, or leaves the cohort for another source. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); boton('Quitar selección')!.click(); fixture.detectChanges(); const r = solicitud(); - expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); - r.flush({ ...base(), filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: null } }); await asentar(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(cohorte({})); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); - expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + expect(ventanas()).toContain('Toda la cohorte'); + expect(exportar()).not.toBeNull(); }); it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => { // Fails if a selection (or its cohort) made in one domain survives into another. diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index c332f70..7f5dd0a 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 { AnalisisService, hoyIso } from './indicadores-analisis.service'; 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'; @@ -13,9 +14,12 @@ import { } from './seguimiento-tabla.service'; type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error'; -type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string }; -/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */ -type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string }; +type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string; estatus?: number }; +/** + * A request with the name of the selection it belongs to, so the answer and its name can never be told apart. + * `refrescar`: the cohort's revision is asked for first (at the query's cut-off, or today's), because the list is read from the cohort. + */ +type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string; refrescar?: boolean; reintento?: boolean }; // What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the // list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click. export interface SeleccionSeguimiento { @@ -101,7 +105,7 @@ const mismosFiltros = (a: Record, b: Record@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]) }} } } } - } @empty { No hay registros para los filtros aplicados. } + } @empty { {{ textoVacio(respuesta) }} } @@ -150,7 +154,13 @@ export class IndicadoresSeguimientoTabla implements OnChanges { @Input() domainLabel = ''; // The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again. @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. + */ + @Input() cohorte = false; private readonly service = inject(SeguimientoTablaService); + private readonly analisis = inject(AnalisisService); private readonly injector = inject(Injector); /** Tells the page that an individual record replaced the list, so it can retitle itself. */ readonly fichaAbierta = output(); @@ -196,26 +206,65 @@ export class IndicadoresSeguimientoTabla implements OnChanges { 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.`; } + // 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; + + /** The list of one query, as the server answers it (without the loading state). */ + private lista(c: Consulta): Observable { + const { q, etiqueta } = c; + let peticion: Observable; + // An invalid query never leaves the browser; it reads like the server's own 400. + try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); } + return peticion.pipe( + // A selection names its patients: an answer that does not apply its window, cut-off and every filter is dropped, + // because its rows would pass for the analysis' group. A plain query shows what the answer says it applied. + map((data): Resultado => { + if ((etiqueta || q.contexto) && !consultaAplicada(q, data)) throw new SeguimientoNoCoincide('La respuesta no corresponde a la consulta'); + return { estado: 'ready', data, mensaje: '', etiqueta }; + }), + 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. */ + 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.' }); } + return agregado.pipe( + map((a): Consulta => { + this.contextoActivo = { cohorte: a.cohorte, escenario: a.escenario, revision: a.revision }; this.contextoCorte = a.corte; + 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 } }); + } + return of(this.fallo(error, c.q)); + })); + } + constructor() { this.consultas.pipe( switchMap((c): Observable => { if (!c) return of({ estado: 'idle', mensaje: '' }); - const { q, etiqueta } = c; - let peticion: Observable; - // An invalid query never leaves the browser; it reads like the server's own 400. - try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); } - return peticion.pipe( - // A selection names its patients: an answer that does not apply its window, cut-off and every filter is dropped, - // because its rows would pass for the analysis' group. A plain query shows what the answer says it applied. - map((data): Resultado => { - if ((etiqueta || q.contexto) && !consultaAplicada(q, data)) throw new SeguimientoNoCoincide('La respuesta no corresponde a la consulta'); - return { estado: 'ready', data, mensaje: '', etiqueta }; - }), - catchError(error => of(this.fallo(error, q))), + const preparada = c.refrescar ? this.refrescar(c) : of(c); + return preparada.pipe( + switchMap(x => 'estado' in x ? of(x) : this.lista(x)), startWith({ estado: 'loading', mensaje: '' })); }), takeUntilDestroyed(inject(DestroyRef)), ).subscribe(r => { + // The cohort changed under a plain list: the revision is asked for again, once, before the user hears of it. + if (r.estatus === 409 && !this.activa && this.contextoActivo && !this.reintentoHecho) { + this.reintentoHecho = true; + this.consultas.next({ q: { ...this.applied, contexto: undefined }, refrescar: true, etiqueta: this.appliedEtiqueta }); + return; + } + if (r.estado === 'ready') this.reintentoHecho = false; this.estado.set(r.estado); this.mensaje.set(r.mensaje); if (r.estado === 'idle') { this.data.set(undefined); this.etiquetaDatos.set(undefined); this.filtros.set([]); } @@ -233,11 +282,13 @@ 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.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined); } const sel = this.seleccion; if (this.active && sel && sel.id !== this.seleccionAplicada) { - this.seleccionAplicada = sel.id; this.iniciado = true; this.activa = sel; this.contextoActivo = sel.contexto; + this.seleccionAplicada = sel.id; this.iniciado = true; this.activa = sel; this.contextoActivo = sel.contexto; this.contextoCorte = sel.corte; + this.reintentoHecho = false; // Whatever was on screen belongs to another query: it goes before the selection is asked for. this.data.set(undefined); this.etiquetaDatos.set(undefined); if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); } @@ -245,10 +296,20 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.aplicar(sel.etiqueta); return; } - if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next({ q: this.applied }); } + if (this.active && !this.iniciado) { + this.iniciado = true; + if (this.cohorte && !this.sinCohorte) { + // 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 }); + } else this.consultas.next({ q: this.applied }); + } } private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado { + return { ...this.falloBase(error, q), estatus: error instanceof HttpErrorResponse ? error.status : undefined }; + } + 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 && 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.' }; @@ -275,26 +336,32 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record; const activa = this.activa, contexto = this.contextoActivo; const exacta = !!seleccion || (!!activa && this.draft.meses === 0 && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte)); - // In the analysis' cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months. - const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto ? ETIQUETA_COHORTE : undefined); + // In the cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months. + // The banner names the analysis' selection, or the cohort of the analysis once the user has refined it. + const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto && activa ? ETIQUETA_COHORTE : undefined); if (!contexto && this.draft.meses === 0) this.draft = { ...this.draft, meses: 3 }; this.seleccionMostrada.set(etiqueta); this.seleccionExacta.set(!!etiqueta && exacta); this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined); this.appliedEtiqueta = etiqueta; - const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, contexto }; + // Another cut-off is another cohort at that date: its revision is asked for before the list. + const refrescar = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; + const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, + contexto: refrescar ? undefined : contexto }; // A new query of the cohort starts from nothing on screen: what was there belongs to the previous one. if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); } this.applied = q; - this.consultas.next({ q, etiqueta }); + this.consultas.next({ q, etiqueta, refrescar }); } + // Leaving the analysis' selection returns to the whole cohort (the habitual list), not to another source. quitarSeleccion() { - this.draft = { ...this.draft, meses: 3, filtros: {} }; - this.activa = undefined; this.contextoActivo = undefined; + this.draft = { ...this.draft, meses: this.contextoActivo ? 0 : 3, filtros: {} }; + this.activa = undefined; this.aplicar(); } ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); } - reintentar() { this.consultas.next({ q: this.applied, 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 }); } 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. @@ -313,6 +380,11 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const control = this.controlFicha; afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector }); } + // The cohort answers an empty page only for a whole cohort without filters that has no patient at the cut-off. + textoVacio(r: SeguimientoTablaResponse) { + const sinFiltros = Object.values(r.filtros).every(v => !v); + 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 ?? []; } 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..c32f06c 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -6,7 +6,7 @@
@if (dominio !== 'cama') {

Seguimiento de {{ domainLabel }}

} @if (dominio === 'cama') { - } @else if (dominio !== 'cacu') {

El seguimiento aún no está disponible.