Use the regular window for breast follow-up

This commit is contained in:
Angel Capetillo Zavala
2026-11-13 15:44:01 -06:00
parent 18e9260705
commit 3783505dbd
7 changed files with 117 additions and 157 deletions
@@ -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]]);
@@ -55,20 +55,17 @@ 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();
}
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
if (domain === 'cacu') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else if (domain === 'cama') {
// Pending integration: the form is gone with no table, and the retry is offered.
expect(tracking.textContent).toContain('Funcionalidad pendiente de publicación');
// An unavailable cohort has no table and offers a retry.
expect(tracking.querySelector('table')).toBeNull();
expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull();
expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento');
@@ -1,28 +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), fails closed when the cohort is unavailable, asks for the
// revision again when the cut-off changes or the cohort changes under the list, and keeps the
// filters, the cut-off and the page while the record is opened and closed. Fixtures: indicadores-analisis.testing.ts.
// 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 { agregadoJson, CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing';
import { hoyIso } from './indicadores-analisis.service';
import fixtureData from './fixtures/cama_seguimiento.json';
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<string, any>;
describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => {
describe('Seguimiento de CaMa: acceso habitual', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, 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(); }
@@ -36,120 +35,128 @@ 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<typeof listaCohorte>[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.each([404, 503])('informa que la cohorte no está disponible ante %s y no cambia de fuente', async status => {
// Fails if an unavailable source is reported as an empty list or another source is queried.
abrir(); lista().flush({ error: 'x' }, { status, statusText: 'Unavailable' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible');
http.expectNone(r => r.url === '/cama/seguimiento');
});
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 la cohorte no está disponible (404 o 503), informa el error sin cambiar de fuente', async () => {
// Fails if an unavailable cohort can silently broaden or replace the population.
for (const status of [404, 503]) {
TestBed.resetTestingModule();
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', true); fixture.detectChanges();
agregado().flush({ error: 'x' }, { status, statusText: 'x' }); fixture.detectChanges();
await asentar();
http.expectNone(r => r.url === '/cama/seguimiento');
expect(root().querySelector('[role=alert]')?.textContent, String(status)).toContain('La cohorte no está disponible');
http.verify();
}
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']);
});
});
@@ -5,8 +5,6 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import fixtureData from './fixtures/cama_seguimiento.json';
import { agregadoJson, listaCohorte } from './indicadores-analisis.testing';
import { hoyIso } from './indicadores-analisis.service';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { IndicadoresTracking } from './indicadores-tracking';
@@ -110,10 +108,7 @@ 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();
// The record is opened from the same cohort that the analysis publishes.
const corte = hoyIso();
http.expectOne(r => r.url === '/cama/analisis/indicadores').flush(agregadoJson({ corte }));
http.expectOne(r => r.url === '/cama/seguimiento').flush(listaCohorte({ corte, n: 6 }));
http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina());
await fixture.whenStable(); fixture.detectChanges();
(fixture.nativeElement as HTMLElement).querySelector<HTMLButtonElement>('.patient-link')!.click();
await fixture.whenStable(); fixture.detectChanges();
@@ -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<string, any>;
@@ -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 () => {
@@ -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, contextoDe, 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. An unavailable cohort is reported without switching sources.
*/
@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<boolean>();
@@ -206,9 +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;
// 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). */
@@ -227,37 +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). */
private refrescar(c: Consulta): Observable<Consulta | Resultado> {
let agregado;
try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of<Resultado>({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); }
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<Consulta | Resultado> => {
if (error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503))
return of<Resultado>({ estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' });
return of(this.fallo(error, c.q));
}));
}
constructor() {
this.consultas.pipe(
switchMap((c): Observable<Resultado> => {
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<Resultado>({ estado: 'loading', mensaje: '' }));
return this.lista(c).pipe(startWith<Resultado>({ 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;
@@ -294,11 +265,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
}
if (this.active && !this.iniciado) {
this.iniciado = true;
if (this.cohorte) {
// The habitual access: the whole cohort at today's cut-off, with the revision the server publishes for it.
this.draft = { ...this.draft, meses: 0 }; this.applied = { meses: 0, page: 1, page_size: this.applied.page_size };
this.consultas.next({ q: this.applied, refrescar: true });
} else this.consultas.next({ q: this.applied });
this.consultas.next({ q: this.applied });
}
}
@@ -306,8 +273,8 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
return { ...this.falloBase(error, q), estatus: error instanceof HttpErrorResponse ? error.status : undefined };
}
private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado {
if (error instanceof HttpErrorResponse && error.status === 404 && this.dominio === 'cama') return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' };
// A first page that does not exist yet is the list's own pending state; a later page that fails is an error.
if (error instanceof HttpErrorResponse && error.status === 404 && this.cohorte) return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' };
if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' };
if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' };
// A cohort's list: the group was too small to publish or access was not granted; the cohort changed after the count; or it is not configured.
@@ -324,9 +291,11 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
const claves = new Set(data.filtros_disponibles.map(f => f.clave));
this.draft = { ...this.draft, corte: data.corte, filtros: Object.fromEntries(Object.entries(this.draft.filtros).filter(([k]) => claves.has(k))) };
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size,
filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])),
contexto: contextoDe(data) };
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.
@@ -342,24 +311,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.applied.contexto }); }
reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta }); }
abrirFicha(item: Record<string, SeguimientoValor>, evento: Event) {
const origen = evento.target instanceof HTMLElement ? evento.target : null;
// A click on the row opens the record unless it landed on another control; the id button always does.
@@ -6,7 +6,7 @@
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
@if (dominio !== 'cama') { <h2>Seguimiento de {{ domainLabel }}</h2> }
@if (dominio === 'cama') {
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" [cohorte]="true" (fichaAbierta)="cambiaFichaCama($event)"
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
(volverAlAnalisis)="volverAlAnalisis.emit()" />
} @else if (dominio !== 'cacu') {
<p>El seguimiento aún no está disponible.</p>