// Covers the files of a list opened from the analysis: they state the selection, the cut-off and «Toda la cohorte», and // hold exactly the patients the table holds, over several pages; and an export never outlives the query it was made for. // Fixture: fixtures/cama_seguimiento.json, whose rows are repeated to make a list of several pages. import { TestBed } from '@angular/core/testing'; import { Observable, of, Subject } from 'rxjs'; import { strFromU8, unzipSync } from 'fflate'; import fixtureData from '../fixtures/cama_seguimiento.json'; import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from '../seguimiento-tabla.service'; import { TrackingExportBar } from './tracking-export-bar'; import { CONTEXTO } from '../indicadores-analisis.testing'; import { fetchAllTracking, queryOf } from './tracking-export-source'; import { TrackingSnapshot } from './tracking-export.models'; import { trackingDocument } from './tracking-pdf'; import { buildTrackingXlsx } from './tracking-xlsx'; const ETIQUETA = 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 5'; const base = () => structuredClone(fixtureData) as unknown as Record; // A cohort of `n` patients, M-0001 onwards, served in the pages that were asked for, with the filters it applied. function cohorte(n: number) { const plantilla = (base()['items'] as Record[])[0]; const todos = Array.from({ length: n }, (_, i) => ({ ...plantilla, id_seudonimo: `M-${String(i + 1).padStart(4, '0')}` })); return (q: SeguimientoTablaQuery): SeguimientoTablaResponse => seguimientoTablaResponse({ ...base(), ventana: { meses: q.meses, desde: '2025-01-01', hasta: '2026-10-20' }, corte: q.corte ?? '2026-10-20', filtros: { ...base()['filtros'], ...q.filtros }, ...(q.contexto ?? {}), paginacion: { page: q.page, page_size: q.page_size, total_items: n, total_pages: Math.ceil(n / q.page_size) }, items: todos.slice((q.page - 1) * q.page_size, q.page * q.page_size), }); } const consulta = (extra: Partial = {}): SeguimientoTablaQuery => ({ corte: '2026-10-20', meses: 0, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO, ...extra }); const textos = (nodo: unknown, salida: string[] = []): string[] => { if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida)); return salida; }; describe('Archivos de una selección del análisis', () => { const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery) => of(cohorte(450)(q)) } as unknown as SeguimientoTablaService; it('el PDF y el XLSX dicen la selección, el corte y «Toda la cohorte», y traen los mismos pacientes que la tabla en todas sus páginas', async () => { // Fails if a file loses the selection, calls the whole cohort «0 meses», or its patients differ from the table's pages. const q = consulta(); // The table, page by page (50 per page), as the user would walk it. const filasTabla: string[] = []; for (let p = 1; p <= 9; p++) filasTabla.push(...cohorte(450)({ ...q, page: p }).items.map(i => String(i['id_seudonimo']))); let snapshot!: TrackingSnapshot; await new Promise((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = { ...e.snapshot, seleccion: ETIQUETA }; }, error: fallo, complete: ok })); expect(snapshot.items.map(i => String(i['id_seudonimo']))).toEqual(filasTabla); expect(new Set(filasTabla).size).toBe(450); const pdf = textos(trackingDocument(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)), 'data:image/png;base64,AAAA')); expect(pdf).toContain('Selección del análisis'); expect(pdf).toContain(ETIQUETA); expect(pdf).toContain('Fecha de corte'); expect(pdf).toContain('2026-10-20'); expect(pdf).toContain('Toda la cohorte, al 2026-10-20'); expect(pdf.some(t => /0 meses/.test(t))).toBe(false); expect(pdf.filter(t => /^M-\d{4}$/.test(t))).toEqual(filasTabla); const PROHIBIDO = /simulad|sint[eé]tic|entorno|\bdev\b|prueba|demostraci|ficticio|mock|valor cl[ií]nico/i; expect(pdf.filter(t => PROHIBIDO.test(t))).toEqual([]); const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, new Date(Date.UTC(2026, 10, 13, 18, 0)))).arrayBuffer())); const cadenas = strFromU8(hojas['xl/sharedStrings.xml']); expect(cadenas).toContain(ETIQUETA); expect(cadenas).toContain('Selección del análisis'); expect(cadenas).toContain('Toda la cohorte, al 2026-10-20'); expect(cadenas).not.toMatch(/0 meses/); expect(cadenas.replace(/<[^>]+>/g, ' ')).not.toMatch(PROHIBIDO); expect([...cadenas.matchAll(/M-\d{4}/g)].map(m => m[0]).filter((v, i, a) => a.indexOf(v) === i)).toEqual(filasTabla); }); it('sin una selección los archivos no llevan esa línea y conservan la ventana de meses', async () => { // Fails if a plain list gets a selection line, or a window of months stops being written as dates and months. const q = consulta({ meses: 3, filtros: {} }); let snapshot!: TrackingSnapshot; await new Promise((ok, fallo) => fetchAllTracking(servicio, 'cama', { ...q, page_size: 200 }, 1000).subscribe({ next: e => { if (e.kind === 'done') snapshot = e.snapshot; }, error: fallo, complete: ok })); const pdf = textos(trackingDocument(snapshot, new Date(), 'data:image/png;base64,AAAA')); expect(pdf).not.toContain('Selección del análisis'); expect(pdf).toContain('2025-01-01 al 2026-10-20 (3 meses)'); }); it('la consulta de una respuesta conserva la cohorte y su revisión, y todas las páginas del archivo la citan', async () => { // Fails if the export reads a cohort's list without quoting its revision (the server refuses it) or from another one. const respuesta = cohorte(450)(consulta()); expect(queryOf(respuesta)).toMatchObject({ corte: '2026-10-20', meses: 0, page: 1, page_size: 200, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO }); const pedidas: SeguimientoTablaQuery[] = []; const espia = { consultar: (_d: string, q: SeguimientoTablaQuery) => { pedidas.push(q); return of(cohorte(450)(q)); } } as unknown as SeguimientoTablaService; await new Promise((ok, fallo) => fetchAllTracking(espia, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok })); expect(pedidas.map(q => q.page).sort()).toEqual([1, 2, 3]); expect(pedidas.every(q => q.contexto?.revision === CONTEXTO.revision && q.contexto?.cohorte === CONTEXTO.cohorte && q.meses === 0)).toBe(true); // A plain list quotes no cohort. expect(queryOf(seguimientoTablaResponse(base())).contexto).toBeUndefined(); }); it('una página posterior de otra revisión hace fallar la lectura', async () => { // Fails if a file mixes pages of two revisions of the cohort. const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, contexto: { ...CONTEXTO, revision: 'f'.repeat(64) } }) : cohorte(450)(q)); const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService; const error = await new Promise(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) })); expect(error).toBeInstanceOf(Error); }); it('una página posterior que pierde un filtro hace fallar la lectura: no se exporta un subconjunto de otra consulta', async () => { // Fails if a file mixes the pages of the selection with a page of another population. const respuestas = (q: SeguimientoTablaQuery) => of(q.page === 2 ? cohorte(450)({ ...q, filtros: {} }) : cohorte(450)(q)); const malo = { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } as unknown as SeguimientoTablaService; const error = await new Promise(ok => fetchAllTracking(malo, 'cama', { ...consulta(), page_size: 200 }, 1000).subscribe({ error: ok, complete: () => ok(undefined) })); expect(error).toBeInstanceOf(Error); }); }); describe('Exportación: la consulta cambia mientras se exporta', () => { let respuestas: (q: SeguimientoTablaQuery) => Observable, descargas: string[]; let fixture: ReturnType>; beforeEach(() => { descargas = []; respuestas = q => of(cohorte(27)(q)); TestBed.configureTestingModule({ providers: [{ provide: SeguimientoTablaService, useValue: { consultar: (_d: string, q: SeguimientoTablaQuery) => respuestas(q) } }] }); vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test'); vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); }); }); afterEach(() => { fixture?.destroy(); vi.restoreAllMocks(); }); const montar = (r: SeguimientoTablaResponse, seleccion?: string) => { fixture = TestBed.createComponent(TrackingExportBar); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('respuesta', r); fixture.componentRef.setInput('seleccion', seleccion); fixture.detectChanges(); return fixture.nativeElement as HTMLElement; }; const excel = (root: HTMLElement) => [...root.querySelectorAll('button')].find(b => b.textContent!.includes('Excel')) as HTMLButtonElement; const esperar = async () => { for (let i = 0; i < 20; i++) { await fixture.whenStable(); await new Promise(r => setTimeout(r, 10)); fixture.detectChanges(); } }; it('un archivo de una selección se llama como tal y no lleva a ningún paciente en el nombre', async () => { // Fails if the file of a selection is told apart from a plain list by nothing, or names a patient. const root = montar(cohorte(27)(consulta()), ETIQUETA); excel(root).click(); await esperar(); expect(descargas).toHaveLength(1); expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-10-20_\d{8}-\d{4}\.xlsx$/); expect(descargas[0]).not.toMatch(/M-\d|cama/i); }); it('si la consulta en pantalla cambia mientras se lee, se cancela y no se descarga nada', async () => { // Fails if a list read for the old selection is downloaded as the one now on screen. const lenta = new Subject(); respuestas = () => lenta; const root = montar(cohorte(27)(consulta()), ETIQUETA); excel(root).click(); fixture.detectChanges(); expect(root.textContent).toContain('Preparando exportación'); fixture.componentRef.setInput('respuesta', cohorte(27)(consulta({ filtros: { birads: 'BIRADS_6' } }))); fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges(); lenta.next(cohorte(27)(consulta())); await esperar(); expect(descargas).toEqual([]); expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió; se canceló la exportación'); expect(excel(root).disabled).toBe(false); }); it('si cambia mientras se genera el archivo, tampoco se descarga', async () => { // Fails if a file finished after the selection changed still reaches the downloads. const root = montar(cohorte(27)(consulta()), ETIQUETA); excel(root).click(); fixture.componentRef.setInput('seleccion', 'Cáncer confirmado: Categoría BI-RADS, BI-RADS 6'); fixture.detectChanges(); await esperar(); expect(descargas).toEqual([]); expect(root.querySelector('[role=alert]')?.textContent).toContain('La consulta cambió'); }); });