diff --git a/e2e/exportaciones-cama.spec.ts b/e2e/exportaciones-cama.spec.ts new file mode 100644 index 0000000..e8e7679 --- /dev/null +++ b/e2e/exportaciones-cama.spec.ts @@ -0,0 +1,386 @@ +import { expect, type Page, test } from '@playwright/test'; +import { strFromU8, unzipSync } from 'fflate'; +import { readFileSync } from 'node:fs'; + +// Exports of CaMa (the follow-up list as Excel and PDF, the record as PDF), and CaCu's still working. +// The contents are checked by the unit tests of their builders; here the real downloads are checked: +// the file's name and format, and for the filter regression the exported rows and query. +// "(simulado)" tests rewrite the API's answers in the browser to reach what the synthetic data lack. + +const EXT = 'https://isssteleon.org/fhir/StructureDefinition/'; +const SHOTS = process.env['SHOTS_DIR']; + +test.beforeEach(async ({ page }) => { + const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' }; + expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204); +}); + +async function saved(page: Page, click: () => Promise) { + const [download] = await Promise.all([page.waitForEvent('download'), click()]); + const file = await download.path(); + return { name: download.suggestedFilename(), bytes: readFileSync(file!) }; +} +const isPdf = (b: Buffer) => b.subarray(0, 4).toString() === '%PDF'; +const isXlsx = (b: Buffer) => b.subarray(0, 2).toString() === 'PK'; // a zip container + +async function followUp(page: Page, domain: 'cama' | 'cacu') { + await page.goto(`/indicadores/${domain}`); + await page.getByRole('tab', { name: 'Seguimiento' }).click(); + await page.locator('table.worklist tbody tr').first().waitFor({ timeout: 120_000 }); +} + +function workbookSheets(bytes: Buffer) { + const parts = unzipSync(bytes); + const strings = [ + ...strFromU8(parts['xl/sharedStrings.xml']).matchAll(/]*)?>(.*?)<\/t>/gs), + ].map((match) => match[1]); + return [1, 2].map((sheet) => + [...strFromU8(parts[`xl/worksheets/sheet${sheet}.xml`]).matchAll(/]*>(.*?)<\/row>/gs)] + .map((row) => [...row[1].matchAll(/(\d+)<\/v>/g)].map((cell) => strings[Number(cell[1])])), + ); +} + +async function pdfText(bytes: Buffer) { + const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs'); + const task = getDocument({ data: Uint8Array.from(bytes) }); + try { + const document = await task.promise; + const text: string[] = []; + for (let n = 1; n <= document.numPages; n++) { + const { items } = await (await document.getPage(n)).getTextContent(); + text.push(...items.flatMap((item) => ('str' in item ? [item.str] : []))); + } + return text.join(' ').replace(/\s+/g, ' '); + } finally { + await task.destroy(); + } +} + +for (const domain of ['cama', 'cacu'] as const) { + for (const format of ['xlsx', 'pdf'] as const) { + test(`exportación (${domain}, ${format}): conserva los filtros aplicados en todas las páginas`, async ({ + page, + }) => { + const original = 'Paciente original'; + const changed = 'Paciente distinto'; + const cutoff = '2026-11-30'; + const studyDate = '2026-09-15'; + const patients = [`${original} Alfa`, `${original} Beta`]; + const requests: URLSearchParams[] = []; + const pending = Promise.withResolvers(); + const resume = Promise.withResolvers(); + + await page.route( + (url) => url.pathname === `/api/${domain}/fhir/Patient` && url.searchParams.has('follow-up-window'), + async (route) => { + const self = new URL(route.request().url()); + const filters = self.searchParams; + filters.set('follow-up-cutoff', cutoff); + const exportPage = filters.get('_count') === '200'; + const offset = Number(filters.get('_offset') ?? '0'); + if (exportPage) { + requests.push(new URLSearchParams(filters)); + if (offset === 0) { + pending.resolve(); + await resume.promise; + } + } + const matched = filters.get('name') !== changed; + const link = [{ relation: 'self', url: self.href }]; + if (matched && exportPage && offset === 0) { + const next = new URL(self); + next.searchParams.set('_offset', '1'); + link.push({ relation: 'next', url: next.href }); + } + await route.fulfill({ + json: { + resourceType: 'Bundle', + type: 'searchset', + total: matched ? patients.length : 0, + link, + entry: matched + ? patients.flatMap((name, index) => { + if (exportPage && index !== offset) return []; + const id = `patient-${index}`; + return [ + { + search: { mode: 'match' }, + resource: { resourceType: 'Patient', id, birthDate: '1980-01-01', name: [{ text: name }] }, + }, + { + search: { mode: 'include' }, + resource: { + resourceType: 'DiagnosticReport', + id: `report-${index}`, + subject: { reference: `Patient/${id}` }, + code: { coding: [{ code: domain === 'cama' ? 'mammography' : 'cervical_cytology' }] }, + effectiveDateTime: studyDate, + extension: [{ url: EXT + 'report-date', valueDate: studyDate }], + }, + }, + ]; + }) + : [], + }, + }); + }, + ); + + await followUp(page, domain); + const search = page.locator('app-patient-search input'); + const searchFor = async (text: string) => { + await search.fill(text); + await search.press('Enter'); + }; + if (domain === 'cacu') { + await page.locator('input[name=ageFrom]').fill('25'); + await page.locator('input[name=ageTo]').fill('64'); + } + const applied = page.waitForResponse((response) => { + const url = new URL(response.url()); + return url.pathname === `/api/${domain}/fhir/Patient` && url.searchParams.get('name') === original; + }); + await searchFor(original); + await applied; + await expect(page.locator('table.worklist tbody tr')).toHaveCount(2); + + const button = page.getByRole('button', { name: format === 'xlsx' ? 'Exportar Excel' : 'Exportar PDF' }); + const download = page.waitForEvent('download'); + await button.click(); + await Promise.race([pending.promise, download.then(() => { throw new Error('Export request was not held'); })]); + try { + await searchFor(changed); + await page.getByRole('combobox', { name: 'Ventana de meses' }).click(); + await page.getByRole('option', { name: '1 mes', exact: true }).click(); + if (domain === 'cacu') { + await page.locator('input[name=ageFrom]').fill('40'); + await page.getByRole('combobox', { name: 'Horizonte de la probabilidad' }).click(); + await page.getByRole('option', { name: '1 año', exact: true }).click(); + } + await expect(page.getByText('No hay registros para los filtros aplicados.')).toBeVisible(); + } finally { + resume.resolve(); + } + + const file = await download; + expect(file.suggestedFilename()).toBe(`seguimiento-${domain}.${format}`); + const bytes = readFileSync((await file.path())!); + expect(requests.map((params) => params.get('_offset') ?? '0')).toEqual(['0', '1']); + for (const params of requests) { + expect(params.get('name')).toBe(original); + expect(params.get('follow-up-window')).toBe('3'); + expect(params.get('follow-up-cutoff')).toBe(cutoff); + if (domain === 'cacu') { + expect(params.getAll('birthdate')).toEqual(['le2001-11-30', 'gt1961-11-30']); + expect(params.get('risk-horizon')).toBe('5'); + } + } + const metadata = [ + ['Ventana consultada', `2026-08-31 al ${cutoff}`], + ['Búsqueda', original], + ['Registros', '2'], + ...(domain === 'cacu' + ? [['Edad mínima', '25'], ['Edad máxima', '64'], ['Horizonte de la probabilidad (años)', '5']] + : []), + ]; + if (format === 'xlsx') { + const [results, query] = workbookSheets(bytes); + expect(results.slice(1).map((row) => row[0])).toEqual(patients); + expect(results.slice(1).every((row) => row.some((cell) => cell.includes(studyDate)))).toBe(true); + expect(query).toEqual(expect.arrayContaining(metadata)); + expect(query.flat()).not.toContain(changed); + } else { + const text = await pdfText(bytes); + for (const value of [...patients, studyDate, ...metadata.map(([key, value]) => `${key}: ${value}`)]) { + expect(text).toContain(value); + } + expect(text).not.toContain(changed); + } + }); + } +} + +test('exportación (CaMa): the follow-up list is saved as Excel and PDF with as many rows as the page asked for', async ({ + page, +}) => { + await followUp(page, 'cama'); + const total = await page.locator('table.worklist tbody tr').count(); + const excel = await saved(page, () => + page.getByRole('button', { name: 'Exportar Excel' }).click(), + ); + expect(excel.name).toBe('seguimiento-cama.xlsx'); + expect(isXlsx(excel.bytes)).toBe(true); + const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click()); + expect(pdf.name).toBe('seguimiento-cama.pdf'); + expect(isPdf(pdf.bytes)).toBe(true); + expect(pdf.bytes.length).toBeGreaterThan(5_000); + expect(total).toBeGreaterThan(0); + await expect(page.getByText('No se generó el archivo.')).toHaveCount(0); +}); + +test('exportación (CaMa): the buttons wait for a cut-off and an empty search still saves a file', async ({ + page, +}) => { + await followUp(page, 'cama'); + await page.locator('app-patient-search input').fill('zzzz-sin-coincidencias'); + await page.keyboard.press('Enter'); + await expect(page.getByText('No hay registros para los filtros aplicados.')).toBeVisible({ + timeout: 60_000, + }); + const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click()); + expect(isPdf(pdf.bytes)).toBe(true); +}); + +test('exportación (CaMa): the record is saved as a PDF', async ({ page }) => { + const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); + await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`); + const button = page.getByRole('button', { name: 'Exportar PDF' }); + await expect(button).toBeVisible({ timeout: 120_000 }); + const pdf = await saved(page, () => button.click()); + expect(pdf.name).toBe('expediente-cama.pdf'); + expect(isPdf(pdf.bytes)).toBe(true); + expect(pdf.bytes.length).toBeGreaterThan(5_000); +}); + +test('exportación (CaMa, simulado): a record with published survival and recurrence estimates saves its PDF', async ({ + page, +}) => { + const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); + const estimate = (id: string, method: string, model: string) => ({ + resourceType: 'RiskAssessment', + id, + status: 'final', + method: { text: method, coding: [{ code: model }] }, + occurrenceDateTime: '2026-02-01', + extension: [{ url: EXT + 'escenario-clinico', valueString: 'En observación' }], + prediction: [ + { + whenRange: { high: { value: 0, unit: 'a', code: 'a' } }, + probabilityDecimal: 0, + extension: [], + }, + { + whenRange: { high: { value: 5, unit: 'a', code: 'a' } }, + probabilityDecimal: 0.8, + extension: [ + { url: EXT + 'ic-bajo', valueDecimal: 0.7 }, + { url: EXT + 'ic-alto', valueDecimal: 0.9 }, + ], + }, + ], + }); + await page.route('**/api/cama/fhir/RiskAssessment**', (route) => + route.fulfill({ + contentType: 'application/fhir+json', + body: JSON.stringify({ + resourceType: 'Bundle', + type: 'searchset', + entry: [ + estimate('s', 'Supervivencia v1', 'cama.survival'), + estimate('r', 'Recurrencia v1', 'cama.recurrence'), + ].map((resource) => ({ resource })), + }), + }), + ); + await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`); + const button = page.getByRole('button', { name: 'Exportar PDF' }); + await expect(button).toBeVisible({ timeout: 120_000 }); + const pdf = await saved(page, () => button.click()); + expect(isPdf(pdf.bytes)).toBe(true); + if (SHOTS) + (await import('node:fs')).writeFileSync( + `${SHOTS}/SIMULADO-expediente-cama-con-estimaciones.pdf`, + pdf.bytes, + ); +}); + +test('exportación (CaCu): the list and the record still save their files', async ({ page }) => { + await followUp(page, 'cacu'); + const excel = await saved(page, () => + page.getByRole('button', { name: 'Exportar Excel' }).click(), + ); + expect(excel.name).toBe('seguimiento-cacu.xlsx'); + expect(isXlsx(excel.bytes)).toBe(true); + const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click()); + expect(pdf.name).toBe('seguimiento-cacu.pdf'); + expect(isPdf(pdf.bytes)).toBe(true); + const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=1')).json(); + await page.goto(`/indicadores/cacu/pacientes/${patients.entry[0].resource.id}`); + const record = await saved(page, async () => { + await page.getByRole('button', { name: 'Exportar PDF' }).click(); + }); + expect(record.name).toBe('expediente-cacu.pdf'); + expect(isPdf(record.bytes)).toBe(true); +}); + +for (const width of [1440, 480]) { + test(`exportación (CaMa) at ${width} px: the record's PDF button sits in the header beside the name, never over it`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 1000 }); + const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); + await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`); + const button = page.getByRole('button', { name: 'Exportar PDF' }); + await expect(button).toBeVisible({ timeout: 120_000 }); + await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 }); + // one button, in the header; the "Historial médico" card no longer holds it + await expect(button).toHaveCount(1); + await expect( + page.locator('.record-head').getByRole('button', { name: 'Exportar PDF' }), + ).toHaveCount(1); + await expect( + page + .locator('mat-card', { has: page.getByText('Historial médico', { exact: true }) }) + .getByRole('button', { name: 'Exportar PDF' }), + ).toHaveCount(0); + const [title, action] = await Promise.all([ + page.locator('.record-head h1').boundingBox(), + button.boundingBox(), + ]); + const overlaps = !( + action!.x >= title!.x + title!.width || + title!.x >= action!.x + action!.width || + action!.y >= title!.y + title!.height || + title!.y >= action!.y + action!.height + ); + expect(overlaps).toBe(false); + if (width >= 1000) { + expect(action!.x + action!.width).toBeGreaterThan(width - 120); // at the right end + expect( + Math.abs(action!.y + action!.height / 2 - (title!.y + title!.height / 2)), + ).toBeLessThan(30); // on the name's line + } else { + expect(action!.x + action!.width).toBeLessThanOrEqual(width); + } + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), + ).toBe(true); + if (SHOTS) + await page.screenshot({ + path: `${SHOTS}/captura-cama-ficha-boton-${width}.png`, + fullPage: false, + }); + const pdf = await saved(page, () => button.click()); + expect(pdf.name).toBe('expediente-cama.pdf'); + expect(isPdf(pdf.bytes)).toBe(true); + if (SHOTS) + (await import('node:fs')).writeFileSync( + `${SHOTS}/descarga-ficha-cama-${width}.pdf`, + pdf.bytes, + ); + }); +} + +test('exportación (CaCu): the record button stays in its "Historial médico" card', async ({ + page, +}) => { + const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=1')).json(); + await page.goto(`/indicadores/cacu/pacientes/${patients.entry[0].resource.id}`); + const card = page.locator('mat-card', { + has: page.getByText('Historial médico', { exact: true }), + }); + await expect(card.getByRole('button', { name: 'Exportar PDF' })).toBeVisible({ + timeout: 120_000, + }); + await expect(page.locator('.record-head').getByRole('button')).toHaveCount(0); +}); diff --git a/package-lock.json b/package-lock.json index a872519..6ebd588 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,8 +42,10 @@ "@types/fhir": "0.0.44", "@types/pdfmake": "0.3.5", "@types/plotly.js": "3.0.15", + "fflate": "0.8.3", "jsdom": "^31.0.0", "ng-openapi-gen": "^1.1.0", + "pdfjs-dist": "6.5.438", "prettier": "^3.8.1", "typescript": "~6.0.2", "vitest": "^5.0.0" @@ -2013,6 +2015,283 @@ "win32" ] }, + "node_modules/@napi-rs/canvas": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz", + "integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==", + "dev": true, + "license": "MIT", + "optional": true, + "workspaces": [ + "e2e/*" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@napi-rs/canvas-android-arm64": "1.2.1", + "@napi-rs/canvas-darwin-arm64": "1.2.1", + "@napi-rs/canvas-darwin-x64": "1.2.1", + "@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1", + "@napi-rs/canvas-linux-arm64-gnu": "1.2.1", + "@napi-rs/canvas-linux-arm64-musl": "1.2.1", + "@napi-rs/canvas-linux-riscv64-gnu": "1.2.1", + "@napi-rs/canvas-linux-x64-gnu": "1.2.1", + "@napi-rs/canvas-linux-x64-musl": "1.2.1", + "@napi-rs/canvas-win32-arm64-msvc": "1.2.1", + "@napi-rs/canvas-win32-x64-msvc": "1.2.1" + } + }, + "node_modules/@napi-rs/canvas-android-arm64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz", + "integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-arm64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz", + "integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-x64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz", + "integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz", + "integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz", + "integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-musl": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz", + "integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz", + "integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz", + "integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-musl": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz", + "integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-arm64-msvc": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz", + "integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-x64-msvc": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz", + "integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, "node_modules/@napi-rs/nice": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz", @@ -6077,6 +6356,19 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/pdfjs-dist": { + "version": "6.5.438", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", + "integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=22.13.0 || >=24" + }, + "optionalDependencies": { + "@napi-rs/canvas": "^1.0.13" + } + }, "node_modules/pdfkit": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz", diff --git a/package.json b/package.json index 73839a0..1ee8f0f 100644 --- a/package.json +++ b/package.json @@ -46,8 +46,10 @@ "@types/fhir": "0.0.44", "@types/pdfmake": "0.3.5", "@types/plotly.js": "3.0.15", + "fflate": "0.8.3", "jsdom": "^31.0.0", "ng-openapi-gen": "^1.1.0", + "pdfjs-dist": "6.5.438", "prettier": "^3.8.1", "typescript": "~6.0.2", "vitest": "^5.0.0" diff --git a/src/app/indicadores/cama-follow-up-sheet.spec.ts b/src/app/indicadores/cama-follow-up-sheet.spec.ts new file mode 100644 index 0000000..20f5b23 --- /dev/null +++ b/src/app/indicadores/cama-follow-up-sheet.spec.ts @@ -0,0 +1,46 @@ +import type { CamaRow } from './follow-up'; +import { camaFollowUpSheet } from './follow-up-sheet'; + +const row = (over: Partial = {}): CamaRow => + ({ + patient: { resourceType: 'Patient', id: 'abcdefghijklmnop' }, + status: 'pending_biopsy', + priority: 'high', + ageGroup: '50-59', + mammogram: { date: '2026-10-26', birads: '4A' }, + ...over, + }) as CamaRow; +const priority = (c: string) => ({ high: 'Alta' })[c as 'high'] ?? c; + +// Each test fails if the list file invented a result or lost the query it answers. +describe('CaMa follow-up list as a file', () => { + it('has CaMa columns, the query and the count', () => { + const sheet = camaFollowUpSheet([row()], [['Búsqueda', 'Ninguna']], priority); + expect(sheet.head).toEqual([ + 'Paciente', 'CURP', 'Grupo de edad', 'Última mastografía (BI-RADS)', 'Fecha de la mastografía', + 'Última biopsia', 'Fecha de reporte de la biopsia', 'Estatus de seguimiento', 'Prioridad', + ]); + expect(sheet.query).toEqual([['Búsqueda', 'Ninguna'], ['Registros', '1']]); + expect(sheet.head.join()).not.toMatch(/LIEAG|VPH|Cáncer|Etapas/); + }); + it('says what is missing: no biopsy, no BI-RADS, no CURP, no priority, never a made-up value', () => { + const [r] = camaFollowUpSheet( + [row({ mammogram: { date: '' }, priority: '' })], + [], + priority, + ).rows; + expect(r.slice(0, 2)).toEqual(['abcdefghij', 'No disponible']); + expect(r.slice(3, 7)).toEqual(['Sin dato', 'No disponible', 'No disponible', 'No disponible']); + expect(r[8]).toBe('No disponible'); + }); + it('shows a biopsy with its date, or no grade when it has none', () => { + const rows = camaFollowUpSheet( + [row({ biopsy: { date: '2026-11-30', histology: 'benign' } }), row({ biopsy: { date: '2026-11-01' } })], + [], + priority, + ).rows; + expect(rows[0].slice(5, 7)).toEqual(['Benigno', '2026-11-30']); + expect(rows[1].slice(5, 7)).toEqual(['Sin resultado', '2026-11-01']); + expect(rows[0][8]).toBe('Alta'); + }); +}); diff --git a/src/app/indicadores/follow-up-export.ts b/src/app/indicadores/follow-up-export.ts new file mode 100644 index 0000000..f1d9783 --- /dev/null +++ b/src/app/indicadores/follow-up-export.ts @@ -0,0 +1,48 @@ +import type { Bundle } from 'fhir/r4'; +import { type Sheet, saveExcel, savePdf } from '../export'; +import type { Fhir } from '../fhir'; +import { windowStart } from './follow-up'; +import { name } from './measures'; + +/** The bundle's self link carries the filters that produced the displayed page. */ +function exportQuery(page: Bundle) { + const self = page.link?.find((link) => link.relation === 'self')?.url; + if (!self) throw new Error('Missing follow-up query'); + + const applied = new URL(self).searchParams; + const cutoff = applied.get('follow-up-cutoff'); + if (!cutoff) throw new Error('Missing follow-up cut-off'); + + applied.delete('_offset'); + applied.set('_count', '200'); + const params = Object.fromEntries( + [...new Set(applied.keys())].map((key) => [key, applied.getAll(key)]), + ); + const start = windowStart(cutoff, Number(applied.get('follow-up-window'))); + const status = applied.get('follow-up-status'); + return { + params, + cutoff, + start, + window: `${start} al ${cutoff}`, + status: status ? name(status) : 'Todos', + search: applied.get('name') ?? applied.get('identifier') ?? 'Ninguna', + horizon: Number(applied.get('risk-horizon')), + birthdates: applied.getAll('birthdate'), + }; +} + +export async function saveFollowUp( + fhir: Fhir, + domain: string, + page: Bundle, + kind: 'xlsx' | 'pdf', + sheetFor: (pages: Bundle[], query: ReturnType) => Sheet, +): Promise { + const query = exportQuery(page); + const pages = await fhir.all(domain, 'Patient', query.params); + const sheet = sheetFor(pages, query); + const file = `seguimiento-${domain}`; + if (kind === 'xlsx') await saveExcel(sheet, file); + else await savePdf([sheet], file, true); +} diff --git a/src/app/indicadores/follow-up-sheet.ts b/src/app/indicadores/follow-up-sheet.ts index 9b0c45b..d47c710 100644 --- a/src/app/indicadores/follow-up-sheet.ts +++ b/src/app/indicadores/follow-up-sheet.ts @@ -1,6 +1,6 @@ import type { Sheet } from '../export'; import { STATES } from '../paciente/stages'; -import type { Row } from './follow-up'; +import type { CamaRow, Row } from './follow-up'; import { name } from './measures'; const NONE = 'No disponible'; @@ -50,3 +50,40 @@ export function followUpSheet(rows: Row[], query: [string, string][]): Sheet { ]), }; } + +const CAMA_HEAD = [ + 'Paciente', + 'CURP', + 'Grupo de edad', + 'Última mastografía (BI-RADS)', + 'Fecha de la mastografía', + 'Última biopsia', + 'Fecha de reporte de la biopsia', + 'Estatus de seguimiento', + 'Prioridad', +]; + +/** CaMa's follow-up list as a table to save: what the page shows, a missing value said as such and + * never filled in. */ +export function camaFollowUpSheet( + rows: CamaRow[], + query: [string, string][], + priority: (code: string) => string, +): Sheet { + return { + title: 'Resultados de seguimiento de cáncer de mama', + query: [...query, ['Registros', `${rows.length}`]], + head: CAMA_HEAD, + rows: rows.map((r) => [ + r.name ?? r.patient.id!.slice(0, 10), + r.curp ?? NONE, + r.ageGroup || NONE, + (r.mammogram.birads && name(r.mammogram.birads)) || 'Sin dato', + r.mammogram.date || NONE, + r.biopsy ? name(r.biopsy.histology ?? '') || 'Sin resultado' : NONE, + r.biopsy?.date ?? NONE, + name(r.status), + priority(r.priority) || NONE, + ]), + }; +} diff --git a/src/app/indicadores/tab-riesgos.ts b/src/app/indicadores/tab-riesgos.ts index a86d1ff..7785799 100644 --- a/src/app/indicadores/tab-riesgos.ts +++ b/src/app/indicadores/tab-riesgos.ts @@ -16,8 +16,8 @@ import { MatSelectModule } from '@angular/material/select'; import { RouterLink } from '@angular/router'; import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; -import { saveExcel, savePdf } from '../export'; import { Stages } from '../paciente/stages'; +import { saveFollowUp } from './follow-up-export'; import { cytologyResult, followUpSheet } from './follow-up-sheet'; import { bornFor, Row, rows, windowStart } from './follow-up'; import { PatientSearch, patientSearch } from './patient-search'; @@ -140,24 +140,28 @@ export class TabRiesgos { /** The whole list, not the page shown, as a file. */ protected async save(kind: 'xlsx' | 'pdf'): Promise { + const page = this.page(); + if (!page) return; this.saving.set(true); this.saveError.set(''); try { - const cutoff = this.applied(); - const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 }; - const pages = await this.fhir.all(this.domain(), 'Patient', asked); - const start = windowStart(cutoff, this.window()); - const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon())); - const sheet = followUpSheet(all, [ - ['Ventana consultada', `${start} al ${cutoff}`], - ['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'], - ['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`], - ['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`], - ['Búsqueda', this.search() || 'Ninguna'], - ['Horizonte de la probabilidad (años)', `${this.horizon()}`], - ]); - if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu'); - else await savePdf([sheet], 'seguimiento-cacu', true); + await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) => { + const cutoffYear = Number(query.cutoff.slice(0, 4)); + // bornFor encodes the minimum with le and the maximum with gt at one year earlier. + const lower = query.birthdates.find((value) => value.startsWith('le')); + const upper = query.birthdates.find((value) => value.startsWith('gt')); + const minimum = lower ? `${cutoffYear - Number(lower.slice(2, 6))}` : 'Sin límite'; + const maximum = upper ? `${cutoffYear - Number(upper.slice(2, 6)) - 1}` : 'Sin límite'; + const all = pages.flatMap((p) => rows(p, query.start, query.cutoff, query.horizon)); + return followUpSheet(all, [ + ['Ventana consultada', query.window], + ['Estatus de seguimiento', query.status], + ['Edad mínima', minimum], + ['Edad máxima', maximum], + ['Búsqueda', query.search], + ['Horizonte de la probabilidad (años)', `${query.horizon}`], + ]); + }); } catch { this.saveError.set('No se generó el archivo.'); } finally { diff --git a/src/app/indicadores/tab-seguimiento.html b/src/app/indicadores/tab-seguimiento.html index 66dd6c9..220bafd 100644 --- a/src/app/indicadores/tab-seguimiento.html +++ b/src/app/indicadores/tab-seguimiento.html @@ -35,7 +35,26 @@ } + + +@if (saveError()) { + +} @if (error()) { } @else if (patient(); as p) { -

- {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} -

+
+

+ {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} +

+ @if (cama()) { +
+ +
+ } +
+ @if (cama() && saveError()) { + + }
CURP
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index 8af730d..88d68af 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -138,3 +138,19 @@ h1 .id { margin: 8px 0; padding-left: 18px; } + +/* The name and, in CaMa, the export of the record on the same line; narrow screens put the button under the name. */ +.record-head { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: 8px 16px; + justify-content: space-between; +} +.record-head h1 { + min-width: 0; + overflow-wrap: anywhere; +} +.head-actions { + flex: none; +} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index 60d30cf..1f68508 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -22,6 +22,7 @@ import type { Domain } from '../api/models/domain'; import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { scenarioFigure } from '../gobernanza/figures'; import { savePdf } from '../export'; +import { camaRecordSheets } from './cama-record-sheets'; import { recordSheets } from './record-sheets'; import { HttpClient } from '@angular/common/http'; import type { Parameters as FhirParameters } from 'fhir/r4'; @@ -292,11 +293,15 @@ export class Paciente { ); protected readonly saving = signal(false); protected readonly saveError = signal(''); - /** CaCu: her record as a PDF. */ + /** Her record as a PDF (CaCu's or CaMa's). */ protected async save(): Promise { this.saving.set(true); this.saveError.set(''); try { + if (this.domain() === 'cama') { + await this.saveCama(); + return; + } const { name: who, curp, numbers } = this.identity(); const facts: [string, string | undefined][] = [ ['Nombre', who], @@ -323,6 +328,51 @@ export class Paciente { this.saving.set(false); } } + /** CaMa: her record as a PDF, with what CaMa publishes of her. */ + private async saveCama(): Promise { + const c = this.cama(); + const { name: who, curp, numbers } = this.identity(); + const p = this.patient(); + const facts: [string, string | undefined][] = [ + ['Nombre', who], + ['CURP', curp], + ['Expedientes', numbers.join(', ')], + ['Fecha de nacimiento', p?.birthDate], + ['Sexo', p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined], + ['Grupo de edad', c?.ageGroup], + ['Escenario clínico', c?.scenario], + ['Fecha de corte', c?.cutoff], + [ + 'Estatus de seguimiento', + c ? (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`) : undefined, + ], + ['Prioridad', c?.priority], + ['Días de mastografía a diagnóstico', c?.days?.toString()], + ...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as [string, string][]) : []), + ]; + const studies: [string, string | undefined][] = [ + ['Categoría BI-RADS de la última mastografía', c?.birads], + ['Fecha de la última mastografía', c?.mammogram], + ['Resultado histopatológico', c?.histology], + ['Fecha de reporte de la biopsia', c?.biopsy], + ]; + const analysis = (title: string, r: typeof this.survival) => { + // a report that failed to load is no analysis: its absence is said, the file is still made + const v = r.hasValue() ? r.value() : undefined; + return v + ? [{ title, scenarios: v.scenarios, figures: v.figures.map((f) => f.title), undrawn: v.unavailable }] + : []; + }; + const sheets = camaRecordSheets( + facts, + studies, + this.history(), + this.tests(), + this.models(), + [...analysis('Supervivencia', this.survival), ...analysis('Recurrencia', this.recurrence)], + ); + await savePdf(sheets, 'expediente-cama'); + } protected readonly tests = computed(() => { const d = this.data.value(); if (!d) return [];