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 }); } test('ficha (simulado): states why a hysterectomy makes this risk assessment unavailable', async ({ page, }) => { const { url, sample } = await firstRecord(page); const previousDay = plus(sample, -1); await page.route('**/api/cacu/fhir/Patient/*', async (route) => { const response = await route.fetch(); const patient = await response.json(); patient.extension = [ ...(patient.extension ?? []), { url: EXT + 'first-hysterectomy-recorded', valueDate: sample }, ]; await route.fulfill({ response, json: patient }); }); await withRisks(page, [risk('past', 'Modelo v1', 'cacu.cin2_pim', previousDay, [[5, 0.2]])]); await open(page, url); await expect( page.getByText('Sin estimación de riesgo por antecedente de histerectomía', { exact: false, }), ).toBeVisible(); await expect(page.locator('app-risk-scales')).toHaveCount(0); const historical = new URL(url, 'http://example.test'); historical.searchParams.set('citologia', previousDay); await open(page, historical.pathname + historical.search); await expect(page.locator('app-risk-scales')).toBeVisible(); }); /** 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.cin2_pim', '2026-02-01', [ [0, 0], [5, 0.5, 0.4, 0.6], ]), risk('b', 'Recurrencia v2', 'cacu.cancer_pim', '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.cin2_pim', '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.cin2_pim', '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); }); // ---- the NCI reference comparison (experimental) and the institutional curves --------------------- const REFERENCE = '**/api/cacu/fhir/Patient/*/$reference-risk*'; const section = (page: Page) => page.locator('[data-section=referencia-nci]'); const value = (p: any) => p.valueCode ?? p.valueString ?? p.valueDate ?? p.valueInteger ?? p.valueDecimal ?? p.valueBoolean; /** The first patients' answers of the API, to find one with a given state (the data is synthetic). */ async function referenceWhere(page: Page, status: string) { const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json(); for (const { resource } of patients.entry) { const answer = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$reference-risk`); if (!answer.ok()) throw new Error(`the reference operation answered ${answer.status()}`); const body = await answer.json(); if (value(body.parameter.find((p: any) => p.name === 'status')) === status) return { id: resource.id as string, body }; } throw new Error(`no patient with the state ${status}`); } const part = (name: string, extra: object) => ({ name, ...extra }); const answerOf = (...parameter: object[]) => ({ resourceType: 'Parameters', parameter }); /** A resolved answer for fixtures, with the given horizons and comparisons. */ function fixture( horizons: { years: number; reference?: number; comparison?: object[] }[], more: object[] = [], ) { return answerOf( part('status', { valueCode: 'resolved' }), part('experimental', { valueBoolean: true }), part('cutoff', { valueDate: '2026-11-30' }), part('scenario', { part: [ part('table', { valueCode: 'screening' }), part('label', { valueString: 'Tamizaje' }), part('key', { part: [ part('name', { valueCode: 'history' }), part('value', { valueString: 'Cotest-negative' }), ], }), ], }), part('source', { part: [ part('id', { valueString: 'fixture-table' }), part('file', { valueString: 'fixture.xlsx' }), part('outcome', { valueCode: 'CIN3+' }), ], }), ...more, ...horizons.map((h) => part('horizon', { part: [ part('years', { valueInteger: h.years }), part('published', { valueBoolean: h.reference !== undefined }), ...(h.reference !== undefined ? [part('reference', { valueDecimal: h.reference })] : []), ...(h.comparison ?? []), ], }), ), ); } const comparison = (status: string, reasons: string[], extra: object[] = []) => part('comparison', { part: [ part('model', { valueCode: 'fixture.model' }), part('title', { valueString: 'Modelo de prueba' }), part('outcome', { valueString: 'CIN3+' }), ...extra, part('status', { valueCode: status }), ...reasons.map((r) => part('reason', { valueCode: r })), ], }); const answerWith = (page: Page, body: object, status = 200) => page.route(REFERENCE, (route) => route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }), ); test('referencia NCI: a resolved cytology shows its reference with scenario, source and no institutional model', async ({ page, }) => { const { id, body } = await referenceWhere(page, 'resolved'); await open(page, `/indicadores/cacu/pacientes/${id}`); const box = section(page); await expect(box).toBeVisible(); await expect(box.locator('dd[data-status=resolved]')).toHaveText('Referencia disponible'); await expect(box).toContainText('Tamizaje'); await expect(box).toContainText('CIN3 o más grave (CIN3+)'); await expect(box).toContainText('Master_NCI_Risk_Table.xlsx'); const rows = box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'); await expect(rows).toHaveCount(2); await expect(rows.first()).toContainText('Inmediato (al índice)'); await expect(rows.nth(1)).toContainText('5 años'); // the figures are the API's: percent with two decimals, and no institutional model is made up const expected = body.parameter .filter((p: any) => p.name === 'horizon') .map((h: any) => (h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2), ); for (const [i, pct] of expected.entries()) await expect(rows.nth(i).locator('td').nth(1)).toContainText(`${pct} %`); // no model evaluated her: said once, not on every horizon await expect(box.locator('.nomodel')).toContainText('No disponible'); await expect(box.getByText('Ningún modelo institucional ha evaluado a la paciente.')).toHaveCount( 1, ); await expect(box.locator('[data-model]')).toHaveCount(0); // the antecedents used are collapsed const used = box.locator('details.used'); expect(await used.getAttribute('open')).toBeNull(); await used.locator('summary').click(); await expect(used).toContainText('Fila de origen'); await expect(used).toContainText('Citología evaluada'); // the other risk displays of the record are still there, and the reference is below the scales await expect(scale(page, FIVE)).toBeVisible(); const [scales, reference] = await Promise.all([ scale(page, FIVE).boundingBox(), box.boundingBox(), ]); expect(reference!.y).toBeGreaterThan(scales!.y); await expect( page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }), ).toBeVisible(); }); test('referencia NCI: a cytology the tables cannot resolve says the state and why, with no figure', async ({ page, }) => { const { id } = await referenceWhere(page, 'unverifiable_correspondence'); await open(page, `/indicadores/cacu/pacientes/${id}`); const box = section(page); await expect(box.locator('dd[data-status=unverifiable_correspondence]')).toHaveText( 'Correspondencia no verificable', ); await expect(box.locator('ul.why li').first()).not.toBeEmpty(); await expect(box.locator('table')).toHaveCount(0); await expect(box).not.toContainText('%'); }); test('referencia NCI: with the feature off (404) the section is not there and the record is whole', async ({ page, }) => { const { url } = await firstRecord(page); await answerWith( page, { resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] }, 404, ); await open(page, url); await expect(section(page)).toHaveCount(0); await expect(scale(page, FIVE)).toBeVisible(); }); test('referencia NCI (simulado): a comparison that is valid shows the difference as institutional minus reference', async ({ page, }) => { const { url } = await firstRecord(page); await answerWith( page, fixture([ { years: 5, reference: 0.0027, comparison: [ comparison( 'comparable', [], [ part('institutional', { valueDecimal: 0.0127 }), part('institutional-low', { valueDecimal: 0.005 }), part('institutional-high', { valueDecimal: 0.02 }), part('difference-pp', { valueDecimal: 1 }), ], ), ], }, ]), ); await open(page, url); const block = section(page).locator('[data-model]'); await expect(block.locator('h5')).toContainText('Modelo de prueba'); await expect(block.locator('h5')).toContainText('CIN3 o más grave (CIN3+)'); const row = block.locator('tbody tr').first(); await expect(row).toContainText('1.27 %'); await expect(row).toContainText('IC 95 %: 0.50–2.00 %'); await expect( section(page).locator('table').first().locator('tbody tr').first().locator('td').nth(1), ).toContainText('0.27 %'); await expect(row.locator('td').nth(2)).toContainText('+1.00'); await expect(row.locator('td').nth(2)).not.toContainText('No comparable'); }); test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({ page, }) => { const { url } = await firstRecord(page); await answerWith( page, fixture([ { years: 0, reference: 0.0001, comparison: [ comparison( 'not_comparable', ['outcome_differs', 'horizon_not_published_by_model', 'population_not_verified'], [part('institutional', { valueDecimal: 0.05 })], ), ], }, { years: 5, reference: 0.0027 }, ]), ); await open(page, url); const first = section(page).locator('[data-model] tbody tr').first(); await expect(first.locator('td').nth(2)).toContainText('No comparable'); await expect(first.locator('td').nth(2)).toContainText( 'El desenlace del modelo no es el de la tabla (CIN3+)', ); await expect(first.locator('td').nth(2)).toContainText( 'no publica una predicción a este horizonte', ); await expect(first.locator('td').nth(2)).not.toContainText(/[+-]\d/); // no signed difference await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted }); test('referencia NCI (simulado): a year-one reference is a year, never the immediate risk; a blank is not zero', async ({ page, }) => { const { url } = await firstRecord(page); await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }])); await open(page, url); const rows = section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'); await expect(rows.first()).toContainText('1 año'); await expect(section(page)).not.toContainText('Inmediato'); await expect(rows.nth(1).locator('td').nth(1)).toContainText('No publicado'); await expect(rows.nth(1).locator('td').nth(1)).not.toContainText('0.00'); await expect(rows.first().locator('td').nth(1)).toContainText('1.36 %'); }); for (const width of [1440, 480]) { test(`referencia NCI (simulado) at ${width} px: the section lays out cleanly beside the scales and curves`, async ({ page, }) => { await page.setViewportSize({ width, height: 1000 }); const { url } = await firstRecord(page); await answerWith( page, fixture( [ { years: 0, reference: 0.0001, comparison: [ comparison( 'not_comparable', ['outcome_differs', 'population_not_verified'], [part('institutional', { valueDecimal: 0.05 })], ), ], }, { years: 5, reference: 0.0027, comparison: [ comparison( 'comparable', [], [ part('institutional', { valueDecimal: 0.0127 }), part('difference-pp', { valueDecimal: 1 }), ], ), ], }, ], [part('assumption', { valueString: 'un supuesto sin verificar' })], ), ); await withRisks(page, [ risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [ [1, 0.08, 0.05, 0.12], [3, 0.21, 0.15, 0.28], [5, 0.34, 0.26, 0.44], ]), risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [ [1, 0.002, 0.001, 0.005], [3, 0.008], [5, 0.015, 0.008, 0.028], ]), ]); await open(page, url); await section(page).locator('details.used summary').click(); await page.waitForTimeout(800); expect(await layoutProblems(page)).toEqual([]); expect( await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), ).toBe(true); }); } test('curvas (simulado): one series per model at its published horizons, its band only where it has intervals, and no NCI data', async ({ page, }) => { const { url } = await firstRecord(page); await answerWith(page, fixture([{ years: 5, reference: 0.0027 }])); await withRisks(page, [ risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [ [1, 0.08, 0.05, 0.12], [3, 0.21, 0.15, 0.28], [5, 0.34, 0.26, 0.44], ]), risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [ [1, 0.002, 0.001, 0.005], [3, 0.008], [5, 0.015, 0.008, 0.028], ]), risk('c', 'Sin intervalo v1', 'cacu.other', '2026-06-01', [ [2, 0.1], [4, 0.2], ]), risk('d', 'Un punto v1', 'cacu.partial', '2026-06-01', [[5, 0.5]]), ]); await open(page, url); const card = page.locator('details.curves'); await expect(card.locator('summary')).toHaveText('Curvas de probabilidad con su intervalo'); await expect(card).toHaveAttribute('open', ''); await expect(card.locator('li').first()).toContainText( 'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 % (IC 95 %: 5.0–12.0 %); 3 años: 21.0 %', ); const plot = await card.locator('.js-plotly-plot').evaluate((e: any) => ({ names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name), series: Object.fromEntries( e.data.filter((t: any) => t.mode?.includes('markers')).map((t: any) => [t.name, t.x]), ), bands: e.data.filter((t: any) => t.fill === 'tonexty').map((t: any) => t.name), ticks: e.layout.xaxis.tickvals, title: e.layout.xaxis.title.text, })); expect(plot.series).toEqual({ 'Riesgo LIEAG+': [1, 3, 5], 'Riesgo cáncer': [1, 3, 5], 'Sin intervalo': [2, 4], 'Un punto': [5], }); expect(plot.bands).toEqual(['IC 95 % Riesgo LIEAG+', 'IC 95 % Riesgo cáncer']); // none for the models without intervals expect(plot.ticks).toEqual([1, 2, 3, 4, 5]); expect(plot.title).toBe('Horizonte (años desde la fecha índice (2026-06-01))'); // the reference is a separate table: its 0.27 % is nowhere in the figure expect( JSON.stringify(await card.locator('.js-plotly-plot').evaluate((e: any) => e.data)), ).not.toContain('0.27'); await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); }); // ---- the grouped NCI comparison, the survival texts and the risk-model selection (all "simulado") ------ const SHOTS = process.env['SHOTS_DIR']; // when set, the simulated pages are saved for the report const shot = async (page: Page, name: string, kind = 'SIMULADO') => { if (SHOTS) await page.screenshot({ path: `${SHOTS}/${kind}-${name}.png`, fullPage: true }); }; const institutional = (p: number, low?: number, high?: number, diff?: number) => [ part('institutional', { valueDecimal: p }), ...(low === undefined ? [] : [part('institutional-low', { valueDecimal: low })]), ...(high === undefined ? [] : [part('institutional-high', { valueDecimal: high })]), ...(diff === undefined ? [] : [part('difference-pp', { valueDecimal: diff })]), ]; const model = ( code: string, title: string, outcome: string, status: string, reasons: string[], extra: object[] = [], ) => part('comparison', { part: [ part('model', { valueCode: code }), part('title', { valueString: title }), part('outcome', { valueString: outcome }), ...extra, part('status', { valueCode: status }), ...reasons.map((r) => part('reason', { valueCode: r })), ], }); const SHARED = ['index_date_differs', 'population_not_verified']; for (const width of [1440, 480]) { test(`referencia NCI (simulado) at ${width} px: several models, outcomes and horizons are grouped without losing any`, async ({ page, }) => { await page.setViewportSize({ width, height: 1000 }); const { url } = await firstRecord(page); await answerWith( page, fixture( [ { years: 0, reference: 0.0001, comparison: [ model( 'cacu.cin2_pim', 'Riesgo LIEAG+', 'CIN2+', 'not_comparable', ['outcome_differs', ...SHARED], institutional(0.05, 0.03, 0.08), ), model( 'cacu.cancer_pim', 'Riesgo de cáncer', 'cancer', 'not_comparable', ['outcome_differs', ...SHARED], institutional(0.002), ), model( 'cacu.cin2_logistic', 'Riesgo LIEAG+ a un año', 'CIN2+ within one year', 'not_comparable', ['horizon_not_published_by_model', 'outcome_differs', ...SHARED], ), ], }, { years: 1, comparison: [ model( 'cacu.cin2_logistic', 'Riesgo LIEAG+ a un año', 'CIN2+ within one year', 'not_comparable', ['no_reference', 'outcome_differs', ...SHARED], institutional(0.04), ), ], }, { years: 5, reference: 0.0027, comparison: [ model( 'cacu.cin2_pim', 'Riesgo LIEAG+', 'CIN2+', 'not_comparable', ['outcome_differs', ...SHARED], institutional(0.12, 0.08, 0.17), ), model( 'cacu.cancer_pim', 'Riesgo de cáncer', 'cancer', 'not_comparable', ['outcome_differs', ...SHARED], institutional(0.011, 0.006, 0.02), ), model( 'cacu.cin3_fixture', 'Modelo CIN3+ de prueba', 'CIN3+', 'comparable', [], institutional(0.0127, 0.005, 0.02, 1), ), ], }, ], [part('assumption', { valueString: 'un supuesto sin verificar' })], ), ); await open(page, url); const box = section(page); // the outcome of the reference comes from the answer; the models' are translated for display only await expect(box).toContainText('Desenlace de la referencia'); const blocks = box.locator('[data-model]'); await expect(blocks).toHaveCount(4); await expect(blocks.locator('h5 [data-outcome="cancer"]')).toHaveText('Cáncer'); await expect(blocks.locator('h5 [data-outcome="CIN2+ within one year"]')).toHaveText( 'CIN2+ en un año', ); await expect(blocks.locator('h5 [data-outcome="CIN2+"]')).toContainText('CIN2'); // the reference is one table; each model keeps its own horizons, values and intervals await expect( box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'), ).toHaveCount(3); const pim = box.locator('[data-model="cacu.cin2_pim"] tbody tr'); await expect(pim).toHaveCount(2); await expect(pim.first()).toContainText('5.00 %'); await expect(pim.first()).toContainText('IC 95 %: 3.00–8.00 %'); await expect(pim.nth(1)).toContainText('12.00 %'); // an absent interval stays absent; a missing value says so await expect(box.locator('[data-model="cacu.cancer_pim"] tbody tr').first()).not.toContainText( 'IC 95 %', ); await expect(box.locator('[data-model="cacu.cin2_logistic"] tbody tr').first()).toContainText( 'No disponible', ); // reasons every incompatible comparison gives are said once, not on each row const common = box.locator('ul[aria-label="Motivos comunes"] li'); await expect(common).toHaveCount(3); // outcome_differs is in every incompatible row too await expect( box.getByText('La fecha índice del modelo no es la de la citología evaluada.'), ).toHaveCount(1); // a difference only on the valid comparison const valid = box.locator('[data-model="cacu.cin3_fixture"] tbody tr'); await expect(valid.locator('td').nth(2)).toContainText('+1.00'); await expect( box.locator('[data-model="cacu.cin2_pim"] tbody td:nth-child(3)').first(), ).not.toContainText(/[+-]\d/); // the reasons of one horizon only stay on that row await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText( 'no publica una predicción a este horizonte', ); await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText( 'no dan un riesgo a este horizonte', ); await box.locator('details.used summary').click(); await page.waitForTimeout(600); expect(await layoutProblems(page)).toEqual([]); expect( await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), ).toBe(true); await shot(page, `referencia-nci-agrupada-${width}`); }); } test('referencia NCI (simulado): with no institutional model it says so once; the reference stays', async ({ page, }) => { const { url } = await firstRecord(page); await answerWith( page, fixture([ { years: 0, reference: 0.0001, comparison: [ part('comparison', { part: [ part('status', { valueCode: 'not_comparable' }), part('reason', { valueCode: 'no_institutional_model' }), ], }), ], }, { years: 5, reference: 0.0027, comparison: [ part('comparison', { part: [ part('status', { valueCode: 'not_comparable' }), part('reason', { valueCode: 'no_institutional_model' }), ], }), ], }, ]), ); await open(page, url); await expect( section(page).getByText('Ningún modelo institucional ha evaluado a la paciente.'), ).toHaveCount(1); await expect( section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'), ).toHaveCount(2); await shot(page, 'referencia-nci-sin-modelos'); }); const scenarioReport = (name: string, n: number, deaths: number) => ({ escenario: name, n, fallecidos: deaths, horizons_months: [12, 36, 60], km: { months: [0, 12, 36, 60], S: [1, 0.92, 0.8, 0.7], low: [1, 0.85, 0.7, 0.55], high: [1, 0.97, 0.9, 0.82], }, weibull: { t: [0, 12, 36, 60], S: [1, 0.93, 0.81, 0.69] }, weibull_fractional: { t: [0, 12, 36, 60], S: [1, 0.91, 0.79, 0.71] }, points: { COMB: { S: [0.92, 0.8, 0.7], low: [0.85, 0.7, 0.55], high: [0.97, 0.9, 0.82] } }, }); async function withSurvival(page: Page, domain: 'cacu' | 'cama', others: object[] = []) { const assessed = { ...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]), extension: [ { url: EXT + 'escenario-clinico', valueString: 'Edad al diagnóstico · 45-54 años' }, { url: EXT + 'escenario-clinico', valueString: 'VPH positivo' }, ], }; await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) => route.fulfill({ contentType: 'application/fhir+json', body: JSON.stringify({ resourceType: 'Bundle', type: 'searchset', entry: [assessed, ...others].map((resource) => ({ resource })), }), }), ); await page.route( `**/api/models/${domain}/survival/versions/*/reports/interpretability`, (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify({ escenarios: [ scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6), scenarioReport('VPH positivo', 30, 9), ], factores_escenarios: [], }), }), ); } for (const width of [1440, 480]) { test(`supervivencia (simulado) at ${width} px: CaCu says the curves are the scenario group's, not individual predictions`, async ({ page, }) => { await page.setViewportSize({ width, height: 1000 }); const { url } = await firstRecord(page); await withSurvival(page, 'cacu'); await open(page, url); const card = page.locator('[data-section=supervivencia]'); await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico'); await expect(card).not.toContainText('Riesgo de muerte'); await expect(card.locator('[data-note=grupo]')).toContainText( 'estimaciones del grupo de pacientes del escenario clínico', ); await expect(card.locator('[data-note=grupo]')).toContainText( 'no son predicciones individuales', ); await expect(card.locator('h4')).toHaveText([ 'Edad al diagnóstico · 45-54 años (n = 12, fallecidos = 6)', 'VPH positivo (n = 30, fallecidos = 9)', ]); // the curves are the report's, untouched const plot = await card .locator('.js-plotly-plot') .first() .evaluate((e: any) => ({ names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name), y: e.layout.yaxis.title.text, x: e.layout.xaxis.title.text, })); expect(plot.y).toBe('Supervivencia S(t)'); expect(plot.x).toBe('Meses desde el diagnóstico'); expect(plot.names).toContain('Kaplan-Meier (IC 95 % Greenwood)'); expect( await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), ).toBe(true); await shot(page, `supervivencia-cacu-${width}`); }); } test('supervivencia (simulado): CaMa keeps its own title and no group note', async ({ page }) => { const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); const id = patients.entry[0].resource.id; await withSurvival(page, 'cama'); await page.goto(`/indicadores/cama/pacientes/${id}`); const card = page.locator('[data-section=supervivencia]'); await expect(card).toBeVisible({ timeout: 120_000 }); await expect(card.locator('mat-card-title')).toHaveText('Riesgo de muerte'); await expect(card.locator('[data-note=grupo]')).toHaveCount(0); await shot(page, 'supervivencia-cama-sin-cambios'); }); const SCALES = [IMMEDIATE, 'Riesgo a 5 años']; test('escalas (simulado): a survival estimate alone never feeds the risk scales or curves; they say "No disponible"', async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 1000 }); const { url } = await firstRecord(page); await withSurvival(page, 'cacu'); // only cacu.survival: S(5 years) = 70 % await open(page, url); for (const label of SCALES) { await expect(scale(page, label)).toContainText('No disponible'); await expect(scale(page, label).locator('.risk-marker')).toHaveCount(0); } await expect(page.locator('.risk-value')).toHaveCount(0); // no 70 % on a risk scale await expect(page.locator('details.curves')).toHaveCount(0); await expect(page.locator('table.plain', { hasText: 'Probabilidad' })).toHaveCount(0); // the survival is still in its own analysis, as the group's estimate const card = page.locator('[data-section=supervivencia]'); await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico'); await expect(card.locator('h4').first()).toContainText('n = 12'); await shot(page, 'escalas-solo-supervivencia-1440'); }); test('escalas (simulado): with a survival model and compatible risk models, only the risk models feed the scales and curves', async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 1000 }); const { url } = await firstRecord(page); await withSurvival(page, 'cacu', [ risk('r1', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [ [0, 0.03, 0.02, 0.05], [5, 0.12, 0.08, 0.17], ]), risk('r2', 'Riesgo de cáncer v2', 'cacu.cancer_pim', '2026-06-01', [[5, 0.011, 0.006, 0.02]]), ]); await open(page, url); const values = await page.locator('.risk-value').allInnerTexts(); expect(values.map((v) => v.trim())).toEqual(['3.0 %', '12.0 %', '1.1 %']); // none is the 70 % survival await expect(scale(page, 'Riesgo a 5 años', 0)).toContainText('IC 95 %: 8.0–17.0'); await expect(scale(page, IMMEDIATE, 1)).toContainText('No disponible'); // the cancer model has no immediate risk await expect(page.locator('app-risk-scales h3')).toHaveText([ 'Riesgo LIEAG+ v3 · fecha índice 2026-06-01', 'Riesgo de cáncer v2 · fecha índice 2026-06-01', ]); const curves = page.locator('details.curves'); await expect(curves).not.toContainText('Supervivencia'); expect( JSON.stringify(await curves.locator('.js-plotly-plot').evaluate((e: any) => e.data)), ).not.toContain('70'); const table = page.locator('table.plain', { hasText: 'Probabilidad' }); await expect(table).not.toContainText('Supervivencia'); // the survival analysis and the NCI reference stay await expect(page.locator('[data-section=supervivencia]')).toBeVisible(); await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); await shot(page, 'escalas-supervivencia-y-riesgo-1440'); }); // ---- "Elegibilidad por escenario clínico": the decisions the backend publishes per indexed visit ---- const ELIGIBILITY = '**/api/cacu/fhir/Patient/*/$eligibility*'; const SCENARIO_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario'; const CRITERION_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion'; const eligibilityBox = (page: Page) => page.locator('[data-section=elegibilidad]'); const visit = ( scenario: string, date: string, eligible: boolean, criteria: string[] = [], sample?: string, ) => part('candidate', { part: [ part('scenario', { valueCoding: { system: SCENARIO_SYSTEM, code: scenario } }), part('index-date', { valueDate: date }), ...(sample ? [part('index-sample-id', { valueString: sample })] : []), part('eligible', { valueBoolean: eligible }), ...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code: c } }), ), ], }); const eligibilityAnswer = (status: string, ...candidates: object[]) => answerOf( part('status', { valueCode: status }), part('patient', { valueReference: { reference: 'Patient/x' } }), part('cutoff', { valueDate: '2026-12-02' }), ...candidates, ); const eligibilityIs = (page: Page, body: object, status = 200) => page.route(ELIGIBILITY, (route) => route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }), ); test('elegibilidad: the real answer of the backend is shown scenario by scenario, with every reason', async ({ page, }) => { const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=200')).json(); let found: { id: string; body: any } | undefined; for (const { resource } of patients.entry) { const body = await ( await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$eligibility`) ).json(); const many = body.parameter.some( (p: any) => p.name === 'candidate' && p.part.filter((x: any) => x.name === 'criterion').length > 1, ); if (many) { found = { id: resource.id, body }; break; } } expect(found, 'a synthetic patient with several reasons in one visit').toBeTruthy(); await open(page, `/indicadores/cacu/pacientes/${found!.id}`); const box = eligibilityBox(page); await expect(box.locator('mat-card-title')).toHaveText('Elegibilidad por escenario clínico'); const candidates = found!.body.parameter.filter((p: any) => p.name === 'candidate'); const scenarios = new Set( candidates.map((c: any) => c.part.find((x: any) => x.name === 'scenario').valueCoding.code), ); await expect(box.locator('details.scenario')).toHaveCount(scenarios.size); await expect(box.locator('li.visit')).toHaveCount(candidates.length); const reasons = candidates.flatMap((c: any) => c.part.filter((x: any) => x.name === 'criterion')); await expect(box.locator('ul.why li')).toHaveCount(reasons.length); // none is dropped or merged await expect(box).toContainText('Antecedente de cáncer cervicouterino'); await shot(page, 'elegibilidad', 'SINTETICO-REAL'); }); for (const width of [1440, 480]) { test(`elegibilidad (simulado) at ${width} px: several scenarios and visits, eligible and not, several reasons each`, async ({ page, }) => { await page.setViewportSize({ width, height: 1000 }); const { url } = await firstRecord(page); await eligibilityIs( page, eligibilityAnswer( 'evaluated', visit('surveillance', '2024-01-05', true, [], 'm-1'), visit('surveillance', '2025-03-01', false, ['no_index_result', 'prior_outcome'], 'm-2'), visit('surveillance', '2025-09-10', true, [], 'm-3'), visit( 'post_colposcopy', '2023-06-01', false, ['cancer_history', 'outcome_by_index', 'prior_treatment', 'no_referral'], '2023-06-01', ), visit('survival', '2024-12-01', true), visit('nuevo_escenario', '2025-01-01', false, ['regla_nueva']), ), ); await open(page, url); const box = eligibilityBox(page); const groups = box.locator('details.scenario'); await expect(groups).toHaveCount(4); await expect(groups.nth(1)).toContainText('Postcolposcopia'); // the backend's order is kept await expect(groups.nth(1)).toContainText('1 visita · 0 elegibles, 1 no elegible'); // a scenario with more than two visits is collapsed but keeps every detail in the page const surveillance = box.locator('[data-scenario=surveillance]'); await expect(surveillance).toContainText('3 visitas · 2 elegibles, 1 no elegible'); expect(await surveillance.getAttribute('open')).toBeNull(); await surveillance.locator('summary').click(); const visits = surveillance.locator('li.visit'); await expect(visits).toHaveCount(3); await expect(visits.first()).toContainText('Fecha índice 2025-09-10'); await expect(visits.first()).toContainText('Elegible'); await expect(visits.nth(1)).toContainText('No elegible'); await expect(visits.nth(1)).toContainText('Muestra m-2'); await expect(visits.nth(1).locator('ul.why li')).toHaveText([ 'Sin resultado de citología o VPH en la visita índice', 'Resultado CIN2+ previo al índice', ]); // all four reasons of one visit; decisions of different visits are never combined await expect(box.locator('[data-scenario=post_colposcopy] ul.why li')).toHaveCount(4); await expect(visits.first().locator('ul.why')).toHaveCount(0); await expect(box.locator('[data-scenario=survival]')).toContainText('Sin muestra asociada'); // an unknown scenario and criterion show their code and keep it await expect(box.locator('[data-scenario=nuevo_escenario] summary')).toContainText( 'nuevo_escenario', ); await expect( box.locator('[data-scenario=nuevo_escenario] li[data-code=regla_nueva]'), ).toHaveText('regla_nueva'); await box.locator('[data-scenario=nuevo_escenario] summary').click(); await page.waitForTimeout(500); expect(await layoutProblems(page)).toEqual([]); expect( await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), ).toBe(true); await shot(page, `elegibilidad-varios-escenarios-${width}`); }); } const STATES: [string, () => object | undefined, number, string, string][] = [ ['sin candidatos', () => eligibilityAnswer('no_candidate'), 200, 'none', 'Sin candidatos'], [ 'información no disponible (404)', () => ({ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] }), 404, 'unavailable', 'no disponible', ], [ 'respuesta fuera del contrato', () => ({ resourceType: 'Parameters', parameter: [] }), 200, 'unavailable', 'no disponible', ], [ 'actualización de gold requerida (409)', () => ({ resourceType: 'OperationOutcome', issue: [ { severity: 'error', code: 'conflict', diagnostics: 'CaCu eligibility gold is not materialized; rebuild gold.cacu_eligibility.', }, ], }), 409, 'gold', 'actualizar la capa gold', ], [ 'error del servidor (500)', () => ({ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'exception' }] }), 500, 'error', 'No se pudo consultar', ], ]; for (const [name, body, status, state, text] of STATES) { test(`elegibilidad (simulado): ${name} has its own state and never reads as eligible`, async ({ page, }) => { const { url } = await firstRecord(page); await eligibilityIs(page, body()!, status); await open(page, url); const box = eligibilityBox(page); await expect(box.locator(`[data-state=${state}]`)).toContainText(text); await expect(box.locator('li.visit')).toHaveCount(0); await expect(box).not.toContainText('Elegible'); if (state === 'gold') await expect(box).toContainText('rebuild gold.cacu_eligibility'); await shot(page, `elegibilidad-${state}`); }); } test('elegibilidad (simulado): no connection is a communication error', async ({ page }) => { const { url } = await firstRecord(page); await page.route(ELIGIBILITY, (route) => route.abort()); await open(page, url); await expect(eligibilityBox(page).locator('[data-state=error]')).toContainText( 'No se pudo consultar', ); }); test('elegibilidad (simulado): the section waits for the answer and a new patient starts from nothing', async ({ page, }) => { await page.goto('/indicadores/cacu'); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); const links = page.locator('table.worklist tbody tr a'); await links.first().waitFor({ timeout: 120_000 }); const hrefs = await links.evaluateAll((els) => els.slice(0, 2).map((e) => e.getAttribute('href')!), ); expect(hrefs.length).toBe(2); const ids = hrefs.map((h) => /pacientes\/([^?]+)/.exec(h)![1]); let releaseSecond!: () => void; const gate = new Promise((resolve) => (releaseSecond = resolve)); await page.route(ELIGIBILITY, async (route) => { const mine = route.request().url().includes(ids[0]); if (!mine) await gate; // the second patient's answer is held await route.fulfill({ contentType: 'application/fhir+json', body: JSON.stringify( mine ? eligibilityAnswer( 'evaluated', visit('surveillance', '2024-01-05', false, ['prior_outcome'], 'primera'), ) : eligibilityAnswer( 'evaluated', visit('post_treatment', '2025-05-05', true, [], 'segunda'), ), ), }); }); await open(page, hrefs[0]); await expect(eligibilityBox(page)).toContainText('primera'); await page.getByRole('link', { name: 'Regresar' }).click(); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.locator(`a[href*="${ids[1]}"]`).first().click(); await expect(historial(page)).toBeVisible({ timeout: 120_000 }); await expect(eligibilityBox(page).locator('[data-state=loading]')).toBeVisible(); await expect(eligibilityBox(page)).not.toContainText('primera'); // nothing of the previous patient releaseSecond(); await expect(eligibilityBox(page)).toContainText('segunda'); await expect(eligibilityBox(page)).not.toContainText('primera'); }); test('elegibilidad: CaMa has no such section and never asks for it', async ({ page }) => { let asked = false; await page.route('**/$eligibility*', (route) => { asked = true; return route.abort(); }); 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}`); await expect(page.locator('app-paciente')).toBeVisible({ timeout: 120_000 }); await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 }); await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0); expect(asked).toBe(false); });