import { expect, type Locator, type Page, test } from '@playwright/test'; import { layoutProblems } from './layout'; // The individual record of CaCu: the stages inside "Historial médico" and the risk scales. // "(simulado)" tests rewrite the API's answers in the browser to cover what the synthetic data // do not hold (every stage state, every risk value); they show how the page draws them, not the backend. const EXT = 'https://isssteleon.org/fhir/StructureDefinition/'; 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); }); /** The record of the first patient of the risk list, as an address. */ async function firstRecord(page: Page): Promise<{ url: string; sample: string }> { await page.goto('/indicadores/cacu'); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); const link = page.locator('table.worklist tbody tr a').first(); await link.waitFor({ timeout: 120_000 }); const url = (await link.getAttribute('href'))!; return { url, sample: new URL(url, 'http://x').searchParams.get('citologia')! }; } const plus = (day: string, days: number) => new Date(Date.parse(day) + days * 86_400_000).toISOString().slice(0, 10); type Route = Partial< Record<'report' | 'colposcopy' | 'request' | 'biopsy' | 'diagnosis', number> > & { link?: 'recorded'; /** more extensions on the report, as the backend would publish them (stage states and sources) */ extra?: object[]; }; /** The shown cytology's report carries these dates (days after its sample). */ async function withRoute(page: Page, sample: string, days: Route) { await page.route('**/api/cacu/fhir/DiagnosticReport**', async (route) => { const response = await route.fetch(); const body = await response.json(); for (const { resource: r } of body.entry ?? []) { if (r.code?.coding?.[0]?.code !== 'cervical_cytology' || r.effectiveDateTime !== sample) continue; const names = { report: 'report-date', colposcopy: 'colposcopy-date', request: 'biopsy-request-date', biopsy: 'biopsy-date', diagnosis: 'diagnosis-date', } as const; r.extension = (r.extension ?? []).filter( (e: any) => !Object.values(names).some((n) => e.url === EXT + n) && e.url !== EXT + 'biopsy-link', ); for (const [key, name] of Object.entries(names)) { const d = days[key as keyof typeof names]; if (d !== undefined) r.extension.push({ url: EXT + name, valueDate: plus(sample, d) }); } if (days.link) r.extension.push({ url: EXT + 'biopsy-link', valueCode: days.link }); r.extension.push(...(days.extra ?? [])); } await route.fulfill({ response, body: JSON.stringify(body), contentType: 'application/fhir+json', }); }); } type Prediction = [years: number, p: number, low?: number, high?: number]; const risk = ( id: string, text: string, model: string, index: string, predictions: Prediction[], ) => ({ resourceType: 'RiskAssessment', id, status: 'final', method: { text, coding: [{ code: model }] }, occurrenceDateTime: index, prediction: predictions.map(([years, p, low, high]) => ({ whenRange: { high: { value: years, unit: 'a', code: 'a' } }, probabilityDecimal: p, extension: low === undefined ? [] : [ { url: EXT + 'ic-bajo', valueDecimal: low }, { url: EXT + 'ic-alto', valueDecimal: high }, ], })), }); /** The patient has these risk assessments. */ async function withRisks(page: Page, assessments: object[]) { await page.route('**/api/cacu/fhir/RiskAssessment**', (route) => route.fulfill({ contentType: 'application/fhir+json', body: JSON.stringify({ resourceType: 'Bundle', type: 'searchset', entry: assessments.map((resource) => ({ resource })), }), }), ); } const historial = (page: Page) => page.locator('mat-card', { has: page.locator('mat-card-title', { hasText: 'Historial médico' }), }); const scale = (page: Page, label: string, nth = 0) => page.locator(`.risk-scale[data-scale="${label}"]`).nth(nth); const IMMEDIATE = 'Riesgo inmediato (al índice)'; const FIVE = 'Riesgo a 5 años'; async function open(page: Page, url: string) { await page.goto(url); await expect(historial(page)).toBeVisible({ timeout: 120_000 }); await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 }); } /** Where a scale draws its marker, in % of the bar, and the figure it prints. */ async function drawn(scaleBox: Locator) { const marker = scaleBox.locator('.risk-marker'); return { markers: await marker.count(), left: (await marker.count()) ? await marker.evaluate((e) => (e as HTMLElement).style.left) : undefined, value: (await scaleBox.locator('.risk-value').count()) ? (await scaleBox.locator('.risk-value').innerText()).trim() : undefined, grey: await scaleBox.locator('.risk-plot.unavailable').count(), }; } test('ficha: the five stages are a line of nodes inside "Historial médico", with the export button', async ({ page, }) => { const { url } = await firstRecord(page); await open(page, url); await expect(page.locator('mat-card-title', { hasText: 'Etapas del tamizaje' })).toHaveCount(0); const stages = historial(page).locator('[data-section=etapas] app-stages li'); await expect(stages).toHaveCount(5); // one row: the five nodes are level const tops = await stages .locator('.node') .evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top))); expect(new Set(tops).size).toBe(1); // each stage says its name, state, day and both intervals, centred const first = stages.first(); await expect(first).toContainText('Toma de muestra'); await expect(first).toContainText('Registrada'); await expect(first).toContainText('Desde anterior: —'); await expect(first).toContainText('Desde toma: 0 días'); expect( await first.locator('.info').evaluate((e) => getComputedStyle(e.parentElement!).textAlign), ).toBe('center'); await expect(historial(page)).toContainText('a la fecha de corte'); await expect(historial(page).getByRole('button', { name: 'Exportar PDF' })).toBeVisible(); // history and tests keep their tables await expect(historial(page).getByRole('table')).toBeVisible(); await expect(page.locator('mat-card-title', { hasText: 'Pruebas y resultados' })).toBeVisible(); }); test('ficha: the export of the record still downloads its PDF', async ({ page }) => { const { url } = await firstRecord(page); await open(page, url); const saved = page.waitForEvent('download'); await historial(page).getByRole('button', { name: 'Exportar PDF' }).click(); expect((await saved).suggestedFilename()).toBe('expediente-cacu.pdf'); }); test('ficha: with no model both horizons are drawn grey, not available, without a marker', async ({ page, }) => { const { url } = await firstRecord(page); await open(page, url); for (const label of [IMMEDIATE, FIVE]) { const box = scale(page, label); await expect(box).toContainText('No disponible'); expect(await drawn(box)).toMatchObject({ markers: 0, grey: 1 }); await expect(box.locator('.risk-labels span')).toHaveText([ '0 %', '25 %', '50 %', '75 %', '100 %', ]); } await expect( page.getByText('Divisiones numéricas descriptivas; no representan umbrales clínicos.'), ).toBeVisible(); }); test('ficha (simulado): every state of a stage, its dates and its intervals', async ({ page }) => { const { url, sample } = await firstRecord(page); await withRoute(page, sample, { report: 14, colposcopy: 30, request: 40, biopsy: 50, diagnosis: 70, link: 'recorded', }); await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`); const stages = historial(page).locator('app-stages li'); const text = async (n: number) => (await stages.nth(n).innerText()).replace(/\s+/g, ' '); expect(await text(0)).toContain(`Registrada ${sample}`); expect(await text(1)).toContain( `Registrada ${plus(sample, 14)} Procedencia: Formulario de citología Desde anterior: 14 días Desde toma: 14 días`, ); // colposcopy and diagnosis are inferred from dates: their intervals say so expect(await text(2)).toContain( `Inferida por fechas ${plus(sample, 30)} Desde anterior: 16 días (inferido) Desde toma: 30 días (inferido)`, ); // a recorded biopsy link is recorded; the interval since an inferred stage is still inferred expect(await text(3)).toContain( `Registrada ${plus(sample, 50)} Desde anterior: 20 días (inferido) Desde toma: 50 días`, ); expect(await text(4)).toContain( `Inferida por fechas ${plus(sample, 70)} Desde anterior: 20 días (inferido)`, ); const state = (n: number) => stages .nth(n) .locator('.node') .evaluate( (e) => getComputedStyle(e).backgroundColor + '|' + getComputedStyle(e).borderTopStyle, ); expect(await state(0)).toBe('rgb(56, 123, 102)|solid'); // recorded expect(await state(2)).toBe('rgb(66, 105, 160)|double'); // inferred // an inferred biopsy link: inferred as well await page.unroute('**/api/cacu/fhir/DiagnosticReport**'); await withRoute(page, sample, { report: 14, colposcopy: 30, request: 40, biopsy: 50, diagnosis: 70, }); await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`); expect(await text(3)).toContain('Inferida por fechas'); }); test('ficha (simulado): the cut-off hides what is dated after it; a biopsy asked and not reported is pending', async ({ page, }) => { const { url, sample } = await firstRecord(page); await withRoute(page, sample, { report: 14, colposcopy: 30, request: 40, biopsy: 50, diagnosis: 70, }); const cutoff = plus(sample, 45); // after the request, before the report await open(page, `${url.split('?')[0]}?corte=${cutoff}&citologia=${sample}`); const stages = historial(page).locator('app-stages li'); const states = await stages.locator('.info span:nth-child(2)').allInnerTexts(); expect(states.map((s) => s.trim())).toEqual([ 'Registrada', 'Registrada', 'Inferida por fechas', 'Pendiente', 'Sin dato', ]); await expect(historial(page)).toContainText(`a la fecha de corte ${cutoff}`); const pending = await stages .nth(3) .locator('.node') .evaluate((e) => getComputedStyle(e).backgroundColor); expect(pending).toBe('rgb(255, 241, 201)'); const unknown = await stages .nth(4) .locator('.node') .evaluate((e) => getComputedStyle(e).borderTopStyle); expect(unknown).toBe('dashed'); await expect(stages.nth(4)).toContainText('Sin fecha'); await expect(stages.nth(4)).toContainText('Desde toma: —'); // a cut-off before the sample: nothing is known await page.unroute('**/api/cacu/fhir/DiagnosticReport**'); await withRoute(page, sample, { report: 14 }); await open(page, `${url.split('?')[0]}?corte=${plus(sample, -1)}&citologia=${sample}`); expect( await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(), ).toEqual(Array(5).fill('Sin dato')); }); test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tell zero from absent', async ({ page, }) => { const { url } = await firstRecord(page); await withRisks(page, [ risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [ [0, 0], [5, 0.5, 0.4, 0.6], ]), risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [ [0, 0.02, 0.01, 0.03], [5, 0.98, 0.95, 1], ]), risk('c', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]), // no immediate horizon risk('d', 'Parcial v1', 'cacu.partial', '2026-05-01', [[0, 0.5]]), // no five-year horizon ]); await open(page, url); await expect( page.getByRole('heading', { name: 'Supervivencia v3 · fecha índice 2026-02-01' }), ).toBeVisible(); await expect( page.getByRole('heading', { name: 'Recurrencia v2 · fecha índice 2026-03-01' }), ).toBeVisible(); const at = async (label: string, nth: number) => drawn(scale(page, label, nth)); // group order follows the page's models: survival, recurrence, other, partial const groups = await page.locator('.risk-scale').count(); expect(groups).toBe(8); // both horizons of four models const model = async (n: number) => [await at(IMMEDIATE, n), await at(FIVE, n)]; const [survival, recurrence, other, partial] = [ await model(0), await model(1), await model(2), await model(3), ]; expect(survival[0]).toMatchObject({ markers: 1, left: '0%', value: '0.0 %', grey: 0 }); // a real zero expect(survival[1]).toMatchObject({ left: '50%', value: '50.0 %' }); expect(recurrence[0]).toMatchObject({ left: '2%', value: '2.0 %' }); expect(recurrence[1]).toMatchObject({ left: '98%', value: '98.0 %' }); expect(other[0]).toMatchObject({ markers: 0, grey: 1 }); // absent, not zero expect(other[1]).toMatchObject({ left: '100%', value: '100.0 %' }); expect(partial[0]).toMatchObject({ left: '50%' }); expect(partial[1]).toMatchObject({ markers: 0, grey: 1 }); await expect(scale(page, IMMEDIATE, 2)).toContainText('No disponible'); await expect(scale(page, FIVE, 3)).toContainText('No disponible'); await expect(scale(page, FIVE, 0)).toContainText('IC 95 %: 40.0–60.0 %'); await expect(scale(page, FIVE, 1)).toContainText('IC 95 %: 95.0–100.0 %'); await expect(scale(page, IMMEDIATE, 0)).not.toContainText('IC 95 %'); // none published, none invented // the descriptive note stays, and the model table and curve of rebuild are still there await expect(page.getByText('no representan umbrales clínicos')).toBeVisible(); await expect(page.getByRole('columnheader', { name: 'Probabilidad', exact: true })).toBeVisible(); }); test('ficha (simulado): the scale is drawn in four equal segments with the numeric divisions', async ({ page, }) => { const { url } = await firstRecord(page); await withRisks(page, [ risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]), ]); await open(page, url); const box = scale(page, FIVE); await expect(box.locator('.risk-labels span')).toHaveText([ '0 %', '25 %', '50 %', '75 %', '100 %', ]); const line = await box.locator('.risk-line').evaluate((e) => getComputedStyle(e).backgroundImage); for (const colour of [ 'rgb(66, 167, 126)', 'rgb(168, 194, 67)', 'rgb(223, 134, 64)', 'rgb(194, 66, 105)', ]) expect(line).toContain(colour); // the marker sits at 50 % of the bar const [bar, mark] = await Promise.all([ box.locator('.risk-plot').boundingBox(), box.locator('.risk-marker').boundingBox(), ]); expect(Math.abs(mark!.x + mark!.width / 2 - (bar!.x + bar!.width / 2))).toBeLessThan(3); }); for (const width of [1440, 480]) { test(`ficha (simulado) at ${width} px: the stages and the scales lay out cleanly`, async ({ page, }) => { await page.setViewportSize({ width, height: 1000 }); const { url, sample } = await firstRecord(page); await withRoute(page, sample, { report: 14, colposcopy: 30, request: 40, biopsy: 50, diagnosis: 70, link: 'recorded', }); await withRisks(page, [ risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [ [0, 0], [5, 0.98, 0.95, 1], ]), risk('b', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]), ]); await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`); await page.waitForTimeout(800); expect(await layoutProblems(page)).toEqual([]); const tops = await historial(page) .locator('app-stages li .node') .evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top))); // wide: one row of nodes; narrow: a column (each below the previous) if (width > 700) expect(new Set(tops).size).toBe(1); else { expect(tops).toEqual([...tops].sort((a, b) => a - b)); expect(new Set(tops).size).toBe(5); } expect( await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), ).toBe(true); }); } const code = (name: string, valueCode: string) => ({ url: EXT + name, valueCode }); const nodeOf = (page: Page, n: number) => historial(page).locator('app-stages li').nth(n); /** A record, by the API, whose cytology (the latest of the first patients) satisfies `wanted`. */ async function recordWhere(page: Page, wanted: (report: any) => boolean) { const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json(); const ids: string[] = patients.entry.map((e: any) => e.resource.id); for (let i = 0; i < ids.length; i += 25) { const subject = ids .slice(i, i + 25) .map((p) => 'Patient/' + p) .join(','); const found = await ( await page.request.get(`/api/cacu/fhir/DiagnosticReport?_count=200&subject=${subject}`) ).json(); for (const { resource: r } of found.entry ?? []) if (r.code?.coding?.[0]?.code === 'cervical_cytology' && wanted(r)) return { id: r.subject.reference.split('/')[1] as string, sample: r.effectiveDateTime as string, }; } throw new Error('no record with those stages in the first patients'); } const has = (r: any, name: string) => (r.extension ?? []).some((e: any) => e.url === EXT + name); test('ficha: the stages say what the backend demonstrates, with their sources', async ({ page, }) => { const { id, sample } = await recordWhere( page, (r) => has(r, 'stage-colposcopy-state') && has(r, 'stage-biopsy-state'), ); await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`); const states = await historial(page) .locator('app-stages li .info span:nth-child(2)') .allInnerTexts(); expect(states[0]).toBe('Registrada'); expect(states[2]).toBe('Inferida por fechas'); // colposcopy is always inferred expect(['Inferida por fechas', 'Registrada']).toContain(states[3]); const colposcopy = (await nodeOf(page, 2).innerText()).replace(/\s+/g, ' '); expect(colposcopy).toMatch(/Procedencia: (Nota clínica|Orden de biopsia)/); expect(colposcopy).toContain('Desde anterior:'); expect((await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ')).toMatch( /Procedencia: (Asociación por fechas|Registro de la biopsia)/, ); // the first two stages come from the form expect(await nodeOf(page, 0).innerText()).toContain('Procedencia: Formulario de citología'); }); test('ficha (simulado): a stage the backend flags as ambiguous is drawn so, with no interval resting on it', async ({ page, }) => { const { url, sample } = await firstRecord(page); await withRoute(page, sample, { report: 14, colposcopy: 30, request: 40, biopsy: 50, diagnosis: 70, extra: [ code('stage-biopsy-state', 'ambiguous'), code('stage-biopsy-source', 'date-association'), code('stage-colposcopy-state', 'inferred'), code('stage-colposcopy-source', 'clinical-note'), code('stage-colposcopy-source', 'biopsy-order'), ], }); await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`); const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' '); expect(biopsy).toContain(`Ambigua ${plus(sample, 50)}`); expect(biopsy).toContain('Procedencia: Asociación por fechas'); expect(biopsy).toContain('Desde anterior: — Desde toma: —'); expect( await nodeOf(page, 3) .locator('.node') .evaluate((e) => getComputedStyle(e).borderTopStyle), ).toBe('double'); // no interval rests on the ambiguous day, so the next stage has none from the previous one either expect((await nodeOf(page, 4).innerText()).replace(/\s+/g, ' ')).toContain('Desde anterior: —'); // a colposcopy dated by a note and a biopsy order lists both sources expect(await nodeOf(page, 2).innerText()).toContain( 'Procedencia: Nota clínica · Orden de biopsia', ); }); test('ficha (simulado): a biopsy the backend says is pending shows its request, not a day', async ({ page, }) => { const { url, sample } = await firstRecord(page); await withRoute(page, sample, { report: 14, colposcopy: 30, request: 40, extra: [ code('stage-biopsy-state', 'pending'), code('stage-biopsy-source', 'date-association'), code('biopsy-link', 'inferred'), ], }); await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`); const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' '); expect(biopsy).toContain('Pendiente'); expect(biopsy).toContain(`Solicitada el ${plus(sample, 40)}`); expect(biopsy).toContain('Desde toma: —'); // colposcopy and diagnosis are never pending: no request is known for them expect( await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(), ).not.toContain('Pendiente' + 'x'); const states = ( await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts() ).map((t) => t.trim()); expect(states.filter((t) => t === 'Pendiente')).toHaveLength(1); }); // ---- the record's tests and its antecedents const antecedents = (page: Page) => page.locator('[data-section=antecedentes]'); const tests = (page: Page) => page.locator('mat-card', { has: page.locator('mat-card-title', { hasText: 'Pruebas y resultados' }), }); test('ficha: antecedents and gynecologic evaluation have their own section; tests keep their results', async ({ page, }) => { const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8); await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`); const card = antecedents(page); await expect(card).toBeVisible(); await expect(card).toContainText('no son diagnósticos confirmados'); await expect(card).toContainText(`Citología cervical · toma ${sample}`); for (const title of [ 'Detección de cáncer de cérvix', 'Condición ginecoobstétrica a la detección', 'Actualmente presenta', 'A la exploración se observa', ]) await expect(card.locator('dl.facts dt', { hasText: title })).toBeVisible(); // the earlier forms are collapsed, each with its own day const earlier = card.locator('details.findings'); if (await earlier.count()) { expect(await earlier.getAttribute('open')).toBeNull(); await earlier.locator('summary').click(); await expect(earlier.locator('tbody tr').first().locator('td').first()).toHaveText( /\d{4}-\d{2}-\d{2}/, ); } // the tests keep date, study, report and the results of the study, without the form's antecedents const table = tests(page); await expect(table.getByRole('columnheader')).toHaveText([ 'Toma', 'Estudio', 'Reporte', 'Resultados', ]); const text = await table.innerText(); expect(text).toContain('Resultado (Bethesda)'); expect(text).not.toContain('Detección de cáncer de cérvix'); expect(text).not.toContain('A la exploración se observa'); // the extra findings are collapsed under their report const findings = table.locator('details.findings').first(); await expect(findings.locator('summary')).toContainText('Hallazgos ('); expect(await findings.getAttribute('open')).toBeNull(); expect((await findings.locator('li').first().textContent())!.trim().length).toBeGreaterThan(0); }); test('ficha (simulado): a missing antecedent says it is not documented; with none, no section', async ({ page, }) => { const { url } = await firstRecord(page); const strip = (keep: string[]) => page.route('**/api/cacu/fhir/Observation**', async (route) => { const response = await route.fetch(); const body = await response.json(); body.entry = (body.entry ?? []).filter((e: any) => { const field = (e.resource.code?.coding?.[0]?.code ?? '').split('.').pop(); const antecedent = [ 'screening_history', 'gynecologic_condition', 'presenting_symptom', 'cervix_appearance', ].includes(field); return !antecedent || keep.includes(field); }); await route.fulfill({ response, body: JSON.stringify(body), contentType: 'application/fhir+json', }); }); await strip(['screening_history']); await open(page, url); const card = antecedents(page); await expect(card.locator('dl.facts dd').first()).not.toHaveText('No documentado'); await expect(card.locator('dl.facts dd', { hasText: 'No documentado' })).toHaveCount(3); await page.unroute('**/api/cacu/fhir/Observation**'); await strip([]); await open(page, url); await expect(antecedents(page)).toHaveCount(0); // the record's tests are still there without them await expect(tests(page).getByRole('table')).toBeVisible(); }); test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ page }) => { const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8); await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`); const saved = page.waitForEvent('download'); await historial(page).getByRole('button', { name: 'Exportar PDF' }).click(); const download = await saved; expect(download.suggestedFilename()).toBe('expediente-cacu.pdf'); const file = await download.path(); expect(file).toBeTruthy(); const { readFileSync } = await import('node:fs'); const bytes = readFileSync(file!); expect(bytes.subarray(0, 4).toString()).toBe('%PDF'); expect(bytes.length).toBeGreaterThan(5_000); });