Integrate CaCu indicators, risk views and exports

Adapted from Angel Capetillo Zavala commits c0e4920 and 31400c7 and Edgar Hinojosas CaCu measures. Includes the existing 6F presentation and external donut labels.

Co-authored-by: edgar <edgar.hinojosas@uanl.edu.mx>
This commit is contained in:
Angel Capetillo Zavala
2026-11-30 16:02:00 -06:00
parent bc621f34f9
commit 44f3dce911
32 changed files with 3725 additions and 152 deletions
+329 -5
View File
@@ -73,7 +73,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(`21–`)).toBeVisible();
await expect(page.getByText(/Página 2 de \d+, \d+ registros/)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
@@ -198,10 +198,54 @@ function captured(domain: string) {
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
const old = items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
return domain === 'cacu' ? rearranged(old) : old;
}
/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the
* opportunity section, under its cards, and the cytology distribution is a table in the joint
* results card (its nested donut is not drawn any more). Nothing else of the old page moves. */
function rearranged(old: any[]) {
const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje');
const moved = old.splice(route, 2); // its heading and its plot
old.splice(
old.findIndex((i) => i.text === 'Indicadores clínicos'),
0,
moved[0],
moved[1],
);
// the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the
// cytology section, under another title) are not headings of this page any more
return old.filter(
(i) =>
!/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test(
i.text ?? '',
),
);
}
/** Sections this platform adds to an old page, by domain, in the order they appear. The old
* headings still have to appear, in their order; nothing else may appear (a figure's own
* `h3.figure-title` inside a measure's card is the card's, not a section). */
const ADDED: Record<string, string[]> = {
cacu: [
'Resultados de citología, VPH y biopsia',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
'VPP tras colposcopía registrada',
],
};
/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */
function oldThenAdded(actual: string[], old: string[], added: string[]) {
const extra: string[] = [];
let found = 0;
for (const heading of actual) {
if (found < old.length && heading === old[found]) found++;
else extra.push(heading);
}
return { allOldInOrder: found === old.length, extra, added };
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
@@ -215,13 +259,19 @@ for (const domain of ['cacu', 'cama', 'tea']) {
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// textContent: a heading inside a collapsed section (CaCu's original confirmation measure)
// is still a heading of the page, though the browser gives it no rendered text.
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
.locator('h2, h3:not(.figure-title)')
.evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
const seen = oldThenAdded(
headings.slice(from).map(period),
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
ADDED[domain] ?? [],
);
expect(seen.allOldInOrder).toBe(true);
expect(seen.extra).toEqual(seen.added);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
@@ -291,6 +341,280 @@ for (const domain of ['cacu', 'cama', 'tea']) {
});
}
test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({
page,
}) => {
const asked: string[] = [];
page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url()));
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// cumulative (the default), step by step with its warning and quartiles, and by ICD-10
// the route's times are in the opportunity section, after its cards and before the clinical ones
const opportunity = tab.locator('section.opportunity');
await expect(opportunity.locator('.route-card')).toBeVisible();
await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0);
expect(
await opportunity.evaluate((el) => {
const kpis = el.querySelector('.kpis')!;
const card = el.querySelector('.route-card')!;
return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING);
}),
).toBe(true);
await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible();
await tab.getByRole('radio', { name: 'Por pasos' }).click();
// by steps: independent bars from zero in a table, every step kept, and the medians not added
const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' });
await expect(steps).toBeVisible();
await expect(steps.locator('tbody tr')).toHaveCount(4);
await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible();
await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0);
await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click();
await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible();
await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click();
await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible();
await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible();
// the sections of the new measures: each one in the place of its subject
for (const measure of [
'CACU_VPH_GENOTIPO',
'CACU_VPH',
'CACU_BIOPSIA_RESULTADOS',
'CACU_VPP_COLPOSCOPIA',
])
await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible();
// a PPV says what it is and what it is not
await expect(
tab
.locator('[data-measure="CACU_VPP_COLPOSCOPIA"]')
.getByText('no un vínculo clínico confirmado'),
).toBeVisible();
// the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut
const joint = tab.locator('.results-card');
const [cyto, hpv, biopsy] = await Promise.all(
['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) =>
joint.locator(`section[data-measure="${m}"]`).boundingBox(),
),
);
expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2);
expect(cyto!.x).toBeLessThan(hpv!.x);
expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1);
expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8);
await expect(
joint.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(joint.getByText('Menor que LIEAG')).toBeVisible();
await expect(joint.getByText('LIEAG o más')).toBeVisible();
// three HPV categories are not listed, and the page says so only when it has such reports
const hpvRows = await joint
.locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th')
.allInnerTexts();
for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable'])
expect(hpvRows.join('|')).not.toContain(hidden);
// the cytology column reads one way at a time: the general table, or the clinical scenarios
const cytology = joint.locator('section[data-measure="CACU_EU7"]');
await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked();
await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0);
await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click();
await expect(cytology.locator('.js-plotly-plot')).toBeVisible();
await expect(cytology.getByRole('table')).toHaveCount(0);
await expect(
cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'),
).toBeVisible();
await expect(cytology.locator('.legend li')).toHaveCount(6);
await cytology.getByRole('radio', { name: 'Distribución general' }).click();
await expect(
cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(
joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'),
).toHaveCount(0);
await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0);
// the confirmation card: one perspective at a time, each with its own PPV and its readings
const confirmation = tab.locator('.confirmation-card');
await expect(
confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }),
).toBeVisible();
await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible();
await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked();
for (const [perspective, measure, title] of [
['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'],
['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'],
]) {
await confirmation.getByRole('radio', { name: perspective, exact: true }).click();
await expect(confirmation.locator('app-ppv-card')).toHaveCount(1);
const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`);
await expect(ppv.getByRole('heading', { name: title })).toBeVisible();
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
await expect(ppv.locator('.ppv-rows')).toHaveCount(0);
for (const mode of [
'Citología previa',
'VPH previo',
'Nivel de histología',
'Ronda de tamizaje',
]) {
await ppv.getByRole('radio', { name: mode, exact: true }).click();
await expect(ppv.getByRole('table', { name: mode })).toBeVisible();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0);
await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
// the score line and the methodological note stay in view in every reading
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
}
await ppv.getByRole('radio', { name: 'Total' }).click();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
}
// the biopsy requests are one more reading of the biopsy perspective, with their own heading
const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]');
await expect(
biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }),
).toBeVisible();
await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }),
).toBeVisible();
await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount(
0,
);
await expect(biopsyPpv.locator('.measure-score')).toContainText(
'solicitudes registradas (no pacientes)',
);
await expect(
biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'),
).toBeVisible();
await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible();
await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible();
await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos');
await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0);
await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }),
).toBeVisible();
// the original confirmation measure is not shown on this tab any more
await expect(confirmation.locator('details')).toHaveCount(0);
await expect(tab.getByText('medida original')).toHaveCount(0);
await expect(tab.getByText('Denominador: ')).toHaveCount(0);
// the tabs are short and the full explanation is in the tab's content
await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = confirmation.locator('app-ppv-card');
await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click();
await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas');
await expect(colposcopy.getByRole('radio')).toHaveCount(5);
const tops = await colposcopy
.locator('mat-button-toggle')
.evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size);
expect(tops).toBe(1); // one line on desktop
// the patients by HPV result: the whole as a donut, then one breakdown at a time
const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible();
await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
for (const mode of [
'Por grupo de edad',
'Por estatus de seguimiento',
'Por genotipo',
'Por tamizaje inicial o subsecuente',
]) {
await vph.getByRole('radio', { name: mode, exact: true }).click();
await expect(vph.getByRole('table', { name: mode })).toBeVisible();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(0);
await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
}
await vph.getByRole('radio', { name: 'Total' }).click();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
// the two HPV measures are told apart: reports against patients
await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText(
'Pacientes evaluadas por resultado de VPH',
);
await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText(
'Cuenta reportes, no pacientes',
);
expect(asked).toEqual([]);
});
test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const rows = page.locator('table.worklist tbody tr:not(.stage-panel)');
await expect(rows.first().locator('a')).toBeVisible();
const total = async () =>
Number(
/(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0,
);
// her age at the cut-off, and the stages: a compact line with a chevron that opens the panel
await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible();
await expect(rows.first().locator('app-stages .node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click();
const panel = page.locator('tr.stage-panel');
await expect(panel).toContainText('Toma de muestra');
await expect(panel).toContainText('Desde anterior');
await expect(panel.locator('.node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click();
await expect(panel).toHaveCount(0);
// the age filters apply before the page is cut; the name search of Rebuild is still there
const all = await total();
await page.getByLabel('Edad mínima').fill('200');
await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible();
await page.getByLabel('Edad mínima').fill('45');
await expect(async () => expect(await total()).toBeLessThan(all)).toPass();
await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible();
await page.getByRole('button', { name: 'Limpiar edades' }).click();
await expect(async () => expect(await total()).toBe(all)).toPass();
// the whole query, as the two files
const [pdf] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar PDF' }).click(),
]);
expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf');
expect(
readFileSync((await pdf.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
const [xlsx] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(),
]);
expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx');
expect(
readFileSync((await xlsx.path())!)
.subarray(0, 2)
.toString(),
).toBe('PK');
// her record: age, the detailed stages, the scales, and the file
await rows.first().locator('a').first().click();
await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:');
await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5);
await expect(page.getByText('Desde toma:').first()).toBeVisible();
await expect(page.getByText('Riesgo inmediato')).toBeVisible();
await expect(page.getByText('Riesgo a 5 años')).toBeVisible();
const [ficha] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar ficha PDF' }).click(),
]);
expect(
readFileSync((await ficha.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
expect(problems).toEqual([]);
});
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {