From a43cf4b51b2e0d7867e2296d3165825a385ae173 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 2 Dec 2026 19:26:50 -0600 Subject: [PATCH] Distinguir ausencias e insuficiencia en supervivencia CaCu --- e2e/ficha-cacu.spec.ts | 480 +++++++++++--------- src/app/gobernanza/figures.ts | 72 ++- src/app/paciente/paciente.html | 19 +- src/app/paciente/paciente.ts | 13 +- src/app/paciente/survival-scenarios.spec.ts | 102 +++++ src/app/paciente/survival-scenarios.ts | 51 +++ 6 files changed, 512 insertions(+), 225 deletions(-) create mode 100644 src/app/paciente/survival-scenarios.spec.ts create mode 100644 src/app/paciente/survival-scenarios.ts diff --git a/e2e/ficha-cacu.spec.ts b/e2e/ficha-cacu.spec.ts index 1969bbd..917a428 100644 --- a/e2e/ficha-cacu.spec.ts +++ b/e2e/ficha-cacu.spec.ts @@ -118,17 +118,18 @@ async function open(page: Page, url: string) { await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 }); } -test('ficha (simulado): states why a hysterectomy makes this risk assessment unavailable', async ({ +test('ficha (simulado): uses the recorded hysterectomy when eligibility is unavailable', async ({ page, }) => { const { url, sample } = await firstRecord(page); const previousDay = plus(sample, -1); + await eligibilityIs(page, {}, 503); 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 }, + { url: EXT + 'first-hysterectomy-recorded', valueDate: sample.slice(0, 10) }, ]; await route.fulfill({ response, json: patient }); }); @@ -136,7 +137,7 @@ test('ficha (simulado): states why a hysterectomy makes this risk assessment una await open(page, url); await expect( - page.getByText('Sin estimación de riesgo por antecedente de histerectomía', { + page.getByText('No disponible por: histerectomía registrada el', { exact: false, }), ).toBeVisible(); @@ -1244,13 +1245,16 @@ const scenarioReport = (name: string, n: number, deaths: number) => ({ 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[] = []) { +async function withSurvival( + page: Page, + domain: 'cacu' | 'cama', + others: object[] = [], + report?: object, + scenarios = ['Edad al diagnóstico · 45-54 años', 'VPH positivo'], +) { 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' }, - ], + extension: scenarios.map((valueString) => ({ url: EXT + 'escenario-clinico', valueString })), }; await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) => route.fulfill({ @@ -1267,13 +1271,15 @@ async function withSurvival(page: Page, domain: 'cacu' | 'cama', others: object[ (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: [], - }), + body: JSON.stringify( + report ?? { + escenarios: [ + scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6), + scenarioReport('VPH positivo', 30, 9), + ], + factores_escenarios: [], + }, + ), }), ); } @@ -1386,250 +1392,214 @@ test('escalas (simulado): with a survival model and compatible risk models, only await shot(page, 'escalas-supervivencia-y-riesgo-1440'); }); -// ---- "Elegibilidad por escenario clínico": the decisions the backend publishes per indexed visit ---- +// ---- Eligibility decisions in "Riesgos y recomendaciones" ---- 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, -) => +const riskBox = (page: Page) => + page.locator('mat-card', { + has: page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }), + }); +const visit = (scenario: string, date: string, eligible: boolean, criteria: 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 } }), + ...criteria.map((code) => + part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code } }), ), ], }); const eligibilityAnswer = (status: string, ...candidates: object[]) => - answerOf( - part('status', { valueCode: status }), - part('patient', { valueReference: { reference: 'Patient/x' } }), - part('cutoff', { valueDate: '2026-12-02' }), - ...candidates, - ); + answerOf(part('status', { valueCode: status }), ...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, +async function withFollowUp(page: Page, status: string, recorded?: string) { + await page.route('**/api/cacu/fhir/Patient/*', async (route) => { + const response = await route.fetch(); + const patient = await response.json(); + patient.extension = (patient.extension ?? []).filter( + (e: { url: string }) => + e.url !== EXT + 'follow-up-status' && e.url !== EXT + 'first-hysterectomy-recorded', ); - if (many) { - found = { id: resource.id, body }; + patient.extension.push({ url: EXT + 'follow-up-status', valueCoding: { code: status } }); + if (recorded) { + patient.extension.push({ url: EXT + 'first-hysterectomy-recorded', valueDate: recorded }); + } + await route.fulfill({ response, json: patient }); + }); +} + +test('elegibilidad: the risk section shows the published post-treatment exclusion', async ({ page }) => { + const patients = await page.request.get( + '/api/cacu/fhir/Patient?_count=200&follow-up-status=post_treatment', + ); + expect(patients.ok()).toBe(true); + const { entry } = await patients.json(); + const code = 'no_pretreatment_biopsy'; + let patientId: string | undefined; + for (const { resource } of entry ?? []) { + const response = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$eligibility`); + expect(response.ok()).toBe(true); + const { parameter } = await response.json(); + const latest = parameter + .filter((p: any) => + p.name === 'candidate' && p.part.some((v: any) => + v.name === 'scenario' && v.valueCoding.code === 'post_treatment', + ), + ) + .map((p: any) => ({ + day: p.part.find((v: any) => v.name === 'index-date').valueDate as string, + eligible: p.part.find((v: any) => v.name === 'eligible').valueBoolean as boolean, + criteria: p.part.filter((v: any) => v.name === 'criterion').map((v: any) => v.valueCoding.code), + })) + .sort((a: { day: string }, b: { day: string }) => b.day.localeCompare(a.day))[0]; + if (latest && !latest.eligible && latest.criteria.length === 1 && latest.criteria[0] === code) { + patientId = resource.id; 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), + expect(patientId, 'a synthetic patient with a published post-treatment exclusion').toBeDefined(); + await open(page, `/indicadores/cacu/pacientes/${patientId}`); + const box = riskBox(page); + await expect(box.getByRole('status')).toHaveText( + 'No disponible por: Sin biopsia previa al tratamiento en el periodo requerido.', ); - 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'); + await expect(box.locator('app-risk-scales')).toHaveCount(0); + await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0); }); for (const width of [1440, 480]) { - test(`elegibilidad (simulado) at ${width} px: several scenarios and visits, eligible and not, several reasons each`, async ({ + test('elegibilidad (simulado) at ' + width + ' px: the risk section shows all reasons from the selected visit', async ({ page, }) => { await page.setViewportSize({ width, height: 1000 }); - const { url } = await firstRecord(page); + const { url, sample } = await firstRecord(page); + const day = sample.slice(0, 10); + await withFollowUp(page, 'pre_colposcopy'); 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']), + visit('pre_colposcopy', plus(day, 1), true), + visit('pre_colposcopy', plus(day, -3), false, ['regla_anterior']), + visit('pre_colposcopy', plus(day, -2), false, ['no_index_result', 'regla_nueva']), + visit('surveillance', day, false, ['cancer_history']), + visit('post_colposcopy', day, false, ['prior_treatment']), ), ); 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', + const box = riskBox(page); + await expect(box.getByRole('status')).toHaveText( + 'No disponible por: Sin resultado de citología o VPH en la visita índice; regla_nueva.', ); - 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); + await expect(box.locator('app-risk-scales')).toHaveCount(0); + await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0); 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 ({ +test('elegibilidad (simulado): precolposcopy falls back to surveillance when it has no visit by the index', async ({ + page, +}) => { + const { url, sample } = await firstRecord(page); + const day = sample.slice(0, 10); + await withFollowUp(page, 'pre_colposcopy'); + await eligibilityIs( 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()); + eligibilityAnswer( + 'evaluated', + visit('pre_colposcopy', plus(day, 1), true), + visit('surveillance', day, false, ['prior_outcome']), + ), + ); await open(page, url); - await expect(eligibilityBox(page).locator('[data-state=error]')).toContainText( - 'No se pudo consultar', + await expect(riskBox(page).getByRole('status')).toHaveText( + 'No disponible por: Resultado CIN2+ previo al índice.', ); }); -test('elegibilidad (simulado): the section waits for the answer and a new patient starts from nothing', async ({ +for (const status of ['evaluated', 'no_candidate']) { + test('elegibilidad (simulado): ' + status + ' takes precedence over recorded hysterectomy', async ({ + page, + }) => { + const { url, sample } = await firstRecord(page); + const day = sample.slice(0, 10); + await withFollowUp(page, 'pre_colposcopy', day); + await eligibilityIs( + page, + status === 'evaluated' + ? eligibilityAnswer( + status, + visit('pre_colposcopy', day, true), + visit('surveillance', day, false, ['hysterectomy']), + ) + : eligibilityAnswer(status), + ); + const answer = page.waitForResponse((r) => r.url().includes('/$eligibility')); + await open(page, url); + await answer; + await expect(riskBox(page).locator('app-risk-scales')).toBeVisible(); + await expect(riskBox(page).getByText('No disponible por:', { exact: false })).toHaveCount(0); + await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0); + }); +} + +test('elegibilidad (simulado): a new patient never inherits the previous risk exclusion', async ({ page, }) => { - await page.goto('/indicadores/cacu'); - await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); + await firstRecord(page); 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)); + const records = await links.evaluateAll((els) => { + const unique = new Map(); + for (const el of els) { + const href = el.getAttribute('href')!; + const id = /pacientes\/([^?]+)/.exec(href)![1]; + if (!unique.has(id)) unique.set(id, href); + if (unique.size === 2) break; + } + return [...unique]; + }); + expect(records).toHaveLength(2); + const [[firstId, firstUrl], [secondId]] = records; + await withFollowUp(page, 'pre_colposcopy'); + let release!: () => void; + const gate = new Promise((resolve) => (release = 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 + const first = new URL(route.request().url()).pathname.endsWith(`/${firstId}/$eligibility`); + if (!first) await gate; 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'), - ), + json: eligibilityAnswer( + 'evaluated', + visit('pre_colposcopy', '1900-01-01', !first, first ? ['prior_outcome'] : []), ), }); }); - 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'); + + const reason = riskBox(page).getByText('No disponible por: Resultado CIN2+ previo al índice.'); + try { + await open(page, firstUrl); + await expect(reason).toBeVisible(); + await page.getByRole('link', { name: 'Regresar' }).click(); + await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); + await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click(); + await expect(historial(page)).toBeVisible({ timeout: 120_000 }); + await expect(riskBox(page).locator('app-risk-scales')).toBeVisible(); + await expect(reason).toHaveCount(0); + const answer = page.waitForResponse((r) => r.url().includes(`/${secondId}/$eligibility`)); + release(); + await answer; + await expect(riskBox(page).locator('app-risk-scales')).toBeVisible(); + await expect(reason).toHaveCount(0); + } finally { + release(); + } }); test('elegibilidad: CaMa has no such section and never asks for it', async ({ page }) => { @@ -1645,3 +1615,105 @@ test('elegibilidad: CaMa has no such section and never asks for it', async ({ pa await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0); expect(asked).toBe(false); }); + +// ---- survival curves: absent values, insufficient data and absent scenarios (all "simulado") ---- + +const A = 'Edad al diagnóstico · 45-54 años'; +const B = 'VPH negativo'; +const C = 'Citología · LIEAG'; +const partial = scenarioReport(A, 12, 6); +partial.km = { + months: [0, 12, 24, 36], + S: [1, 0.9, 0.8, 0.7], + low: [1, 0.8, null, 0.55], + high: [1, 0.95, null, 0.82], +} as any; +partial.points = { + COMB: { S: [0, null, 0.7], low: [null, null, 0.55], high: [null, null, 0.82] }, +} as any; +const contract = { + escenarios: [partial], + escenarios_sin_curvas: [{ escenario: B, n: 9, fallecidos: 2 }], + min_fallecidos_escenario: 5, + factores_escenarios: [], +}; + +for (const width of [1440, 480]) { + test(`supervivencia (simulado) at ${width} px: absent limits draw no band, zero is not unavailable, insufficient data is told apart from an absent scenario`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 1000 }); + const { url } = await firstRecord(page); + await withSurvival(page, 'cacu', [], contract, [A, B, C]); + await open(page, url); + const card = page.locator('[data-section=supervivencia]'); + await expect(card.locator('[data-note=grupo]')).toContainText( + 'no son predicciones individuales', + ); + const plot = await card + .locator('.js-plotly-plot') + .first() + .evaluate((e: any) => ({ + bands: e.data.filter((t: any) => t.fill === 'toself').map((t: any) => t.y), + model: e.data.find((t: any) => t.name?.startsWith('LR + HBN')), + km: e.data.find((t: any) => t.name?.startsWith('Kaplan')), + })); + expect(plot.bands.length).toBe(1); // only where both limits exist (the first two points) + expect(plot.bands[0].every((v: unknown) => typeof v === 'number')).toBe(true); + expect(plot.km.y).toEqual([1, 0.9, 0.8, 0.7]); // the curve itself stays whole + expect(plot.model.y).toEqual([0, null, 0.7]); // a real zero is drawn; the unavailable value is a gap + expect(plot.model.error_y.array).toEqual([null, null, expect.closeTo(0.12, 5)]); // no bar from absent limits + const insufficient = card.locator('[data-state=insuficiente]'); + await expect(insufficient).toHaveCount(1); + await expect(insufficient).toContainText('Datos insuficientes para trazar la curva'); + await expect(insufficient).toContainText('n = 9, fallecidos = 2'); + await expect(insufficient).toContainText('mínimo requerido: 5 fallecidos'); + const absent = card.locator('[data-state=sin-informacion]'); + await expect(absent).toHaveCount(1); + await expect(absent).toContainText( + 'Sin información de este escenario en el informe del modelo', + ); + await expect(absent).not.toContainText('insuficientes'); + await expect(card.locator('h4', { hasText: C })).toHaveCount(1); + await expect(card.locator('h4', { hasText: B })).toHaveCount(1); + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), + ).toBe(true); + await shot(page, `supervivencia-valores-ausentes-${width}`); + }); +} + +test('supervivencia (simulado): CaCu distinguishes an unlisted scenario from having no applicable report', async ({ + page, +}) => { + const { url } = await firstRecord(page); + await withSurvival(page, 'cacu', [], { escenarios: [], factores_escenarios: [] }, [A]); + await open(page, url); + const card = page.locator('[data-section=supervivencia]'); + await expect(card.locator('[data-state=sin-informacion]')).toHaveCount(1); + await expect(card.locator('[data-state=insuficiente]')).toHaveCount(0); + await expect(card).not.toContainText('datos insuficientes'); + + await page.unroute('**/api/cacu/fhir/RiskAssessment**'); + await withSurvival(page, 'cacu', [], undefined, []); + await open(page, url); + await expect(card.locator('[data-state=sin-informe]')).toHaveText( + 'No disponible: no hay un informe de supervivencia para los escenarios de la paciente.', + ); + await expect(card.locator('[data-state=insuficiente]')).toHaveCount(0); +}); + +test('supervivencia (simulado): CaMa keeps its own wording for a scenario without a curve', async ({ + page, +}) => { + const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json(); + await withSurvival(page, 'cama', [], contract, [A, B]); + await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.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).toContainText('No disponible: datos insuficientes.'); + await expect(card.locator('[data-state=insuficiente], [data-state=sin-informacion]')).toHaveCount( + 0, + ); +}); diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts index 61b7a26..3cdec7c 100644 --- a/src/app/gobernanza/figures.ts +++ b/src/app/gobernanza/figures.ts @@ -10,23 +10,44 @@ interface Band { high?: (number | null)[]; } +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); + +/** The stretches of x where the curve has both limits: a band is drawn only there, never from a + * limit that is absent (an absent limit is not zero). */ +function bandRuns(b: Band): number[][] { + const runs: number[][] = []; + let run: number[] = []; + b.x.forEach((x, i) => { + if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i); + else { + if (run.length > 1) runs.push(run); + run = []; + } + }); + if (run.length > 1) runs.push(run); + return runs; +} + function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial[] { const lines: Partial[] = []; if (b.low && b.high) { - lines.push({ - x: [...b.x, ...[...b.x].reverse()], - y: [...b.high, ...[...b.low].reverse()] as number[], - fill: 'toself', - fillcolor: `${colour}33`, - line: { width: 0 }, - hoverinfo: 'skip', - showlegend: false, - type: 'scatter', - }); + for (const run of bandRuns(b)) { + const x = run.map((i) => b.x[i]); + lines.push({ + x: [...x, ...[...x].reverse()], + y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[], + fill: 'toself', + fillcolor: `${colour}33`, + line: { width: 0 }, + hoverinfo: 'skip', + showlegend: false, + type: 'scatter', + }); + } } lines.push({ x: b.x, - y: b.y, + y: b.y.map((v) => (finite(v) ? v : null)) as number[], name, type: 'scatter', mode: 'lines', @@ -295,20 +316,33 @@ export function scenarioFigure( }; } +/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a + * point without both limits has no bar. */ function points( name: string, x: number[], - p: { S: number[]; low: number[]; high: number[] }, + p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] }, ): Partial { + const errors = p.S.map((value, i) => { + const low = p.low?.[i]; + const high = p.high?.[i]; + return finite(value) && finite(low) && finite(high) + ? { up: high - value, down: value - low } + : null; + }); return { x, - y: p.S, - error_y: { - type: 'data', - symmetric: false, - array: p.high.map((h, i) => h - p.S[i]), - arrayminus: p.S.map((v, i) => v - p.low[i]), - }, + y: p.S.map((v) => (finite(v) ? v : null)) as number[], + ...(errors.some((error) => error !== null) + ? { + error_y: { + type: 'data' as const, + symmetric: false, + array: errors.map((error) => error?.up ?? null) as number[], + arrayminus: errors.map((error) => error?.down ?? null) as number[], + }, + } + : {}), name, type: 'scatter', mode: 'markers', diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index 65f2de8..ebc5402 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -603,11 +603,28 @@

{{ name }}

No disponible: datos insuficientes.

} + @for (u of s.insufficient; track u.name) { +

{{ u.name }}

+

{{ insufficientText(u) }}

+ } + @for (name of s.missing; track name) { +

{{ name }}

+

+ Sin información de este escenario en el informe del modelo. +

+ } } @else if (survival.error()) { } @else { -

No disponible: datos insuficientes.

+

+ @if (domain() === 'cacu') { + No disponible: no hay un informe de supervivencia para los escenarios de la + paciente. + } @else { + No disponible: datos insuficientes. + } +

} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index f4791f5..8272a1f 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -13,6 +13,7 @@ import type { RiskAssessment, } from 'fhir/r4'; import { Api } from '../api/api'; +import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios'; import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility'; import { studies as eegStudies } from '../api/fn/eeg/studies'; import { study as eegStudy } from '../api/fn/eeg/study'; @@ -415,6 +416,8 @@ export class Paciente { factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[], scenarios: m.scenarios, unavailable: [] as string[], + insufficient: [] as Insufficient[], + missing: [] as string[], methods: [] as string[], figures: mine(r['escenarios'] ?? []).map((e) => scenarioFigure( @@ -435,12 +438,19 @@ export class Paciente { 'Supervivencia S(t)', ), ); + const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s)); + // CaCu: the report says which scenarios lack deaths (`escenarios_sin_curvas`); one it does not + // mention is not "insufficient", it is absent from the report. Other domains keep one list. + const { insufficient, missing } = + domain === 'cacu' ? sortUndrawn(report, undrawn) : { insufficient: [], missing: [] }; return { factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[], scenarios: m.scenarios, figures, // her scenarios the report draws no curve for - unavailable: m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s)), + unavailable: domain === 'cacu' ? [] : undrawn, + insufficient, + missing, methods: methods(figures), }; }, @@ -563,6 +573,7 @@ export class Paciente { ...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)), ); } + protected readonly insufficientText = insufficientText; protected readonly name = name; protected readonly levelNames = LEVEL_NAMES; protected readonly identity = computed(() => { diff --git a/src/app/paciente/survival-scenarios.spec.ts b/src/app/paciente/survival-scenarios.spec.ts new file mode 100644 index 0000000..83c115e --- /dev/null +++ b/src/app/paciente/survival-scenarios.spec.ts @@ -0,0 +1,102 @@ +import { scenarioFigure } from '../gobernanza/figures'; +import { insufficientText, sortUndrawn } from './survival-scenarios'; + +const base = (over: object = {}) => ({ + km: { + months: [0, 12, 24, 36], + S: [1, 0.9, 0.8, 0.7], + low: [1, 0.8, 0.7, 0.55], + high: [1, 0.95, 0.9, 0.82], + }, + weibull: { t: [0, 36], S: [1, 0.7] }, + weibull_fractional: { t: [0, 36], S: [1, 0.72] }, + points: { COMB: { S: [0.9, 0.7], low: [0.8, 0.55], high: [0.95, 0.82] } }, + ...over, +}); +const draw = (e: object) => scenarioFigure('t', e, [12, 36], 'S(t)').figure.data as any[]; +const bands = (d: any[]) => d.filter((t) => t.fill === 'toself'); +const model = (d: any[]) => d.find((t) => t.name?.startsWith('LR + HBN')); + +describe('survival curves with absent values', () => { + it('complete data draw one band and symmetric-free error bars, as before', () => { + const d = draw(base()); + expect(bands(d).length).toBe(1); + expect(bands(d)[0].x.length).toBe(8); + expect(model(d).error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.05, 0.12]); + expect(model(d).error_y.arrayminus.map((v: number) => +v.toFixed(2))).toEqual([0.1, 0.15]); + }); + it('a band is drawn only where both limits exist, never from an absent one', () => { + const km = { + months: [0, 12, 24, 36, 48], + S: [1, 0.9, 0.8, 0.7, 0.6], + low: [1, 0.8, null, 0.55, 0.4], + high: [1, 0.95, null, 0.82, 0.7], + }; + const d = draw(base({ km })); + expect(bands(d).map((b) => b.x.length)).toEqual([4, 4]); // [0,12] and [36,48]; each polygon out and back + for (const b of bands(d)) expect(b.y.every((v: unknown) => typeof v === 'number')).toBe(true); + const none = draw( + base({ + km: { ...km, low: [null, null, null, null, null], high: [null, null, null, null, null] }, + }), + ); + expect(bands(none).length).toBe(0); // no limits: no band at all + expect(none.find((t) => t.name?.startsWith('Kaplan')).y).toEqual([1, 0.9, 0.8, 0.7, 0.6]); // the curve stays + }); + it('a point without its limits has no bar; zero is a value and unavailable is not drawn', () => { + const d = draw( + base({ points: { COMB: { S: [0, null], low: [null, null], high: [null, null] } } }), + ); + const m = model(d); + expect(m.y).toEqual([0, null]); // 0 % is drawn at 0, an absent value is a gap + expect(m.error_y).toBeUndefined(); // no invented limits + expect(model(draw(base({ points: { COMB: { S: [0, null] } } }))).error_y).toBeUndefined(); + const half = model( + draw(base({ points: { COMB: { S: [0.9, 0.7], low: [0.8, null], high: [0.95, null] } } })), + ); + expect(half.error_y.array).toEqual([expect.closeTo(0.05, 5), null]); + expect(half.error_y.arrayminus).toEqual([expect.closeTo(0.1, 5), null]); + }); +}); + +describe('scenarios without a curve', () => { + const report = { + escenarios_sin_curvas: [ + { escenario: 'VPH negativo', n: 9, fallecidos: 2 }, + { escenario: 'Citología · ASC-H', n: 0, fallecidos: 0 }, + ], + min_fallecidos_escenario: 5, + }; + it('those the report lists as lacking deaths keep its numbers and the minimum', () => { + expect(sortUndrawn(report, ['VPH negativo', 'Citología · ASC-H']).insufficient).toEqual([ + { name: 'VPH negativo', n: 9, deaths: 2, minimum: 5 }, + { name: 'Citología · ASC-H', n: 0, deaths: 0, minimum: 5 }, // zero deaths is a count, not a gap + ]); + }); + it('one the report does not mention is absent, never "insufficient"', () => { + expect(sortUndrawn(report, ['VPH negativo', 'Edad · 45-54']).missing).toEqual(['Edad · 45-54']); + expect(sortUndrawn({}, ['a'])).toEqual({ insufficient: [], missing: ['a'] }); + expect(sortUndrawn(null, ['a'])).toEqual({ insufficient: [], missing: ['a'] }); + expect(sortUndrawn({ escenarios_sin_curvas: 'x' }, ['a']).missing).toEqual(['a']); + }); + it('a listing without counts is still insufficient, without inventing numbers', () => { + expect( + sortUndrawn({ escenarios_sin_curvas: [{ escenario: 'a' }] }, ['a']).insufficient, + ).toEqual([{ name: 'a', n: undefined, deaths: undefined, minimum: undefined }]); + }); +}); + +describe('the insufficient-data text', () => { + it("says the report's numbers and leaves out the ones it did not give", () => { + expect(insufficientText({ name: 'a', n: 9, deaths: 2, minimum: 5 })).toBe( + 'Datos insuficientes para trazar la curva (n = 9, fallecidos = 2; mínimo requerido: 5 fallecidos).', + ); + expect(insufficientText({ name: 'a', n: 0, deaths: 0 })).toBe( + 'Datos insuficientes para trazar la curva (n = 0, fallecidos = 0).', + ); + expect(insufficientText({ name: 'a', n: null, deaths: 0, minimum: 5 })).toBe( + 'Datos insuficientes para trazar la curva (fallecidos = 0; mínimo requerido: 5 fallecidos).', + ); + expect(insufficientText({ name: 'a' })).toBe('Datos insuficientes para trazar la curva.'); + }); +}); diff --git a/src/app/paciente/survival-scenarios.ts b/src/app/paciente/survival-scenarios.ts new file mode 100644 index 0000000..5bc280a --- /dev/null +++ b/src/app/paciente/survival-scenarios.ts @@ -0,0 +1,51 @@ +/** A scenario the report says has too few deaths for a curve, with its counts and the minimum. */ +export interface Insufficient { + name: string; + n?: number | null; + deaths?: number | null; + minimum?: number; +} + +/** Her scenarios without a curve, apart: those the report lists as lacking deaths (with the numbers it + * gives) and those it does not mention at all. */ +export function sortUndrawn( + report: Record | null | undefined, + undrawn: string[], +): { insufficient: Insufficient[]; missing: string[] } { + const listed = ( + Array.isArray(report?.['escenarios_sin_curvas']) ? report['escenarios_sin_curvas'] : [] + ) as { + escenario?: string; + n?: number | null; + fallecidos?: number | null; + }[]; + const minimum = + typeof report?.['min_fallecidos_escenario'] === 'number' + ? report['min_fallecidos_escenario'] + : undefined; + const insufficient: Insufficient[] = []; + const missing: string[] = []; + for (const name of undrawn) { + const found = listed.find((s) => s.escenario === name); + if (found) insufficient.push({ name, n: found.n, deaths: found.fallecidos, minimum }); + else missing.push(name); + } + return { insufficient, missing }; +} + +/** What the section says of a scenario the report lists as lacking deaths; the numbers are the + * report's and a missing one is left out, never replaced. */ +export function insufficientText(u: Insufficient): string { + const fmt = (v: number) => v.toLocaleString('es-MX'); + const counts = [ + typeof u.n === 'number' ? `n = ${fmt(u.n)}` : '', + typeof u.deaths === 'number' ? `fallecidos = ${fmt(u.deaths)}` : '', + ] + .filter(Boolean) + .join(', '); + const details = [ + counts, + u.minimum !== undefined ? `mínimo requerido: ${fmt(u.minimum)} fallecidos` : '', + ].filter(Boolean); + return `Datos insuficientes para trazar la curva${details.length ? ` (${details.join('; ')})` : ''}.`; +}