diff --git a/src/app/features/indicadores/export/download-file.ts b/src/app/features/indicadores/export/download-file.ts index 78ef5a4..f04346c 100644 --- a/src/app/features/indicadores/export/download-file.ts +++ b/src/app/features/indicadores/export/download-file.ts @@ -4,7 +4,7 @@ const pad = (n: number) => String(n).padStart(2, '0'); * Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a * patient identifier, because file names end up in download lists, backups and mail attachments. */ -export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string { +export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string { const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`; return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`; } diff --git a/src/app/features/indicadores/export/tracking-export-bar.ts b/src/app/features/indicadores/export/tracking-export-bar.ts index d5be694..3e6f757 100644 --- a/src/app/features/indicadores/export/tracking-export-bar.ts +++ b/src/app/features/indicadores/export/tracking-export-bar.ts @@ -1,5 +1,6 @@ import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; import { DecimalPipe } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { Dominio } from '../indicadores.models'; import { SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; @@ -54,6 +55,8 @@ export class TrackingExportBar { readonly respuesta = input.required(); /** False while a page is being loaded, so the export never reads a query that is about to change. */ readonly habilitado = input(true); + /** How the analysis named the selection this answer belongs to; it travels into the files. */ + readonly seleccion = input(undefined); private readonly service = inject(SeguimientoTablaService); private subscription?: Subscription; @@ -73,13 +76,22 @@ export class TrackingExportBar { // Identifies the query on screen: paging through its pages keeps it, changing a filter or the cut-off replaces it. private readonly queryKey = computed(() => { const r = this.respuesta(); - return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items]); + return JSON.stringify([r.corte, r.ventana.meses, r.filtros, r.paginacion.total_items, this.seleccion() ?? null]); }); constructor() { inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe()); - // A result message belongs to the query it was made for: it goes away when another query is shown. - effect(() => { this.queryKey(); untracked(() => { if (this.estado() !== 'working') { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); } }); }); + // A result message belongs to the query it was made for: it goes away when another query is shown. An export still + // being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one. + effect(() => { + this.queryKey(); + untracked(() => { + if (this.estado() === 'working') { + this.subscription?.unsubscribe(); + this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.'); + } else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); } + }); + }); } available(formato: ExportFormat): boolean { @@ -90,10 +102,11 @@ export class TrackingExportBar { if (!this.available(formato)) return; this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 }); this.subscription?.unsubscribe(); + const clave = this.queryKey(), seleccion = this.seleccion(); this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({ next: event => { if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total }); - else void this.generar(formato, event.snapshot); + else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave); }, error: error => this.fallar(error), }); @@ -104,13 +117,15 @@ export class TrackingExportBar { this.estado.set('idle'); } - private async generar(formato: ExportFormat, snapshot: TrackingSnapshot) { + private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) { try { // Each generator (and its library) downloads only when its button is used. const blob = formato === 'xlsx' ? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot) : await (await import('./tracking-pdf')).buildTrackingPdf(snapshot); - downloadBlob(blob, exportFilename('seguimiento-cancer-de-mama', snapshot.corte, formato)); + // The query on screen changed while the file was being made: it is not the one that was asked for. + if (clave !== this.queryKey()) return; + downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato)); this.estado.set('idle'); this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`); } catch { @@ -120,7 +135,10 @@ export class TrackingExportBar { private fallar(error: unknown) { this.estado.set('error'); - this.mensaje.set(error instanceof ExportLimitExceeded ? 'La consulta excede el límite de este formato. Acota los filtros.' + const estatus = error instanceof HttpErrorResponse ? error.status : 0; + this.mensaje.set(error instanceof ExportLimitExceeded || estatus === 413 ? 'La consulta excede el límite de este formato. Acota los filtros.' + : estatus === 403 ? 'No hay acceso para exportar esta lista, o la selección tiene muy pocos pacientes para publicarse.' + : estatus === 409 ? 'La cohorte cambió mientras se leía. Vuelve al análisis, consúltalo de nuevo y exporta otra vez.' : error instanceof ExportInconsistent ? 'La lista cambió mientras se leía. Vuelve a consultar e intenta de nuevo.' : 'No se pudo generar el archivo. Intenta nuevamente.'); } diff --git a/src/app/features/indicadores/export/tracking-export-seleccion.spec.ts b/src/app/features/indicadores/export/tracking-export-seleccion.spec.ts new file mode 100644 index 0000000..ef9f25c --- /dev/null +++ b/src/app/features/indicadores/export/tracking-export-seleccion.spec.ts @@ -0,0 +1,157 @@ +// 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ó'); + }); +}); diff --git a/src/app/features/indicadores/export/tracking-export-source.ts b/src/app/features/indicadores/export/tracking-export-source.ts index e0a0ad3..a778405 100644 --- a/src/app/features/indicadores/export/tracking-export-source.ts +++ b/src/app/features/indicadores/export/tracking-export-source.ts @@ -1,6 +1,6 @@ import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs'; import { Dominio } from '../indicadores.models'; -import { PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; +import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models'; const CONCURRENCY = 3; @@ -13,17 +13,14 @@ export function queryOf(response: SeguimientoTablaResponse): SeguimientoTablaQue page: 1, page_size: PAGE_SIZE_MAX, filtros: Object.fromEntries(Object.entries(response.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])), + // A cohort's list is exported as that cohort, at the revision it was read at: another revision is refused by the server. + contexto: contextoDe(response), }; } // The server must report having applied the window and the filters that were asked for; otherwise the file would // hold rows of another query under the title of this one. -function sameQuery(query: SeguimientoTablaQuery, answer: SeguimientoTablaResponse): boolean { - const entries = (filters: Record) => - JSON.stringify(Object.entries(filters).filter(([, v]) => !!v).sort(([a], [b]) => a.localeCompare(b))); - return answer.ventana.meses === query.meses && (!query.corte || answer.corte === query.corte) - && entries(query.filtros ?? {}) === entries(answer.filtros); -} +const sameQuery = consultaAplicada; /** * Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer. @@ -44,7 +41,7 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi mergeMap(page => ask({ ...pinned, page }).pipe(map(answer => ({ page, answer }))), CONCURRENCY), tap(({ page, answer }) => { if (answer.paginacion.page !== page || answer.paginacion.total_items !== total || answer.paginacion.total_pages !== pages - || answer.corte !== first.corte) throw new ExportInconsistent('The list changed while it was being read'); + || answer.corte !== first.corte || !sameQuery(pinned, answer)) throw new ExportInconsistent('The list changed while it was being read'); collected.set(page, answer.items); }), map((): TrackingExportEvent => ({ kind: 'progress', fetched: count(), total })), diff --git a/src/app/features/indicadores/export/tracking-export.models.ts b/src/app/features/indicadores/export/tracking-export.models.ts index 8a209d2..6a7a77a 100644 --- a/src/app/features/indicadores/export/tracking-export.models.ts +++ b/src/app/features/indicadores/export/tracking-export.models.ts @@ -1,4 +1,4 @@ -import { SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service'; +import { etiquetaVentana, SeguimientoTablaResponse, SeguimientoValor } from '../seguimiento-tabla.service'; /** Largest number of rows each format accepts. A query above the limit is refused, never truncated. */ export const EXPORT_LIMITS = { xlsx: 5000, pdf: 1000 } as const; @@ -8,6 +8,8 @@ export type TrackingRow = Record; /** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */ export interface TrackingSnapshot { + /** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */ + seleccion?: string; corte: string; ventana: SeguimientoTablaResponse['ventana']; filtros: SeguimientoTablaResponse['filtros']; @@ -16,6 +18,12 @@ export interface TrackingSnapshot { items: TrackingRow[]; } +/** The window as the files state it: the whole cohort up to the cut-off, or the dates and months of the window. */ +export function ventanaConsultada(snapshot: Pick): string { + const { meses, desde, hasta } = snapshot.ventana; + return meses === 0 ? `Toda la cohorte, al ${hasta}` : `${desde} al ${hasta} (${etiquetaVentana(meses)})`; +} + export type TrackingExportEvent = | { kind: 'progress'; fetched: number; total: number } | { kind: 'done'; snapshot: TrackingSnapshot }; diff --git a/src/app/features/indicadores/export/tracking-pdf.ts b/src/app/features/indicadores/export/tracking-pdf.ts index 0066847..ac8d13f 100644 --- a/src/app/features/indicadores/export/tracking-pdf.ts +++ b/src/app/features/indicadores/export/tracking-pdf.ts @@ -1,7 +1,7 @@ import { renderPdf, PdfDefinition } from './pdf-engine'; import { COLORS, institutionalDocument, loadLogo } from './pdf-template'; import { displayText, exportColumns } from './tracking-export-table'; -import { TrackingSnapshot } from './tracking-export.models'; +import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models'; export const TRACKING_TITLE = 'Cáncer de mama'; @@ -11,8 +11,9 @@ const zebra = { ...rule, fillColor: (row: number) => (row === 0 ? undefined : ro /** What the query was: cut-off, window, each announced filter with its chosen option, and how many rows follow. */ function parameters(snapshot: TrackingSnapshot) { const rows: unknown[][] = [ + ...(snapshot.seleccion ? [['Selección del análisis', snapshot.seleccion]] : []), ['Fecha de corte', snapshot.corte], - ['Ventana consultada', `${snapshot.ventana.desde} al ${snapshot.ventana.hasta} (${snapshot.ventana.meses} ${snapshot.ventana.meses === 1 ? 'mes' : 'meses'})`], + ['Ventana consultada', ventanaConsultada(snapshot)], ...snapshot.filtros_disponibles.map(f => [f.etiqueta, f.opciones.find(o => o.codigo === snapshot.filtros[f.clave])?.etiqueta ?? 'Todos']), ['Registros', String(snapshot.items.length)], ]; diff --git a/src/app/features/indicadores/export/tracking-xlsx.ts b/src/app/features/indicadores/export/tracking-xlsx.ts index cd1c19a..e27245e 100644 --- a/src/app/features/indicadores/export/tracking-xlsx.ts +++ b/src/app/features/indicadores/export/tracking-xlsx.ts @@ -1,7 +1,7 @@ import type { Feature, SheetData } from 'write-excel-file/browser'; import { neutralizeFormula } from './cell-sanitizer'; import { flatTable } from './tracking-export-table'; -import { TrackingSnapshot } from './tracking-export.models'; +import { TrackingSnapshot, ventanaConsultada } from './tracking-export.models'; export const DATA_SHEET = 'Seguimiento'; export const PARAMETERS_SHEET = 'Parámetros'; @@ -49,8 +49,9 @@ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData return [ [header('Parámetro'), header('Valor')], row('Reporte', 'Cáncer de mama'), + ...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []), row('Fecha de corte', snapshot.corte), - row('Ventana consultada', `${snapshot.ventana.desde} al ${snapshot.ventana.hasta} (${snapshot.ventana.meses} ${snapshot.ventana.meses === 1 ? 'mes' : 'meses'})`), + row('Ventana consultada', ventanaConsultada(snapshot)), ...filters, row('Total de registros', snapshot.items.length), row('Generado', generatedAt(now)), diff --git a/src/app/features/indicadores/indicadores-analisis.testing.ts b/src/app/features/indicadores/indicadores-analisis.testing.ts new file mode 100644 index 0000000..1bf6388 --- /dev/null +++ b/src/app/features/indicadores/indicadores-analisis.testing.ts @@ -0,0 +1,20 @@ +// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API +// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort). +import { AnalisisAgregado } from './indicadores-analisis.service'; + +export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7'; +export const CORTE = '2026-10-20'; +export const CONTEXTO = { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: REVISION }; + +/** One published category (BI-RADS 5, six patients) and five suppressed ones. */ +export const agregado = (extra: Partial = {}): AnalisisAgregado => ({ + simulado: true, ...CONTEXTO, corte: CORTE, umbral_supresion: 5, unidad: 'paciente', + denominador: 'pacientes elegibles con última mastografía reportada BI-RADS 4 a 6', + grupos: [ + { codigo: 'BIRADS_4', n: null, suprimido: true }, { codigo: 'BIRADS_4A', n: null, suprimido: true }, { codigo: 'BIRADS_4B', n: null, suprimido: true }, + { codigo: 'BIRADS_4C', n: null, suprimido: true }, { codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_6', n: null, suprimido: true }, + ], + ...extra, +}); +/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */ +export const agregadoJson = (extra: Record = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts new file mode 100644 index 0000000..8e61316 --- /dev/null +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -0,0 +1,222 @@ +// Covers the follow-up list when the epidemiological analysis opens it on a group of the cohort: what it asks for (whole +// cohort, the analysis' cut-off, the group's filter and the cohort with its revision), what the user reads, how the +// selection is kept, refined and removed, and that a list which does not belong to the selection on screen is never +// drawn. Fixture: fixtures/cama_seguimiento.json shaped like the cohort's list (two filters, the cohort quoted back). +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 { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; + +const base = () => structuredClone(fixtureData) as unknown as Record; +const NULOS = { birads: null, grupo_edad: null }; +const OPCIONES = { birads: ['BIRADS_4', 'BIRADS_5', 'BIRADS_6'], grupo_edad: ['40-49', '50-59', '60-69'] }; +// The cohort's answer: only the two filters it announces, the cohort quoted back, window 0 and the filters it applied. +function cohorte(filtros: Record, pagina = 1, tam = 50, extra: Record = {}) { + const d = base(), todos = d['items'] as unknown[]; + d['items'] = todos.slice((pagina - 1) * tam, pagina * tam); + d['paginacion'] = { page: pagina, page_size: tam, total_items: todos.length, total_pages: Math.max(1, Math.ceil(todos.length / tam)) }; + d['corte'] = CORTE; d['ventana'] = { meses: 0, desde: '2025-01-01', hasta: CORTE }; + d['filtros'] = { ...NULOS, ...filtros }; + d['filtros_disponibles'] = [ + { clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: OPCIONES.birads.map(c => ({ codigo: c, etiqueta: c })) }, + { clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: OPCIONES.grupo_edad.map(c => ({ codigo: c, etiqueta: c })) }]; + return { ...d, ...CONTEXTO, ...extra }; +} +const seleccion = (id: number, extra: Partial = {}): SeleccionSeguimiento => + ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id, ...extra }); +const PARAMS = { meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO, birads: 'BIRADS_5' }; + +describe('Seguimiento de CaMa abierto desde el análisis', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); + fixture.componentRef.setInput('active', false); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const root = () => fixture.nativeElement as HTMLElement; + const solicitud = (dominio = 'cama') => http.expectOne(r => r.url === `/${dominio}/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 abrirCon = (sel: SeleccionSeguimiento) => { fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', sel); 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))!; + async function elegir(etiqueta: string, valor: string) { + const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor || o.value.endsWith(valor))!.value; + s.dispatchEvent(new Event('change')); await asentar(); + } + const banner = () => root().querySelector('.seleccion')?.textContent?.replace(/\s+/g, ' ').trim(); + const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim()); + const exportar = () => root().querySelector('app-seguimiento-exportar'); + + it('pide toda la cohorte con el corte del análisis, el filtro del grupo y la cohorte con su revisión, y lo dice con su etiqueta y un camino de regreso', async () => { + // Fails if the list opens on another window, cut-off, group or cohort revision, or hides where it came from. + http.expectNone(() => true); + abrirCon(seleccion(1)); + const r = solicitud(); + expect(parametros(r)).toEqual(PARAMS); + r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico: Categoría BI-RADS: BI-RADS 5. Toda la cohorte, corte 2026-10-20.'); + expect(boton('Volver al análisis')).toBeDefined(); expect(boton('Quitar selección')).toBeDefined(); + expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.'); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']); + expect(fixture.componentInstance.etiquetaDatos()).toBe('Categoría BI-RADS: BI-RADS 5'); + expect(exportar()).not.toBeNull(); + }); + it('sin una selección la ventana no ofrece «Toda la cohorte» y la consulta no cita ninguna cohorte', async () => { + // Fails if the whole cohort becomes a plain window of the list, or a plain query quotes a revision. + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + const r = solicitud(); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush({ ...base() }); await asentar(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + expect(root().querySelector('.seleccion')).toBeNull(); + }); + it('avisa cuando la lista no tiene tantos pacientes como contó el análisis, y calla cuando coinciden', async () => { + // Fails if a difference between the analysis' count and the list goes unsaid. + abrirCon(seleccion(1, { esperados: 30 })); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección; la lista muestra 27.'); + fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges(); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + expect(root().querySelector('.diferencia')).toBeNull(); + }); + + it('una respuesta que pierde el filtro, cambia la ventana o el corte, o no es la cohorte ni la revisión pedidas no se dibuja ni se puede exportar', async () => { + // Fails if rows of another population or of another revision are shown (or exported) under the name of the analysis' group. + for (const [mal, respuesta] of [ + ['pierde el filtro', cohorte({})], + ['cambia la ventana', cohorte({ birads: 'BIRADS_5' }, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })], + ['cambia el corte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { corte: '2026-09-01' })], + ['otra revisión', cohorte({ birads: 'BIRADS_5' }, 1, 50, { revision: 'f'.repeat(64) })], + ['otra cohorte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { cohorte: 'otra' })], + ['sin cohorte', (() => { const d: Record = cohorte({ birads: 'BIRADS_5' }); delete d['revision']; return d; })()], + ] as const) { + fixture.componentRef.setInput('active', true); + fixture.componentRef.setInput('seleccion', seleccion(mal.length * 7 + mal.charCodeAt(1))); + fixture.detectChanges(); + solicitud().flush(respuesta); await asentar(); + expect(root().querySelector('[role=alert]')?.textContent, mal).toContain('no corresponde a la selección consultada'); + expect(root().querySelector('table'), mal).toBeNull(); + expect(exportar(), mal).toBeNull(); + expect(root().textContent, mal).not.toContain('M-0081'); + } + }); + it('403, 409 y 503 dicen qué pasó, no dejan ninguna lista a la vista y no exponen el cuerpo del servidor', async () => { + // Fails if a refused list is explained with the server's text, or the previous rows stay under the failed selection. + abrirCon(seleccion(1)); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + for (const [status, texto] of [[403, 'no hay acceso, o la selección tiene muy pocos pacientes'], [409, 'La cohorte cambió desde que se calculó el análisis'], + [503, 'La cohorte no está disponible en este momento']] as const) { + 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(); + const r = solicitud(); + expect(r.request.params.get('corte'), String(status)).toBe(c.value); + r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar(); + const alerta = root().querySelector('[role=alert]')?.textContent; + expect(alerta, String(status)).toContain(texto); + expect(alerta, String(status)).not.toContain('detalle interno'); + expect(root().querySelector('table'), String(status)).toBeNull(); + expect(exportar(), String(status)).toBeNull(); + } + }); + it('una selección nueva cancela la anterior: su respuesta tardía no se dibuja y mientras carga no queda la lista anterior', async () => { + // Fails if a slow answer replaces the list of a later selection, or the old rows stay under the new banner. + abrirCon(seleccion(1)); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + expect(root().querySelector('table')).not.toBeNull(); + fixture.componentRef.setInput('seleccion', seleccion(2, { filtros: { birads: 'BIRADS_6' }, etiqueta: 'Categoría BI-RADS: BI-RADS 6' })); fixture.detectChanges(); + const r2 = solicitud(); + expect(root().querySelector('table')).toBeNull(); + expect(root().textContent).toContain('Cargando seguimiento'); + fixture.componentRef.setInput('seleccion', seleccion(3, { filtros: { birads: 'BIRADS_4' }, etiqueta: 'Categoría BI-RADS: BI-RADS 4' })); fixture.detectChanges(); + const r3 = solicitud(); + expect(r2.cancelled).toBe(true); + expect(() => r2.flush(cohorte({ birads: 'BIRADS_6' }))).toThrow(); + r3.flush(cohorte({ birads: 'BIRADS_4' })); await asentar(); + expect(banner()).toContain('BI-RADS 4'); + expect(banner()).not.toContain('BI-RADS 6'); + expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 4'); + }); + it('al paginar conserva la selección, el corte, el filtro y la cohorte, y el nombre sigue a las filas', async () => { + // Fails if a later page is asked without the group's filter or the cohort's revision, or loses the name of the selection. + abrirCon(seleccion(1)); + solicitud().flush(cohorte({ birads: 'BIRADS_5' }, 1, 10)); await asentar(); + boton('Siguiente')!.click(); fixture.detectChanges(); + const r = solicitud(); + expect(parametros(r)).toEqual({ ...PARAMS, page: '2', page_size: '10' }); + r.flush(cohorte({ birads: 'BIRADS_5' }, 2, 10)); await asentar(); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); + expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 5'); + expect(banner()).toContain('BI-RADS 5'); + }); + + it('la selección sobrevive a salir de la pestaña y volver, sin pedir otra vez; «Volver al análisis» avisa a la página', async () => { + // Fails if coming back to the tab repeats the request, drops the selection or the way back stops working. + abrirCon(seleccion(1)); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + let volvio = 0; fixture.componentInstance.volverAlAnalisis.subscribe(() => volvio++); + fixture.componentRef.setInput('active', false); fixture.detectChanges(); + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + http.expectNone(() => true); + expect(banner()).toContain('BI-RADS 5'); + expect(root().querySelector('table')).not.toBeNull(); + boton('Volver al análisis')!.click(); + expect(volvio).toBe(1); + expect(banner()).toContain('BI-RADS 5'); + }); + it('«Consultar» sin cambios repite la misma selección; con otro filtro refina la misma cohorte, citando su revisión, y lo dice', async () => { + // Fails if the banner keeps naming a group after the user narrowed the list, or a refinement leaves the cohort. + abrirCon(seleccion(1)); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + boton('Consultar')!.click(); fixture.detectChanges(); + let r = solicitud(); + expect(parametros(r)).toEqual(PARAMS); + r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico'); + await elegir('Grupo de edad', '50-59'); boton('Consultar')!.click(); fixture.detectChanges(); + r = solicitud(); + expect(parametros(r)).toEqual({ ...PARAMS, grupo_edad: '50-59' }); + r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' })); await asentar(); + expect(banner()).toContain('Pacientes de la cohorte del análisis epidemiológico, corte 2026-10-20. Los filtros y la ventana son los de esta consulta.'); + expect(banner()).not.toContain('selección del análisis'); + expect(exportar()).not.toBeNull(); + expect(fixture.componentInstance.etiquetaDatos()).toBe('Cohorte del análisis epidemiológico'); + 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. + 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(root().querySelector('.seleccion')).toBeNull(); + expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + }); + 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. + abrirCon(seleccion(1)); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); + fixture.componentRef.setInput('seleccion', undefined); fixture.componentRef.setInput('dominio', 'cacu'); fixture.detectChanges(); + expect(root().querySelector('.seleccion')).toBeNull(); + expect(root().querySelector('table')).toBeNull(); + const r = solicitud('cacu'); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush('', { status: 404, statusText: 'Not Found' }); + }); + it('una selección que llega con la pestaña inactiva espera a que se abra', async () => { + // Fails if the list is asked for while its tab is hidden. + fixture.componentRef.setInput('seleccion', seleccion(1)); fixture.detectChanges(); + http.expectNone(() => true); + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + solicitud().flush(cohorte({ birads: 'BIRADS_5' })); + }); +}); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 43695ca..55d4f57 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -8,17 +8,34 @@ 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 { - MESES_VENTANA, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, - SeguimientoTablaService, SeguimientoValor, + consultaAplicada, ContextoLista, 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 }; -interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; filtros: Record; } +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 }; +// 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 { + filtros: Record; etiqueta: string; corte?: string; esperados?: number | null; contexto?: ContextoLista; id: number; +} +const ETIQUETA_COHORTE = 'Cohorte del análisis epidemiológico'; +/** The answer does not apply the cut-off, window or filters that were asked for: it is neither shown nor exported. */ +export class SeguimientoNoCoincide extends Error {} + +interface Borrador { corte?: string; meses: MesesVentana; page_size: number; filtros: Record; } + +const mismosFiltros = (a: Record, b: Record) => { + const f = (x: Record) => JSON.stringify(Object.entries(x).filter(([, v]) => !!v).sort(([k], [l]) => k.localeCompare(l))); + return f(a) === f(b); +}; /** * Follow-up list of a domain, drawn from what `GET //seguimiento` announces: the filters, the columns - * and their details come with the answer. Nothing is requested until the tab is opened. + * and their details come with the answer. Nothing is requested until the tab is opened. The analysis can open it + * on a selection (a published group, whole cohort); the list keeps it until it is removed or the domain changes. */ @Component({ selector: 'app-seguimiento-tabla', @@ -31,13 +48,25 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f

Seguimiento de {{ domainLabel }}

@if (data(); as respuesta) { - + }
+ @if (seleccionMostrada(); as sel) { +
+ @if (seleccionExacta()) { + Pacientes de la selección del análisis epidemiológico: {{ sel }}. {{ etiquetaVentana(0) }}@if (corteSeleccion()) {, corte {{ corteSeleccion() }}}. + } @else { + Pacientes de la cohorte del análisis epidemiológico@if (corteSeleccion()) {, corte {{ corteSeleccion() }}}. Los filtros y la ventana son los de esta consulta. + } + + +
+ @if (diferencia(); as d) {

{{ d }}

} + }
@for (filtro of filtros(); track filtro.clave) {