From 0acee49de2098b2f9d06607f7d374091a5f4b764 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:43:02 -0600 Subject: [PATCH] fix(cama): regular follow-up opens on the 3-month window and adopts the cohort the server returns The follow-up list asks for the regular window without quoting a revision; when the answer names a cohort the next pages and the files quote it. A new cut-off or a revision that changed under the list is asked for again without the old revision (once, then reported). Leaving the analysis' selection returns to the regular window. A server that does not answer from the cohort keeps the plain list. Histopathology codes are written with the catalog labels (Benigno, Carcinoma in situ, Carcinoma invasor, Desconocido); other values stay as they arrive. --- .../features/indicadores/etiquetas-cohorte.ts | 6 +- .../indicadores-initial-integration.spec.ts | 4 - .../indicadores/indicadores-sections.spec.ts | 2 - .../indicadores-seguimiento-cohorte.spec.ts | 158 +++++++++--------- .../indicadores-seguimiento-ficha.spec.ts | 2 - .../indicadores-seguimiento-seleccion.spec.ts | 13 +- .../indicadores-seguimiento-tabla.ts | 77 +++------ .../indicadores/indicadores-tracking.html | 2 +- .../indicadores/seguimiento-tabla.service.ts | 2 +- 9 files changed, 110 insertions(+), 156 deletions(-) diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts index 09dae04..c67ecd6 100644 --- a/src/app/features/indicadores/etiquetas-cohorte.ts +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -5,6 +5,8 @@ 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', }; +// The CaMa catalog's labels for the histopathology codes the list carries; a code it does not list stays as it arrives. +const BIOPSIA: Readonly> = { BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido' }; 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. */ @@ -12,7 +14,9 @@ export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS /** «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 }; +/** «CARCINOMA_INVASOR» as «Carcinoma invasor». */ +export const etiquetaBiopsia = (codigo: string) => BIOPSIA[codigo] ?? codigo; +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaBiopsia }; /** 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-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 34bef33..267d869 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -84,8 +84,6 @@ 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); @@ -106,8 +104,6 @@ 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 272ed9b..0a41c2e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -55,8 +55,6 @@ 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 index 00f5196..e60b013 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -1,30 +1,27 @@ -// 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. +// Covers the habitual access to Seguimiento of breast cancer: the list opens on the regular window and, when the server +// answers from the cohort, adopts the cohort and its revision for the next pages and the files; a cut-off or a changed +// revision is asked for without the old revision; and the filters, the cut-off, the page and the rows are kept while the +// record is opened and closed. Fixtures: indicadores-analisis.testing.ts (listaCohorte) and fixtures/cama_seguimiento.json. 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 { CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; 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', () => { +describe('Seguimiento de CaMa: acceso habitual', () => { 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(); + 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(); } @@ -38,122 +35,121 @@ describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { 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(); + // The list opens on the regular window of 3 months and the cohort answers with its revision. + async function abierta(extra: Parameters[0] = {}) { + abrir(); lista().flush(listaCohorte({ meses: 3, n: 27, ...extra })); 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. + it('abre en la ventana habitual de 3 meses sin citar ninguna revisión, y adopta la cohorte que el servidor devuelve', async () => { + // Fails if the habitual access asks for another window, or needs a revision it cannot have yet, 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(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10 })); 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(); + expect(root().textContent).toContain('Ventana consultada: 2025-02-01 al 2026-10-20.'); + // The next page quotes the cohort the first answer named, with the same window and cut-off. + boton('Siguiente')!.click(); fixture.detectChanges(); + const p2 = lista(); + expect(parametros(p2)).toEqual({ meses: '3', page: '2', page_size: '10', corte: CORTE, ...CONTEXTO }); + p2.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2 })); await asentar(); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); }); - 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('«Toda la cohorte» pide la ventana 0 citando la cohorte', async () => { + // Fails if the whole cohort is asked for without the revision the server requires for it. + await abierta(); + await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ meses: 0, n: 43 })); await asentar(); + expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.'); + expect(root().querySelector('nav')?.textContent).toContain('43 registros'); }); - 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('un servidor sin cohorte responde la lista de siempre: sin «Toda la cohorte» y sin citar nada', async () => { + // Fails if a deployment without the cohort provider loses its follow-up list or is sent parameters it does not know. + abrir(); lista().flush(base()); await asentar(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + boton('Consultar')!.click(); fixture.detectChanges(); + expect(parametros(lista())).not.toHaveProperty('revision'); }); - it('si el usuario cambia el corte, pide la revisión de ese corte antes de la lista y la cita', async () => { + it('si el usuario cambia el corte, la consulta no cita la revisión del corte anterior y adopta la nueva', 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(); + expect(parametros(r)).toMatchObject({ corte: '2026-09-01', meses: '3' }); + expect(parametros(r)).not.toHaveProperty('revision'); + r.flush(listaCohorte({ meses: 3, n: 27, corte: '2026-09-01', revision: OTRA })); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); + expect(parametros(lista())).toMatchObject({ corte: '2026-09-01', revision: OTRA }); + }); + it('si la cohorte cambia bajo la lista (409), repite la misma consulta una vez sin la revisión vieja; 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({ size: 10 }); + boton('Siguiente')!.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(); + const r = lista(); + expect(parametros(r)).toMatchObject({ page: '2', meses: '3' }); + expect(parametros(r)).not.toHaveProperty('revision'); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, 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(); + lista().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(); + // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow window as an empty cohort. + await abierta({ n: 0 }); + expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); + await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ meses: 0, 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(); + lista().flush(listaCohorte({ meses: 0, 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 abierta({ size: 10 }); 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(); + lista().flush(listaCohorte({ meses: 3, 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 r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ meses: 3, 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}.`); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE}.`); ([...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); + expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(CORTE); }); - 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 }); + it('con una selección del análisis, «Quitar selección» regresa a la lista habitual: 3 meses, sin filtros ni revisión citada', async () => { + // Fails if leaving the selection keeps its filter, its window or the old revision. + await abierta(); + fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 43, contexto: { ...CONTEXTO, revision: REVISION }, id: 1 }); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: CORTE, n: 27, filtros: { birads: 'BIRADS_5' } })); await asentar(); + lista().flush(listaCohorte({ meses: 0, n: 43, 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(); + const r = lista(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); + r.flush(listaCohorte({ meses: 3, n: 27 })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); }); + it('la biopsia se escribe con las etiquetas del catálogo y un valor desconocido queda como llegó', async () => { + // Fails if a source code is remapped to a diagnosis the catalog does not name, or the code is lost. + abrir(); + const r = listaCohorte({ meses: 3, n: 4 }); const v = ['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'OTRO_VALOR']; r['items'].forEach((i: any, k: number) => { i['biopsia'] = v[k]; }); + lista().flush(r); await asentar(); + expect([...root().querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.replace(/\s+/g, ' ').trim().split(' Fecha')[0])).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'OTRO_VALOR']); + }); }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index e385e79..f6ab443 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -108,8 +108,6 @@ 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 2f00a32..7691581 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 { agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing'; +import { CONTEXTO, CORTE } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; const base = () => structuredClone(fixtureData) as unknown as Record; @@ -118,8 +118,6 @@ 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(); @@ -195,17 +193,16 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(root().querySelector('.diferencia')).toBeNull(); expect(ventanas()).toContain('Toda la cohorte'); }); - 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. + it('«Quitar selección» vuelve a la lista habitual: 3 meses, sin filtros ni nombre, y sin citar la revisión anterior', async () => { + // Fails if removing the selection leaves its filter, the whole-cohort window or the old revision behind. 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: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); - r.flush(cohorte({})); await asentar(); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); + r.flush(cohorte({}, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); - 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 () => { diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 7f5dd0a..7eb41d7 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -4,22 +4,18 @@ 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'; import { - consultaAplicada, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, + consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor, } from './seguimiento-tabla.service'; type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error'; 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 }; +/** 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 }; // 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 { @@ -154,13 +150,7 @@ 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(); @@ -206,11 +196,9 @@ 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. + // The cut-off of the cohort's revision: another cut-off is another cohort at that date, so its revision is not quoted. 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. + // A cohort that changed under a plain list is read again once, without the old revision, before it is reported. private reintentoHecho = false; /** The list of one query, as the server answers it (without the loading state). */ @@ -229,39 +217,18 @@ 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. */ - 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 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: '' })); + return this.lista(c).pipe(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. + // The cohort changed under a plain list: the same query is asked again, once, without the old revision, 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 }); + this.consultas.next({ q: { ...this.applied, contexto: undefined }, etiqueta: this.appliedEtiqueta }); return; } if (r.estado === 'ready') this.reintentoHecho = false; @@ -282,7 +249,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,11 +265,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } 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 }); + this.consultas.next({ q: this.applied }); } } @@ -329,6 +292,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges { 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])) }; this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size; + // A list read from the cohort says which one (and its revision): the next pages and the files quote it. + this.contextoActivo = contextoDe(data); this.contextoCorte = data.corte; + this.applied = { ...this.applied, contexto: this.contextoActivo }; } // The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort // included; anything else is the user's own query, with a window of months. @@ -344,24 +310,23 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.seleccionExacta.set(!!etiqueta && exacta); this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined); this.appliedEtiqueta = etiqueta; - // 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; + // Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one. + const otroCorte = !!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 }; + contexto: otroCorte ? 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, refrescar }); + this.consultas.next({ q, etiqueta }); } - // Leaving the analysis' selection returns to the whole cohort (the habitual list), not to another source. + // Leaving the analysis' selection returns to the habitual list: the regular window, no filters, the cohort's new revision. quitarSeleccion() { - this.draft = { ...this.draft, meses: this.contextoActivo ? 0 : 3, filtros: {} }; - this.activa = undefined; + this.draft = { ...this.draft, meses: 3, filtros: {} }; + this.activa = undefined; this.contextoActivo = undefined; this.aplicar(); } 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 }); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index c32f06c..1b537dc 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.

diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index e7a9637..f523b2f 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -122,7 +122,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR }), }; } -const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true }; +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true, biopsia: true }; @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService {