Añadir exportaciones de CaMa y conservar los filtros aplicados
This commit is contained in:
@@ -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<unknown>) {
|
||||
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(?: [^>]*)?>(.*?)<\/t>/gs),
|
||||
].map((match) => match[1]);
|
||||
return [1, 2].map((sheet) =>
|
||||
[...strFromU8(parts[`xl/worksheets/sheet${sheet}.xml`]).matchAll(/<row\b[^>]*>(.*?)<\/row>/gs)]
|
||||
.map((row) => [...row[1].matchAll(/<v>(\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<void>();
|
||||
const resume = Promise.withResolvers<void>();
|
||||
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user