Distinguir ausencias e insuficiencia en supervivencia CaCu

This commit is contained in:
Angel Capetillo Zavala
2026-12-02 19:26:50 -06:00
parent a4cc80fbe2
commit a43cf4b51b
6 changed files with 512 additions and 225 deletions
+276 -204
View File
@@ -118,17 +118,18 @@ async function open(page: Page, url: string) {
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_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 ({ test('ficha (simulado): uses the recorded hysterectomy when eligibility is unavailable', async ({
page, page,
}) => { }) => {
const { url, sample } = await firstRecord(page); const { url, sample } = await firstRecord(page);
const previousDay = plus(sample, -1); const previousDay = plus(sample, -1);
await eligibilityIs(page, {}, 503);
await page.route('**/api/cacu/fhir/Patient/*', async (route) => { await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
const response = await route.fetch(); const response = await route.fetch();
const patient = await response.json(); const patient = await response.json();
patient.extension = [ patient.extension = [
...(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 }); 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 open(page, url);
await expect( 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, exact: false,
}), }),
).toBeVisible(); ).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] }, 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] } }, 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 = { const assessed = {
...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]), ...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]),
extension: [ extension: scenarios.map((valueString) => ({ url: EXT + 'escenario-clinico', valueString })),
{ 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) => await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) =>
route.fulfill({ route.fulfill({
@@ -1267,13 +1271,15 @@ async function withSurvival(page: Page, domain: 'cacu' | 'cama', others: object[
(route) => (route) =>
route.fulfill({ route.fulfill({
contentType: 'application/json', contentType: 'application/json',
body: JSON.stringify({ body: JSON.stringify(
escenarios: [ report ?? {
scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6), escenarios: [
scenarioReport('VPH positivo', 30, 9), scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6),
], scenarioReport('VPH positivo', 30, 9),
factores_escenarios: [], ],
}), 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'); 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 ELIGIBILITY = '**/api/cacu/fhir/Patient/*/$eligibility*';
const SCENARIO_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario'; const SCENARIO_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
const CRITERION_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion'; const CRITERION_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
const eligibilityBox = (page: Page) => page.locator('[data-section=elegibilidad]'); const riskBox = (page: Page) =>
const visit = ( page.locator('mat-card', {
scenario: string, has: page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
date: string, });
eligible: boolean, const visit = (scenario: string, date: string, eligible: boolean, criteria: string[] = []) =>
criteria: string[] = [],
sample?: string,
) =>
part('candidate', { part('candidate', {
part: [ part: [
part('scenario', { valueCoding: { system: SCENARIO_SYSTEM, code: scenario } }), part('scenario', { valueCoding: { system: SCENARIO_SYSTEM, code: scenario } }),
part('index-date', { valueDate: date }), part('index-date', { valueDate: date }),
...(sample ? [part('index-sample-id', { valueString: sample })] : []),
part('eligible', { valueBoolean: eligible }), part('eligible', { valueBoolean: eligible }),
...criteria.map((c) => ...criteria.map((code) =>
part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code: c } }), part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code } }),
), ),
], ],
}); });
const eligibilityAnswer = (status: string, ...candidates: object[]) => const eligibilityAnswer = (status: string, ...candidates: object[]) =>
answerOf( answerOf(part('status', { valueCode: status }), ...candidates);
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) => const eligibilityIs = (page: Page, body: object, status = 200) =>
page.route(ELIGIBILITY, (route) => page.route(ELIGIBILITY, (route) =>
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }), 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 ({ async function withFollowUp(page: Page, status: string, recorded?: string) {
page, await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
}) => { const response = await route.fetch();
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=200')).json(); const patient = await response.json();
let found: { id: string; body: any } | undefined; patient.extension = (patient.extension ?? []).filter(
for (const { resource } of patients.entry) { (e: { url: string }) =>
const body = await ( e.url !== EXT + 'follow-up-status' && e.url !== EXT + 'first-hysterectomy-recorded',
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) { patient.extension.push({ url: EXT + 'follow-up-status', valueCoding: { code: status } });
found = { id: resource.id, body }; 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; break;
} }
} }
expect(found, 'a synthetic patient with several reasons in one visit').toBeTruthy(); expect(patientId, 'a synthetic patient with a published post-treatment exclusion').toBeDefined();
await open(page, `/indicadores/cacu/pacientes/${found!.id}`); await open(page, `/indicadores/cacu/pacientes/${patientId}`);
const box = eligibilityBox(page); const box = riskBox(page);
await expect(box.locator('mat-card-title')).toHaveText('Elegibilidad por escenario clínico'); await expect(box.getByRole('status')).toHaveText(
const candidates = found!.body.parameter.filter((p: any) => p.name === 'candidate'); 'No disponible por: Sin biopsia previa al tratamiento en el periodo requerido.',
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('app-risk-scales')).toHaveCount(0);
await expect(box.locator('li.visit')).toHaveCount(candidates.length); await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
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]) { 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, page,
}) => { }) => {
await page.setViewportSize({ width, height: 1000 }); 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( await eligibilityIs(
page, page,
eligibilityAnswer( eligibilityAnswer(
'evaluated', 'evaluated',
visit('surveillance', '2024-01-05', true, [], 'm-1'), visit('pre_colposcopy', plus(day, 1), true),
visit('surveillance', '2025-03-01', false, ['no_index_result', 'prior_outcome'], 'm-2'), visit('pre_colposcopy', plus(day, -3), false, ['regla_anterior']),
visit('surveillance', '2025-09-10', true, [], 'm-3'), visit('pre_colposcopy', plus(day, -2), false, ['no_index_result', 'regla_nueva']),
visit( visit('surveillance', day, false, ['cancer_history']),
'post_colposcopy', visit('post_colposcopy', day, false, ['prior_treatment']),
'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); await open(page, url);
const box = eligibilityBox(page); const box = riskBox(page);
const groups = box.locator('details.scenario'); await expect(box.getByRole('status')).toHaveText(
await expect(groups).toHaveCount(4); 'No disponible por: Sin resultado de citología o VPH en la visita índice; regla_nueva.',
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( await expect(box.locator('app-risk-scales')).toHaveCount(0);
box.locator('[data-scenario=nuevo_escenario] li[data-code=regla_nueva]'), await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
).toHaveText('regla_nueva');
await box.locator('[data-scenario=nuevo_escenario] summary').click();
await page.waitForTimeout(500);
expect(await layoutProblems(page)).toEqual([]); 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][] = [ test('elegibilidad (simulado): precolposcopy falls back to surveillance when it has no visit by the index', async ({
['sin candidatos', () => eligibilityAnswer('no_candidate'), 200, 'none', 'Sin candidatos'], page,
[ }) => {
'información no disponible (404)', const { url, sample } = await firstRecord(page);
() => ({ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] }), const day = sample.slice(0, 10);
404, await withFollowUp(page, 'pre_colposcopy');
'unavailable', await eligibilityIs(
'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, page,
}) => { eligibilityAnswer(
const { url } = await firstRecord(page); 'evaluated',
await eligibilityIs(page, body()!, status); visit('pre_colposcopy', plus(day, 1), true),
await open(page, url); visit('surveillance', day, false, ['prior_outcome']),
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 open(page, url);
await expect(eligibilityBox(page).locator('[data-state=error]')).toContainText( await expect(riskBox(page).getByRole('status')).toHaveText(
'No se pudo consultar', '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, page,
}) => { }) => {
await page.goto('/indicadores/cacu'); await firstRecord(page);
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const links = page.locator('table.worklist tbody tr a'); const links = page.locator('table.worklist tbody tr a');
await links.first().waitFor({ timeout: 120_000 }); const records = await links.evaluateAll((els) => {
const hrefs = await links.evaluateAll((els) => const unique = new Map<string, string>();
els.slice(0, 2).map((e) => e.getAttribute('href')!), for (const el of els) {
); const href = el.getAttribute('href')!;
expect(hrefs.length).toBe(2); const id = /pacientes\/([^?]+)/.exec(href)![1];
const ids = hrefs.map((h) => /pacientes\/([^?]+)/.exec(h)![1]); if (!unique.has(id)) unique.set(id, href);
let releaseSecond!: () => void; if (unique.size === 2) break;
const gate = new Promise<void>((resolve) => (releaseSecond = resolve)); }
return [...unique];
});
expect(records).toHaveLength(2);
const [[firstId, firstUrl], [secondId]] = records;
await withFollowUp(page, 'pre_colposcopy');
let release!: () => void;
const gate = new Promise<void>((resolve) => (release = resolve));
await page.route(ELIGIBILITY, async (route) => { await page.route(ELIGIBILITY, async (route) => {
const mine = route.request().url().includes(ids[0]); const first = new URL(route.request().url()).pathname.endsWith(`/${firstId}/$eligibility`);
if (!mine) await gate; // the second patient's answer is held if (!first) await gate;
await route.fulfill({ await route.fulfill({
contentType: 'application/fhir+json', contentType: 'application/fhir+json',
body: JSON.stringify( json: eligibilityAnswer(
mine 'evaluated',
? eligibilityAnswer( visit('pre_colposcopy', '1900-01-01', !first, first ? ['prior_outcome'] : []),
'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'); const reason = riskBox(page).getByText('No disponible por: Resultado CIN2+ previo al índice.');
await page.getByRole('link', { name: 'Regresar' }).click(); try {
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await open(page, firstUrl);
await page.locator(`a[href*="${ids[1]}"]`).first().click(); await expect(reason).toBeVisible();
await expect(historial(page)).toBeVisible({ timeout: 120_000 }); await page.getByRole('link', { name: 'Regresar' }).click();
await expect(eligibilityBox(page).locator('[data-state=loading]')).toBeVisible(); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await expect(eligibilityBox(page)).not.toContainText('primera'); // nothing of the previous patient await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click();
releaseSecond(); await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(eligibilityBox(page)).toContainText('segunda'); await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
await expect(eligibilityBox(page)).not.toContainText('primera'); 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 }) => { 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); await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
expect(asked).toBe(false); 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,
);
});
+53 -19
View File
@@ -10,23 +10,44 @@ interface Band {
high?: (number | null)[]; 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<Plotly.Data>[] { function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = []; const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) { if (b.low && b.high) {
lines.push({ for (const run of bandRuns(b)) {
x: [...b.x, ...[...b.x].reverse()], const x = run.map((i) => b.x[i]);
y: [...b.high, ...[...b.low].reverse()] as number[], lines.push({
fill: 'toself', x: [...x, ...[...x].reverse()],
fillcolor: `${colour}33`, y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
line: { width: 0 }, fill: 'toself',
hoverinfo: 'skip', fillcolor: `${colour}33`,
showlegend: false, line: { width: 0 },
type: 'scatter', hoverinfo: 'skip',
}); showlegend: false,
type: 'scatter',
});
}
} }
lines.push({ lines.push({
x: b.x, x: b.x,
y: b.y, y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name, name,
type: 'scatter', type: 'scatter',
mode: 'lines', 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( function points(
name: string, name: string,
x: number[], x: number[],
p: { S: number[]; low: number[]; high: number[] }, p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> { ): Partial<Plotly.Data> {
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 { return {
x, x,
y: p.S, y: p.S.map((v) => (finite(v) ? v : null)) as number[],
error_y: { ...(errors.some((error) => error !== null)
type: 'data', ? {
symmetric: false, error_y: {
array: p.high.map((h, i) => h - p.S[i]), type: 'data' as const,
arrayminus: p.S.map((v, i) => v - p.low[i]), symmetric: false,
}, array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: errors.map((error) => error?.down ?? null) as number[],
},
}
: {}),
name, name,
type: 'scatter', type: 'scatter',
mode: 'markers', mode: 'markers',
+18 -1
View File
@@ -603,11 +603,28 @@
<h4>{{ name }}</h4> <h4>{{ name }}</h4>
<p class="muted">No disponible: datos insuficientes.</p> <p class="muted">No disponible: datos insuficientes.</p>
} }
@for (u of s.insufficient; track u.name) {
<h4>{{ u.name }}</h4>
<p class="muted" data-state="insuficiente">{{ insufficientText(u) }}</p>
}
@for (name of s.missing; track name) {
<h4>{{ name }}</h4>
<p class="muted" data-state="sin-informacion">
Sin información de este escenario en el informe del modelo.
</p>
}
<app-factores [rows]="s.factors" /> <app-factores [rows]="s.factors" />
} @else if (survival.error()) { } @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else { } @else {
<p class="muted">No disponible: datos insuficientes.</p> <p class="muted" data-state="sin-informe">
@if (domain() === 'cacu') {
No disponible: no hay un informe de supervivencia para los escenarios de la
paciente.
} @else {
No disponible: datos insuficientes.
}
</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+12 -1
View File
@@ -13,6 +13,7 @@ import type {
RiskAssessment, RiskAssessment,
} from 'fhir/r4'; } from 'fhir/r4';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility'; import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
import { studies as eegStudies } from '../api/fn/eeg/studies'; import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study'; import { study as eegStudy } from '../api/fn/eeg/study';
@@ -415,6 +416,8 @@ export class Paciente {
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[], factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
scenarios: m.scenarios, scenarios: m.scenarios,
unavailable: [] as string[], unavailable: [] as string[],
insufficient: [] as Insufficient[],
missing: [] as string[],
methods: [] as string[], methods: [] as string[],
figures: mine(r['escenarios'] ?? []).map((e) => figures: mine(r['escenarios'] ?? []).map((e) =>
scenarioFigure( scenarioFigure(
@@ -435,12 +438,19 @@ export class Paciente {
'Supervivencia S(t)', '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 { return {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[], factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
scenarios: m.scenarios, scenarios: m.scenarios,
figures, figures,
// her scenarios the report draws no curve for // 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), methods: methods(figures),
}; };
}, },
@@ -563,6 +573,7 @@ export class Paciente {
...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)), ...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)),
); );
} }
protected readonly insufficientText = insufficientText;
protected readonly name = name; protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES; protected readonly levelNames = LEVEL_NAMES;
protected readonly identity = computed(() => { protected readonly identity = computed(() => {
+102
View File
@@ -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.');
});
});
+51
View File
@@ -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<string, unknown> | 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('; ')})` : ''}.`;
}