CaCu record: the NCI reference comparison section and probability curves at the published horizons

This commit is contained in:
Angel Capetillo Zavala
2026-12-01 18:24:37 -06:00
parent 8fc06038fb
commit 652fd45c29
8 changed files with 1209 additions and 46 deletions
+347
View File
@@ -625,3 +625,350 @@ test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ p
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' }),
],
}),
...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('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(2)).toContainText(`${pct} %`);
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
// 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 row = section(page).locator('tbody tr').first();
await expect(row).toContainText('Modelo de prueba');
await expect(row).toContainText('1.27 %');
await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
await expect(row.locator('td').nth(3)).toContainText('+1.00');
await expect(row.locator('td').nth(3)).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('tbody tr').first();
await expect(first.locator('td').nth(3)).toContainText('No comparable');
await expect(first.locator('td').nth(3)).toContainText(
'El desenlace del modelo no es el de la tabla (CIN3+)',
);
await expect(first.locator('td').nth(3)).toContainText(
'no publica una predicción a este horizonte',
);
await expect(first.locator('td').nth(3)).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('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(2)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(2)).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.survival', '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.recurrence', '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.survival', '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.recurrence', '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();
});