Agregar elegibilidad CaCu por escenario clínico

This commit is contained in:
Angel Capetillo Zavala
2026-12-02 18:47:09 -06:00
parent f7fdab950a
commit 370da43695
18 changed files with 1128 additions and 9 deletions
+262 -2
View File
@@ -1015,8 +1015,8 @@ test('curvas (simulado): one series per model at its published horizons, its ban
// ---- 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) => {
if (SHOTS) await page.screenshot({ path: `${SHOTS}/SIMULADO-${name}.png`, fullPage: true });
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 }),
@@ -1385,3 +1385,263 @@ test('escalas (simulado): with a survival model and compatible risk models, only
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<void>((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);
});