Compare commits

...

33 Commits

Author SHA1 Message Date
edgar 24415b79b6 Quitar la barra de Plotly en las curvas de la ficha 2026-12-03 00:24:50 -06:00
edgar b43c89befd Decir una sola vez el supuesto de la referencia NCI 2026-12-03 00:18:28 -06:00
edgar 9c17a383d1 Usar barras comunes en confirmación y renombrar la serie de ingreso del NCI 2026-12-03 00:06:32 -06:00
edgar 8e16de33b7 Mostrar tabla de valores de supervivencia 2026-12-02 23:44:28 -06:00
edgar 5d660b7043 Mostrar confirmación con intervalo en barra y ajustar etiquetas de la ficha 2026-12-02 23:43:18 -06:00
edgar a3a100450b Mostrar supervivencia con su curva de combinación y métodos por estimación 2026-12-02 23:20:51 -06:00
edgar a92515eb4d Mostrar factores usados en cada estimación 2026-12-02 23:13:59 -06:00
edgar 5f92c49ed4 Mostrar escalas de supervivencia publicadas 2026-12-02 23:00:06 -06:00
edgar a22ce12067 Mostrar solo curvas de probabilidad disponibles 2026-12-02 22:53:44 -06:00
edgar a19874438b Ajustar resumen y ocultar series no disponibles 2026-12-02 22:50:30 -06:00
edgar c08a0b8874 Ajustar pestañas y etiquetas de días 2026-12-02 21:54:54 -06:00
edgar 5201340a13 Aclarar etiquetas de días en indicadores CaCu 2026-12-02 21:50:01 -06:00
edgar cca9517b7c Conservar la exclusión por histerectomía cuando la API no la reporta 2026-12-02 20:26:14 -06:00
edgar 3693991772 Renombrar tasas de confirmación histopatológica 2026-12-02 20:23:32 -06:00
edgar e49dde10e7 Distinguir diagnósticos en la ruta de tamizaje 2026-12-02 20:19:36 -06:00
edgar 2dec5af826 Distinguir tiempos de diagnóstico en indicadores 2026-12-02 20:19:36 -06:00
edgar 0316966374 Ajustar la prueba de las escalas al título sin versión 2026-12-02 19:43:55 -06:00
edgar 3d72c153c5 Ficha: quitar la nota de las etapas de la citología 2026-12-02 19:42:55 -06:00
edgar 422b408e37 Ficha: quitar la procedencia del formulario de citología 2026-12-02 19:42:53 -06:00
edgar 211f02edad Ficha: mostrar el VPH como estudio aparte 2026-12-02 19:42:51 -06:00
edgar 32b879edd2 Ficha: mostrar la tabla de modelos como desplegable 2026-12-02 19:42:48 -06:00
edgar 9726d6faa3 Ficha: quitar el texto de las curvas de probabilidad 2026-12-02 19:42:46 -06:00
edgar bafd6760d4 Ficha: llevar la comparación y sus filtros a las curvas de probabilidad 2026-12-02 19:42:43 -06:00
edgar 0666ce3077 Ficha: no mostrar la comparación de riesgos de referencia 2026-12-02 19:42:41 -06:00
edgar d2eada9385 Ficha: titular cada riesgo por su desenlace y llevar el escenario al pie 2026-12-02 19:42:38 -06:00
edgar 0d458818b5 Ficha: dibujar el intervalo sobre la escala y llevar la fecha índice al pie 2026-12-02 19:42:36 -06:00
edgar 2970ce16b0 Ficha: quitar el título Riesgos y recomendaciones 2026-12-02 19:42:33 -06:00
Angel Capetillo Zavala a43cf4b51b Distinguir ausencias e insuficiencia en supervivencia CaCu 2026-12-02 19:26:50 -06:00
edgar a4cc80fbe2 Mostrar la elegibilidad CaCu solo cuando la paciente no es elegible 2026-12-02 19:04:00 -06:00
Angel Capetillo Zavala 370da43695 Agregar elegibilidad CaCu por escenario clínico 2026-12-02 18:47:09 -06:00
edgar f7fdab950a Comparar series de riesgo seleccionables en la ficha CaCu 2026-12-02 18:24:33 -06:00
edgar 1260e0ff2a Mostrar métodos y escenarios sin curva en la supervivencia de la ficha 2026-12-02 18:14:19 -06:00
Angel Capetillo Zavala 09e5f4dd34 CaCu record: grouped NCI comparison, Spanish outcome names, survival texts and risk-only scales
The NCI comparison shows the reference once per horizon and one block per model, saying the
reasons that every incompatible comparison shares only once. Outcome names are translated for
display only (the API identifiers stay), and the reference outcome is read from the answer.
The CaCu survival card is titled as survival and states that its curves estimate the clinical
scenario's group, not an individual. Survival and recurrence estimates no longer feed the risk
scales, curves, probability table or PDF.
2026-12-02 17:48:03 -06:00
44 changed files with 3136 additions and 297 deletions
+7 -7
View File
@@ -14,8 +14,8 @@ const TITLES = {
cytology: 'Distribución de resultados citológicos', cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo', genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical', biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Valor predictivo positivo de la colposcopía', colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia', ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
}; };
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({ test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
@@ -30,17 +30,17 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([ expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad', 'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje', 'Días de la ruta del tamizaje',
'Indicadores clínicos', 'Indicadores clínicos',
'Resultados de citología, VPH y biopsia', 'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos', 'Distribución de resultados citológicos',
'Resultados de VPH por genotipo', 'Resultados de VPH por genotipo',
'Resultados de biopsia cervical', 'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica', 'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
]); ]);
const route = tab.locator('app-readings').first(); const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) { for (const mode of ['Por pasos', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click(); await route.getByRole('radio', { name: mode }).click();
await expect( await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')), route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
@@ -105,14 +105,14 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.getByRole('radio', ROUND) .getByRole('radio', ROUND)
.click(); .click();
await expect( await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }), tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible(); ).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click(); await tab.getByRole('radio', { name: 'Solicitudes' }).click();
}); });
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => { test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const list = page.locator('table.worklist tbody tr'); const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5); await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click(); await list.first().getByRole('button', { name: 'Detalle' }).click();
+745 -31
View File
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
/** The record of the first patient of the risk list, as an address. */ /** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> { async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const link = page.locator('table.worklist tbody tr a').first(); const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 }); await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!; const url = (await link.getAttribute('href'))!;
@@ -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();
@@ -321,11 +322,11 @@ test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tel
}) => { }) => {
const { url } = await firstRecord(page); const { url } = await firstRecord(page);
await withRisks(page, [ await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [ risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [
[0, 0], [0, 0],
[5, 0.5, 0.4, 0.6], [5, 0.5, 0.4, 0.6],
]), ]),
risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [ risk('b', 'Recurrencia v2', 'cacu.cancer_pim', '2026-03-01', [
[0, 0.02, 0.01, 0.03], [0, 0.02, 0.01, 0.03],
[5, 0.98, 0.95, 1], [5, 0.98, 0.95, 1],
]), ]),
@@ -373,7 +374,7 @@ test('ficha (simulado): the scale is drawn in four equal segments with the numer
}) => { }) => {
const { url } = await firstRecord(page); const { url } = await firstRecord(page);
await withRisks(page, [ await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]), risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
]); ]);
await open(page, url); await open(page, url);
const box = scale(page, FIVE); const box = scale(page, FIVE);
@@ -415,7 +416,7 @@ for (const width of [1440, 480]) {
link: 'recorded', link: 'recorded',
}); });
await withRisks(page, [ await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [ risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [
[0, 0], [0, 0],
[5, 0.98, 0.95, 1], [5, 0.98, 0.95, 1],
]), ]),
@@ -703,6 +704,7 @@ function fixture(
part: [ part: [
part('id', { valueString: 'fixture-table' }), part('id', { valueString: 'fixture-table' }),
part('file', { valueString: 'fixture.xlsx' }), part('file', { valueString: 'fixture.xlsx' }),
part('outcome', { valueCode: 'CIN3+' }),
], ],
}), }),
...more, ...more,
@@ -745,7 +747,7 @@ test('referencia NCI: a resolved cytology shows its reference with scenario, sou
await expect(box).toContainText('Tamizaje'); await expect(box).toContainText('Tamizaje');
await expect(box).toContainText('CIN3 o más grave (CIN3+)'); await expect(box).toContainText('CIN3 o más grave (CIN3+)');
await expect(box).toContainText('Master_NCI_Risk_Table.xlsx'); await expect(box).toContainText('Master_NCI_Risk_Table.xlsx');
const rows = box.locator('tbody tr'); const rows = box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr');
await expect(rows).toHaveCount(2); await expect(rows).toHaveCount(2);
await expect(rows.first()).toContainText('Inmediato (al índice)'); await expect(rows.first()).toContainText('Inmediato (al índice)');
await expect(rows.nth(1)).toContainText('5 años'); await expect(rows.nth(1)).toContainText('5 años');
@@ -756,10 +758,13 @@ test('referencia NCI: a resolved cytology shows its reference with scenario, sou
(h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2), (h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2),
); );
for (const [i, pct] of expected.entries()) for (const [i, pct] of expected.entries())
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`); await expect(rows.nth(i).locator('td').nth(1)).toContainText(`${pct} %`);
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible'); // no model evaluated her: said once, not on every horizon
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable'); await expect(box.locator('.nomodel')).toContainText('No disponible');
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional'); await expect(box.getByText('Ningún modelo institucional ha evaluado a la paciente.')).toHaveCount(
1,
);
await expect(box.locator('[data-model]')).toHaveCount(0);
// the antecedents used are collapsed // the antecedents used are collapsed
const used = box.locator('details.used'); const used = box.locator('details.used');
expect(await used.getAttribute('open')).toBeNull(); expect(await used.getAttribute('open')).toBeNull();
@@ -832,13 +837,17 @@ test('referencia NCI (simulado): a comparison that is valid shows the difference
]), ]),
); );
await open(page, url); await open(page, url);
const row = section(page).locator('tbody tr').first(); const block = section(page).locator('[data-model]');
await expect(row).toContainText('Modelo de prueba'); await expect(block.locator('h5')).toContainText('Modelo de prueba');
await expect(block.locator('h5')).toContainText('CIN3 o más grave (CIN3+)');
const row = block.locator('tbody tr').first();
await expect(row).toContainText('1.27 %'); await expect(row).toContainText('1.27 %');
await expect(row).toContainText('IC 95 %: 0.50–2.00 %'); await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
await expect(row.locator('td').nth(2)).toContainText('0.27 %'); await expect(
await expect(row.locator('td').nth(3)).toContainText('+1.00'); section(page).locator('table').first().locator('tbody tr').first().locator('td').nth(1),
await expect(row.locator('td').nth(3)).not.toContainText('No comparable'); ).toContainText('0.27 %');
await expect(row.locator('td').nth(2)).toContainText('+1.00');
await expect(row.locator('td').nth(2)).not.toContainText('No comparable');
}); });
test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({ test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({
@@ -863,15 +872,15 @@ test('referencia NCI (simulado): another outcome or horizon is "No comparable" w
]), ]),
); );
await open(page, url); await open(page, url);
const first = section(page).locator('tbody tr').first(); const first = section(page).locator('[data-model] tbody tr').first();
await expect(first.locator('td').nth(3)).toContainText('No comparable'); await expect(first.locator('td').nth(2)).toContainText('No comparable');
await expect(first.locator('td').nth(3)).toContainText( await expect(first.locator('td').nth(2)).toContainText(
'El desenlace del modelo no es el de la tabla (CIN3+)', 'El desenlace del modelo no es el de la tabla (CIN3+)',
); );
await expect(first.locator('td').nth(3)).toContainText( await expect(first.locator('td').nth(2)).toContainText(
'no publica una predicción a este horizonte', '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(2)).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 await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted
}); });
@@ -881,12 +890,12 @@ test('referencia NCI (simulado): a year-one reference is a year, never the immed
const { url } = await firstRecord(page); const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }])); await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
await open(page, url); await open(page, url);
const rows = section(page).locator('tbody tr'); const rows = section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr');
await expect(rows.first()).toContainText('1 año'); await expect(rows.first()).toContainText('1 año');
await expect(section(page)).not.toContainText('Inmediato'); 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(1)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00'); await expect(rows.nth(1).locator('td').nth(1)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %'); await expect(rows.first().locator('td').nth(1)).toContainText('1.36 %');
}); });
for (const width of [1440, 480]) { for (const width of [1440, 480]) {
@@ -929,12 +938,12 @@ for (const width of [1440, 480]) {
), ),
); );
await withRisks(page, [ await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [ risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [
[1, 0.08, 0.05, 0.12], [1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28], [3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44], [5, 0.34, 0.26, 0.44],
]), ]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [ risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [
[1, 0.002, 0.001, 0.005], [1, 0.002, 0.001, 0.005],
[3, 0.008], [3, 0.008],
[5, 0.015, 0.008, 0.028], [5, 0.015, 0.008, 0.028],
@@ -956,12 +965,12 @@ test('curvas (simulado): one series per model at its published horizons, its ban
const { url } = await firstRecord(page); const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }])); await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
await withRisks(page, [ await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [ risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [
[1, 0.08, 0.05, 0.12], [1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28], [3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44], [5, 0.34, 0.26, 0.44],
]), ]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [ risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [
[1, 0.002, 0.001, 0.005], [1, 0.002, 0.001, 0.005],
[3, 0.008], [3, 0.008],
[5, 0.015, 0.008, 0.028], [5, 0.015, 0.008, 0.028],
@@ -1003,3 +1012,708 @@ test('curvas (simulado): one series per model at its published horizons, its ban
).not.toContain('0.27'); ).not.toContain('0.27');
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible(); await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
}); });
// ---- 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, 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 }),
...(low === undefined ? [] : [part('institutional-low', { valueDecimal: low })]),
...(high === undefined ? [] : [part('institutional-high', { valueDecimal: high })]),
...(diff === undefined ? [] : [part('difference-pp', { valueDecimal: diff })]),
];
const model = (
code: string,
title: string,
outcome: string,
status: string,
reasons: string[],
extra: object[] = [],
) =>
part('comparison', {
part: [
part('model', { valueCode: code }),
part('title', { valueString: title }),
part('outcome', { valueString: outcome }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const SHARED = ['index_date_differs', 'population_not_verified'];
for (const width of [1440, 480]) {
test(`referencia NCI (simulado) at ${width} px: several models, outcomes and horizons are grouped without losing any`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await answerWith(
page,
fixture(
[
{
years: 0,
reference: 0.0001,
comparison: [
model(
'cacu.cin2_pim',
'Riesgo LIEAG+',
'CIN2+',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.05, 0.03, 0.08),
),
model(
'cacu.cancer_pim',
'Riesgo de cáncer',
'cancer',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.002),
),
model(
'cacu.cin2_logistic',
'Riesgo LIEAG+ a un año',
'CIN2+ within one year',
'not_comparable',
['horizon_not_published_by_model', 'outcome_differs', ...SHARED],
),
],
},
{
years: 1,
comparison: [
model(
'cacu.cin2_logistic',
'Riesgo LIEAG+ a un año',
'CIN2+ within one year',
'not_comparable',
['no_reference', 'outcome_differs', ...SHARED],
institutional(0.04),
),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
model(
'cacu.cin2_pim',
'Riesgo LIEAG+',
'CIN2+',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.12, 0.08, 0.17),
),
model(
'cacu.cancer_pim',
'Riesgo de cáncer',
'cancer',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.011, 0.006, 0.02),
),
model(
'cacu.cin3_fixture',
'Modelo CIN3+ de prueba',
'CIN3+',
'comparable',
[],
institutional(0.0127, 0.005, 0.02, 1),
),
],
},
],
[part('assumption', { valueString: 'un supuesto sin verificar' })],
),
);
await open(page, url);
const box = section(page);
// the outcome of the reference comes from the answer; the models' are translated for display only
await expect(box).toContainText('Desenlace de la referencia');
const blocks = box.locator('[data-model]');
await expect(blocks).toHaveCount(4);
await expect(blocks.locator('h5 [data-outcome="cancer"]')).toHaveText('Cáncer');
await expect(blocks.locator('h5 [data-outcome="CIN2+ within one year"]')).toHaveText(
'CIN2+ en un año',
);
await expect(blocks.locator('h5 [data-outcome="CIN2+"]')).toContainText('CIN2');
// the reference is one table; each model keeps its own horizons, values and intervals
await expect(
box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'),
).toHaveCount(3);
const pim = box.locator('[data-model="cacu.cin2_pim"] tbody tr');
await expect(pim).toHaveCount(2);
await expect(pim.first()).toContainText('5.00 %');
await expect(pim.first()).toContainText('IC 95 %: 3.00–8.00 %');
await expect(pim.nth(1)).toContainText('12.00 %');
// an absent interval stays absent; a missing value says so
await expect(box.locator('[data-model="cacu.cancer_pim"] tbody tr').first()).not.toContainText(
'IC 95 %',
);
await expect(box.locator('[data-model="cacu.cin2_logistic"] tbody tr').first()).toContainText(
'No disponible',
);
// reasons every incompatible comparison gives are said once, not on each row
const common = box.locator('ul[aria-label="Motivos comunes"] li');
await expect(common).toHaveCount(3); // outcome_differs is in every incompatible row too
await expect(
box.getByText('La fecha índice del modelo no es la de la citología evaluada.'),
).toHaveCount(1);
// a difference only on the valid comparison
const valid = box.locator('[data-model="cacu.cin3_fixture"] tbody tr');
await expect(valid.locator('td').nth(2)).toContainText('+1.00');
await expect(
box.locator('[data-model="cacu.cin2_pim"] tbody td:nth-child(3)').first(),
).not.toContainText(/[+-]\d/);
// the reasons of one horizon only stay on that row
await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText(
'no publica una predicción a este horizonte',
);
await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText(
'no dan un riesgo a este horizonte',
);
await box.locator('details.used summary').click();
await page.waitForTimeout(600);
expect(await layoutProblems(page)).toEqual([]);
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
await shot(page, `referencia-nci-agrupada-${width}`);
});
}
test('referencia NCI (simulado): with no institutional model it says so once; the reference stays', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 0,
reference: 0.0001,
comparison: [
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
},
]),
);
await open(page, url);
await expect(
section(page).getByText('Ningún modelo institucional ha evaluado a la paciente.'),
).toHaveCount(1);
await expect(
section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'),
).toHaveCount(2);
await shot(page, 'referencia-nci-sin-modelos');
});
const scenarioReport = (name: string, n: number, deaths: number) => ({
escenario: name,
n,
fallecidos: deaths,
horizons_months: [12, 36, 60],
km: {
months: [0, 12, 36, 60],
S: [1, 0.92, 0.8, 0.7],
low: [1, 0.85, 0.7, 0.55],
high: [1, 0.97, 0.9, 0.82],
},
weibull: { t: [0, 12, 36, 60], S: [1, 0.93, 0.81, 0.69] },
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[] = [],
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: scenarios.map((valueString) => ({ url: EXT + 'escenario-clinico', valueString })),
};
await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: [assessed, ...others].map((resource) => ({ resource })),
}),
}),
);
await page.route(
`**/api/models/${domain}/survival/versions/*/reports/interpretability`,
(route) =>
route.fulfill({
contentType: 'application/json',
body: JSON.stringify(
report ?? {
escenarios: [
scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6),
scenarioReport('VPH positivo', 30, 9),
],
factores_escenarios: [],
},
),
}),
);
}
for (const width of [1440, 480]) {
test(`supervivencia (simulado) at ${width} px: CaCu says the curves are the scenario group's, not individual predictions`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu');
await open(page, url);
const card = page.locator('[data-section=supervivencia]');
await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico');
await expect(card).not.toContainText('Riesgo de muerte');
await expect(card.locator('[data-note=grupo]')).toContainText(
'estimaciones del grupo de pacientes del escenario clínico',
);
await expect(card.locator('[data-note=grupo]')).toContainText(
'no son predicciones individuales',
);
await expect(card.locator('h4')).toHaveText([
'Edad al diagnóstico · 45-54 años (n = 12, fallecidos = 6)',
'VPH positivo (n = 30, fallecidos = 9)',
]);
// the curves are the report's, untouched
const plot = await card
.locator('.js-plotly-plot')
.first()
.evaluate((e: any) => ({
names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name),
y: e.layout.yaxis.title.text,
x: e.layout.xaxis.title.text,
}));
expect(plot.y).toBe('Supervivencia S(t)');
expect(plot.x).toBe('Meses desde el diagnóstico');
expect(plot.names).toContain('Kaplan-Meier (IC 95 % Greenwood)');
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
await shot(page, `supervivencia-cacu-${width}`);
});
}
test('supervivencia (simulado): CaMa keeps its own title and no group note', async ({ page }) => {
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
const id = patients.entry[0].resource.id;
await withSurvival(page, 'cama');
await page.goto(`/indicadores/cama/pacientes/${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.locator('[data-note=grupo]')).toHaveCount(0);
await shot(page, 'supervivencia-cama-sin-cambios');
});
const SCALES = [IMMEDIATE, 'Riesgo a 5 años'];
test('escalas (simulado): a survival estimate alone never feeds the risk scales or curves; they say "No disponible"', async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu'); // only cacu.survival: S(5 years) = 70 %
await open(page, url);
for (const label of SCALES) {
await expect(scale(page, label)).toContainText('No disponible');
await expect(scale(page, label).locator('.risk-marker')).toHaveCount(0);
}
await expect(page.locator('.risk-value')).toHaveCount(0); // no 70 % on a risk scale
await expect(page.locator('details.curves')).toHaveCount(0);
await expect(page.locator('table.plain', { hasText: 'Probabilidad' })).toHaveCount(0);
// the survival is still in its own analysis, as the group's estimate
const card = page.locator('[data-section=supervivencia]');
await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico');
await expect(card.locator('h4').first()).toContainText('n = 12');
await shot(page, 'escalas-solo-supervivencia-1440');
});
test('escalas (simulado): with a survival model and compatible risk models, only the risk models feed the scales and curves', async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu', [
risk('r1', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [
[0, 0.03, 0.02, 0.05],
[5, 0.12, 0.08, 0.17],
]),
risk('r2', 'Riesgo de cáncer v2', 'cacu.cancer_pim', '2026-06-01', [[5, 0.011, 0.006, 0.02]]),
]);
await open(page, url);
const values = await page.locator('.risk-value').allInnerTexts();
expect(values.map((v) => v.trim())).toEqual(['3.0 %', '12.0 %', '1.1 %']); // none is the 70 % survival
await expect(scale(page, 'Riesgo a 5 años', 0)).toContainText('IC 95 %: 8.0–17.0');
await expect(scale(page, IMMEDIATE, 1)).toContainText('No disponible'); // the cancer model has no immediate risk
await expect(page.locator('app-risk-scales h3')).toHaveText([
'Riesgo LIEAG+ v3 · fecha índice 2026-06-01',
'Riesgo de cáncer v2 · fecha índice 2026-06-01',
]);
const curves = page.locator('details.curves');
await expect(curves).not.toContainText('Supervivencia');
expect(
JSON.stringify(await curves.locator('.js-plotly-plot').evaluate((e: any) => e.data)),
).not.toContain('70');
const table = page.locator('table.plain', { hasText: 'Probabilidad' });
await expect(table).not.toContainText('Supervivencia');
// the survival analysis and the NCI reference stay
await expect(page.locator('[data-section=supervivencia]')).toBeVisible();
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
await shot(page, 'escalas-supervivencia-y-riesgo-1440');
});
// ---- 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 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 }),
part('eligible', { valueBoolean: eligible }),
...criteria.map((code) =>
part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code } }),
),
],
});
const eligibilityAnswer = (status: string, ...candidates: object[]) =>
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) }),
);
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',
);
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(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('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: the risk section shows all reasons from the selected visit', async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url, sample } = await firstRecord(page);
const day = sample.slice(0, 10);
await withFollowUp(page, 'pre_colposcopy');
await eligibilityIs(
page,
eligibilityAnswer(
'evaluated',
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 = 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('app-risk-scales')).toHaveCount(0);
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
expect(await layoutProblems(page)).toEqual([]);
});
}
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,
eligibilityAnswer(
'evaluated',
visit('pre_colposcopy', plus(day, 1), true),
visit('surveillance', day, false, ['prior_outcome']),
),
);
await open(page, url);
await expect(riskBox(page).getByRole('status')).toHaveText(
'No disponible por: Resultado CIN2+ previo al índice.',
);
});
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 firstRecord(page);
const links = page.locator('table.worklist tbody tr a');
const records = await links.evaluateAll((els) => {
const unique = new Map<string, string>();
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<void>((resolve) => (release = resolve));
await page.route(ELIGIBILITY, async (route) => {
const first = new URL(route.request().url()).pathname.endsWith(`/${firstId}/$eligibility`);
if (!first) await gate;
await route.fulfill({
contentType: 'application/fhir+json',
json: eligibilityAnswer(
'evaluated',
visit('pre_colposcopy', '1900-01-01', !first, first ? ['prior_outcome'] : []),
),
});
});
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: 'Seguimiento' }).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 }) => {
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);
});
// ---- 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,
);
});
+16 -6
View File
@@ -58,14 +58,14 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
); );
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Histórico' }).click();
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9); await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const bundle = await (await list).json(); const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource; const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10); const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
@@ -84,8 +84,8 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
).not.toContainText('Sin estudios'); ).not.toContainText('Sin estudios');
await page.goto('/indicadores/cama'); await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr'); const camaRows = page.locator('table.worklist tbody tr');
@@ -205,6 +205,16 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>'); const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Seguimiento', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Histórico', exact: true })).toHaveCount(1);
const labels = await page.getByRole('tab').allTextContents();
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
});
}
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one. // CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) { for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
@@ -242,7 +252,7 @@ for (const domain of ['cama', 'tea']) {
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad'); const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual( expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
); );
// Each figure drawn is one of the old kinds (a figure with no data in the period is named). // Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab const drawn = await tab
@@ -268,7 +278,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
['h2', 'h3', 'plot'].includes(i.kind), ['h2', 'h3', 'plot'].includes(i.kind),
); );
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Histórico' }).click();
const tab = page.locator('app-tab-trazabilidad'); const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
+285
View File
@@ -292,6 +292,7 @@
"default": "identity", "default": "identity",
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -443,6 +444,7 @@
"description": "Qu\u00e9 estudio se saca del documento.", "description": "Qu\u00e9 estudio se saca del documento.",
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -465,6 +467,10 @@
"label": "Identidad de la persona", "label": "Identidad de la persona",
"value": "identity" "value": "identity"
}, },
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{ {
"label": "Citolog\u00eda cervical", "label": "Citolog\u00eda cervical",
"value": "cervical_cytology" "value": "cervical_cytology"
@@ -641,6 +647,7 @@
"entity": { "entity": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -663,6 +670,10 @@
"label": "Identidad de la persona", "label": "Identidad de la persona",
"value": "identity" "value": "identity"
}, },
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{ {
"label": "Citolog\u00eda cervical", "label": "Citolog\u00eda cervical",
"value": "cervical_cytology" "value": "cervical_cytology"
@@ -1530,6 +1541,7 @@
"entity": { "entity": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -2117,6 +2129,7 @@
"description": "En qu\u00e9 estudio de la plataforma se guarda.", "description": "En qu\u00e9 estudio de la plataforma se guarda.",
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -2139,6 +2152,10 @@
"label": "Identidad de la persona", "label": "Identidad de la persona",
"value": "identity" "value": "identity"
}, },
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{ {
"label": "Citolog\u00eda cervical", "label": "Citolog\u00eda cervical",
"value": "cervical_cytology" "value": "cervical_cytology"
@@ -4056,6 +4073,7 @@
"schema": { "schema": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -4164,6 +4182,7 @@
"schema": { "schema": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -5907,6 +5926,272 @@
] ]
} }
}, },
"/{domain}/fhir/Patient/{id}/$eligibility": {
"get": {
"description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.",
"operationId": "cacu_eligibility",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Limit the report to one CaCu scenario",
"in": "query",
"name": "scenario",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Limit the report to one CaCu scenario",
"title": "Scenario"
}
},
{
"description": "Only index dates up to this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only index dates up to this day",
"title": "Cutoff"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Eligibility",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$reference-risk": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.",
"operationId": "reference_risk",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Reference Risk",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$risk-series": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.",
"operationId": "cacu_risk_series",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Risk Series",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Procedure": { "/{domain}/fhir/Procedure": {
"get": { "get": {
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).", "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuEligibility$Params {
domain: Domain;
id: string;
/**
* Limit the report to one CaCu scenario
*/
scenario?: (string | null);
/**
* Only index dates up to this day
*/
cutoff?: (string | null);
}
export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('scenario', params.scenario, {});
rb.query('cutoff', params.cutoff, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuRiskSeries$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ReferenceRisk$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params { export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params { export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+6
View File
@@ -113,6 +113,12 @@ export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/sea
export { searchPatient as searchPatient } from './fn/fhir/search-patient'; export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient'; export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
export { readPatient as readPatient } from './fn/fhir/read-patient'; export { readPatient as readPatient } from './fn/fhir/read-patient';
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
export type { ReferenceRisk$Params as ReferenceRisk$Params } from './fn/fhir/reference-risk';
export { referenceRisk as referenceRisk } from './fn/fhir/reference-risk';
export type { CacuRiskSeries$Params as CacuRiskSeries$Params } from './fn/fhir/cacu-risk-series';
export { cacuRiskSeries as cacuRiskSeries } from './fn/fhir/cacu-risk-series';
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure'; export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure'; export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment'; export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable). * field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/ */
export interface Correction { export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string; field: string;
record: string; record: string;
value: string; value: string;
+1 -1
View File
@@ -25,7 +25,7 @@ export interface Extract {
/** /**
* Qué estudio se saca del documento. * Qué estudio se saca del documento.
*/ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
+1 -1
View File
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir { export interface Fhir {
column?: string; column?: string;
concept_map?: (string | null); concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'fhir'; kind?: 'fhir';
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection { export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string; reason: string;
record: string; record: string;
} }
+1 -1
View File
@@ -12,7 +12,7 @@ export interface Target {
/** /**
* En qué estudio de la plataforma se guarda. * En qué estudio de la plataforma se guarda.
*/ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'target'; kind?: 'target';
+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',
+21
View File
@@ -54,6 +54,8 @@ export type Mode = {
hidden?: Hidden; hidden?: Hidden;
} }
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint } | { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
| { kind: 'ratio'; measure: string; colors?: Colors }
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint } | { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */ /** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] } | { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
@@ -204,6 +206,25 @@ const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */ /** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined { export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) { switch (mode.kind) {
case 'ratio': {
const r = of(mode.measure);
const n = r?.populations['numerator'] ?? 0;
const total = r?.populations['denominator'] ?? 0;
if (r?.score === undefined || !total) return undefined;
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return {
head: ['n/N', '%', 'IC 95 %'],
rows: [
{
label: 'Total',
color: mode.colors?.['numerator'],
width: 100 * r.score,
marks: ends.map((v) => 100 * v),
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
},
],
};
}
case 'counts': { case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {}; const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0); const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
+5 -5
View File
@@ -36,28 +36,28 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else { } @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms"> <mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'"> <mat-tab label="Resumen">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" /> <app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab> </mat-tab>
<mat-tab label="Trazabilidad"> <mat-tab label="Histórico">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" /> <app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="Seguimiento">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" /> <app-tab-riesgos [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'tea') { } @else if (domain() === 'tea') {
<mat-tab label="Análisis de Riesgo"> <mat-tab label="Seguimiento">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos-tea [domain]="domain()" /> <app-tab-riesgos-tea [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'cama') { } @else if (domain() === 'cama') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="Seguimiento">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" /> <app-tab-seguimiento [domain]="domain()" />
</ng-template> </ng-template>
+5 -4
View File
@@ -13,13 +13,14 @@ export const LAYOUTS: Record<string, Layout> = {
'CACU_EU7', 'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE', 'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO', 'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
'CACU_DIAS_TOMA_TRATAMIENTO', 'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
], ],
route: [ route: [
{ {
label: 'Resultado de citología', label: 'Días de toma de citología a resultado',
step: 'Toma a resultado de citología', step: 'Días de toma de citología a resultado',
fromSample: 'CACU_EU_TIEMPO_REPORTE', fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE', fromStep: 'CACU_EU_TIEMPO_REPORTE',
}, },
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA', fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
}, },
{ {
label: 'Diagnóstico', label: 'Diagnóstico tras biopsia',
step: 'Del resultado de biopsia al diagnóstico', step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO', fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO', fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
}, },
], ],
+37 -18
View File
@@ -116,9 +116,10 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
kind: 'readings', kind: 'readings',
title, title,
headline: measure, headline: measure,
footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`, note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [ modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT }, { kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT },
{ {
kind: 'shares', kind: 'shares',
label: 'Citología previa', label: 'Citología previa',
@@ -174,29 +175,29 @@ export const CACU: Page = {
}, },
{ {
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado', title: 'Días de toma de citología a resultado',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
], ],
opportunity: [ opportunity: [
{ {
kind: 'readings', kind: 'readings',
title: 'Tiempos de la ruta del tamizaje', title: 'Días de la ruta del tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.', note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [ modes: [
{ {
@@ -204,10 +205,13 @@ export const CACU: Page = {
tint: TINT, tint: TINT,
label: 'Acumulado desde la toma', label: 'Acumulado desde la toma',
steps: [ steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, { label: 'Días de toma de citología a resultado', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' }, { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' }, { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }, {
label: 'Diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
], ],
}, },
{ {
@@ -216,19 +220,31 @@ export const CACU: Page = {
label: 'Por pasos', label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.', caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [ steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, {
label: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
},
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' }, { label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' }, { label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' }, { label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
], ],
}, },
{ {
kind: 'days-by', kind: 'days',
tint: TINT, tint: TINT,
label: 'Por CIE-10', label: 'Primer diagnóstico',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.', steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10', },
stratum: 'diagnosis_code', {
kind: 'days',
tint: TINT,
label: 'Diagnóstico tras biopsia',
steps: [
{
label: 'Toma a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
}, },
], ],
}, },
@@ -263,7 +279,10 @@ export const CACU: Page = {
catalog: HPV, catalog: HPV,
hidden: HPV_HIDDEN, hidden: HPV_HIDDEN,
}, },
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', { ofAll: true, hidden: HPV_HIDDEN }), ...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
ofAll: true,
hidden: HPV_HIDDEN,
}),
], ],
}, },
{ {
@@ -289,7 +308,7 @@ export const CACU: Page = {
label: 'Colposcopía', label: 'Colposcopía',
section: ppv( section: ppv(
'CACU_VPP_COLPOSCOPIA', 'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.', 'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
), ),
}, },
@@ -297,7 +316,7 @@ export const CACU: Page = {
label: 'Biopsia', label: 'Biopsia',
section: ppv( section: ppv(
'CACU_VPP_BIOPSIA', 'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la biopsia', 'Tasa de confirmación histopatológica de referencia a biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.', 'Pacientes con biopsia reportada, por fecha de solicitud.',
{ {
kind: 'counts', kind: 'counts',
+16 -9
View File
@@ -26,6 +26,8 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** say the headline under the figure instead of above it */
footnote?: boolean;
/** what the headline proportion counts, in the plural (default: pacientes) */ /** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string; unit?: string;
note?: string; note?: string;
@@ -263,16 +265,16 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica', title: 'Días de toma de mastografía a interpretación radiológica',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico', title: 'Días de interpretación radiológica a diagnóstico',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
value: 'Indicador no disponible', value: 'Indicador no disponible',
note: PENDING, note: PENDING,
}, },
@@ -280,12 +282,12 @@ export const PAGES: Record<string, Page> = {
opportunity: [ opportunity: [
{ {
kind: 'route', kind: 'route',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a diagnóstico',
// from the mammography: only the two measures that start at it // from the mammography: only the two measures that start at it
sample: [ sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' }, { label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)', label: 'Diagnóstico (días de tamizaje a diagnóstico)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
}, },
], ],
@@ -476,22 +478,27 @@ export const HISTORY: Record<string, History> = {
], ],
), ),
{ {
title: 'Días de la toma de la citología a su resultado', title: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median',
},
{
title: 'Días de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
+5
View File
@@ -146,6 +146,9 @@ import { Reading } from './measures';
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`, `,
styles: ` styles: `
:host { :host {
@@ -347,6 +350,8 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** a line under the figure */
readonly foot = input('');
/** the card around it names it already (tabs inside one card) */ /** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false); readonly hideTitle = input(false);
readonly camaStyle = input(false); readonly camaStyle = input(false);
+10 -2
View File
@@ -28,7 +28,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
<app-readings <app-readings
[title]="s.title" [title]="s.title"
[camaStyle]="hasCamaHeading(s)" [camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)" [headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''" [note]="s.note ?? ''"
[modes]="s.modes" [modes]="s.modes"
[view]="view()" [view]="view()"
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
[title]="c.section.title" [title]="c.section.title"
[hideTitle]="true" [hideTitle]="true"
[camaStyle]="true" [camaStyle]="true"
[headline]="headlineOf(c.section)" [headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''" [note]="c.section.note ?? ''"
[modes]="c.section.modes" [modes]="c.section.modes"
[loading]="of().loading" [loading]="of().loading"
@@ -162,6 +164,12 @@ export class ReadingsSection {
const words = detail(measure, r, s.unit); const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
} }
/** The headline of a card that says it under its figure, as one line separated by commas. */
protected footOf(s: ReadingsCard): string {
return s.footnote
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
: '';
}
protected readonly draw = computed(() => (mode: Mode) => { protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined; if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure); const r = this.of().reading(mode.measure);
+2 -2
View File
@@ -33,10 +33,10 @@ interface Drawn {
</mat-button-toggle-group> </mat-button-toggle-group>
</section> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" /> <app-loading what="el histórico" text="Cargando histórico…" />
} @else if (series.error()) { } @else if (series.error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
No se pudo cargar la trazabilidad. No se pudo cargar el histórico.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button> <button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p> </p>
} @else { } @else {
+130
View File
@@ -0,0 +1,130 @@
import { HttpErrorResponse } from '@angular/common/http';
import type { Parameters } from 'fhir/r4';
import { eligibilityFailure, eligibilityView } from './eligibility';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
const candidate = (
scenario: string,
date: string,
eligible: boolean,
criteria: string[] = [],
sample?: string,
display?: string,
) =>
part('candidate', {
part: [
part('scenario', { valueCoding: { system: SCENARIOS, code: scenario, display } }),
part('index-date', { valueDate: date }),
...(sample ? [part('index-sample-id', { valueString: sample })] : []),
part('eligible', { valueBoolean: eligible }),
...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERIA, code: c } })),
],
});
const answer = (status: string, ...candidates: object[]): Parameters =>
({
resourceType: 'Parameters',
parameter: [
part('status', { valueCode: status }),
part('patient', { valueReference: { reference: 'Patient/p' } }),
part('cutoff', { valueDate: '2026-12-02' }),
...candidates,
],
}) as Parameters;
// Each test fails if the section merged visits, dropped a reason or read silence as eligibility.
describe('the eligibility answer as the section shows it', () => {
it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate(
'post_colposcopy',
'2020-08-10',
false,
['cancer_history', 'outcome_by_index', 'prior_treatment'],
'2020-08-10',
),
candidate('surveillance', '2024-01-05', true, [], 'a'),
candidate('surveillance', '2025-03-01', false, ['no_index_result'], 'b'),
candidate('post_colposcopy', '2022-02-02', true, [], '2022-02-02'),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.cutoff).toBe('2026-12-02');
expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([
['post_colposcopy', 'Postcolposcopia', 2],
['surveillance', 'Vigilancia', 2],
]);
const post = view.groups[0].visits; // newest visit first
expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([
['2022-02-02', true, []],
['2020-08-10', false, ['cancer_history', 'outcome_by_index', 'prior_treatment']],
]);
expect(post[1].reasons[0].text).toBe('Antecedente de cáncer cervicouterino');
expect(view.groups[1].visits.map((v) => v.sampleId)).toEqual(['b', 'a']);
});
it('the backend decides: a visit it calls eligible is eligible, one with reasons is not derived', () => {
const view = eligibilityView(answer('evaluated', candidate('survival', '2025-01-01', true)));
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups[0].visits[0]).toMatchObject({
eligible: true,
reasons: [],
sampleId: undefined,
});
});
it('without candidates it says so, which is not eligibility', () => {
expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' });
});
it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => {
for (const bad of [
null,
undefined,
{} as any,
{ resourceType: 'Bundle' } as any,
answer('evaluated'),
answer('other', candidate('survival', '2025-01-01', true)),
answer('evaluated', part('candidate', { part: [] })),
])
expect(eligibilityView(bad)).toEqual({ kind: 'unavailable' });
});
it('unknown codes show the display the API gave, else the code, and keep the code', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'),
candidate('other_scenario', '2025-01-02', false, ['another_rule']),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups.map((g) => [g.code, g.text])).toEqual([
['new_scenario', 'Escenario nuevo'],
['other_scenario', 'other_scenario'],
]);
expect(view.groups[1].visits[0].reasons).toEqual([
{ code: 'another_rule', text: 'another_rule' },
]);
});
});
describe('what a failed call is', () => {
const failure = (status: number, error: unknown = null) =>
eligibilityFailure(new HttpErrorResponse({ status, error }));
it('a 409 asks for the gold update and keeps the backend diagnostics', () => {
expect(
failure(409, {
resourceType: 'OperationOutcome',
issue: [{ code: 'conflict', diagnostics: 'rebuild gold.cacu_eligibility' }],
}),
).toEqual({ kind: 'gold', text: 'rebuild gold.cacu_eligibility' });
expect(failure(409)).toEqual({ kind: 'gold', text: undefined });
});
it('404 and 422 are "unavailable"; any other status or no connection is a communication error', () => {
expect(failure(404)).toEqual({ kind: 'unavailable' });
expect(failure(422)).toEqual({ kind: 'unavailable' });
expect(failure(500)).toEqual({ kind: 'error' });
expect(failure(0)).toEqual({ kind: 'error' });
expect(eligibilityFailure(new Error('boom'))).toEqual({ kind: 'error' });
});
});
+252
View File
@@ -0,0 +1,252 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */
export const SCENARIO_TEXT: Record<string, string> = {
surveillance: 'Vigilancia',
pre_colposcopy: 'Precolposcopia',
post_colposcopy: 'Postcolposcopia',
post_colposcopy_second_visit: 'Segunda visita postcolposcopia',
post_treatment: 'Postratamiento',
survival: 'Supervivencia',
};
/** The exclusion criteria the backend publishes, as the screens say them. */
export const CRITERION_TEXT: Record<string, string> = {
hysterectomy: 'Histerectomía previa al índice',
under_18: 'Edad menor de 18 años al índice',
prior_outcome: 'Resultado CIN2+ previo al índice',
no_index_result: 'Sin resultado de citología o VPH en la visita índice',
unreported_biopsy: 'Biopsia solicitada sin resultado',
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
cancer_history: 'Antecedente de cáncer cervicouterino',
prior_treatment: 'Tratamiento previo a la visita índice',
no_referral: 'Sin resultado que sustente la referencia a colposcopia',
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
no_birth_date: 'Fecha de nacimiento desconocida',
died_by_index: 'Defunción en o antes de la visita índice',
};
export interface Reason {
/** the API's code, untouched */
code: string;
text: string;
}
export interface Visit {
indexDate: string;
/** the sample the visit is evaluated at, when the backend names one */
sampleId?: string;
/** the backend's decision; it is never derived from the reasons */
eligible: boolean;
reasons: Reason[];
}
export interface ScenarioGroup {
code: string;
text: string;
visits: Visit[];
}
/** What the section can be in; none of them says "eligible" unless the backend did. */
export type EligibilityState =
| { kind: 'loading' }
| { kind: 'error' }
| { kind: 'unavailable' }
| { kind: 'gold'; text?: string }
| { kind: 'none'; cutoff?: string }
| { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] };
type Part = ParametersParameter;
const value = (p?: Part): unknown =>
p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueBoolean ?? undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const coding = (p?: Part) => p?.valueCoding;
/** The answer of `$eligibility`, grouped by scenario and keeping the visits apart: each visit has
* its own decision and its own reasons. A code the screens do not know shows the display the API
* gave, else the code itself. An answer that is not what the contract says is "unavailable". */
export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
const top = answer?.parameter;
if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' };
const status = value(named(top, 'status')[0]);
const cutoff = value(named(top, 'cutoff')[0]) as string | undefined;
const candidates = named(top, 'candidate');
if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff };
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
const groups = new Map<string, ScenarioGroup>();
for (const c of candidates) {
const scenario = coding(named(c.part, 'scenario')[0]);
const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined;
const eligible = value(named(c.part, 'eligible')[0]);
if (!scenario?.code || !indexDate || typeof eligible !== 'boolean')
return { kind: 'unavailable' };
const group = groups.get(scenario.code) ?? {
code: scenario.code,
text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code,
visits: [],
};
groups.set(scenario.code, group);
group.visits.push({
indexDate,
sampleId: value(named(c.part, 'index-sample-id')[0]) as string | undefined,
eligible,
reasons: named(c.part, 'criterion').flatMap((r) => {
const k = coding(r);
return k?.code
? [{ code: k.code, text: CRITERION_TEXT[k.code] ?? k.display ?? k.code }]
: [];
}),
});
}
for (const g of groups.values()) g.visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate));
return { kind: 'evaluated', cutoff, groups: [...groups.values()] };
}
/** What the answer's failure says: the gold must be updated (409), the patient has no such
* operation (404, 422), or the call itself failed (anything else, including no connection). */
export function eligibilityFailure(error: unknown): EligibilityState {
if (error instanceof HttpErrorResponse) {
if (error.status === 409) {
const issue = (error.error as { issue?: { diagnostics?: string }[] } | null)?.issue?.[0];
return { kind: 'gold', text: issue?.diagnostics };
}
if (error.status === 404 || error.status === 422) return { kind: 'unavailable' };
}
return { kind: 'error' };
}
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
/** "Elegibilidad por escenario clínico": the decisions the backend publishes for each indexed visit,
* one scenario at a time. It shows them; it decides nothing. */
@Component({
selector: 'app-eligibility',
template: `
@let s = state();
@switch (s.kind) {
@case ('loading') {
<p class="state" role="status" data-state="loading">Consultando la elegibilidad…</p>
}
@case ('error') {
<p class="state" role="alert" data-state="error">
No se pudo consultar la elegibilidad. Intente de nuevo más tarde.
</p>
}
@case ('unavailable') {
<p class="state" role="status" data-state="unavailable">
Información de elegibilidad no disponible para esta paciente.
</p>
}
@case ('gold') {
<p class="state" role="status" data-state="gold">
La elegibilidad requiere actualizar la capa gold del servidor; todavía no está disponible.
</p>
@if (s.text) {
<p class="muted detail">{{ s.text }}</p>
}
}
@case ('none') {
<p class="state" role="status" data-state="none">
Sin candidatos: la paciente no tiene visitas indexadas en estos escenarios
@if (s.cutoff) {
a la fecha de corte {{ s.cutoff }}
}
. Esto no significa que sea elegible.
</p>
}
@case ('evaluated') {
@for (g of s.groups; track g.code) {
<details class="scenario" [attr.data-scenario]="g.code" [open]="g.visits.length <= 2">
<summary>
<strong>{{ g.text }}</strong>
<span class="muted">
· {{ plural(g.visits.length, 'visita', 'visitas') }} ·
{{ plural(count(g, true), 'elegible', 'elegibles') }},
{{ plural(count(g, false), 'no elegible', 'no elegibles') }}
</span>
</summary>
<ul class="visits">
@for (v of g.visits; track $index) {
<li class="visit" [attr.data-eligible]="v.eligible">
<p class="head">
<span class="badge" [class.ok]="v.eligible">{{
v.eligible ? 'Elegible' : 'No elegible'
}}</span>
Fecha índice {{ v.indexDate }}
<span class="muted"
>· {{ v.sampleId ? 'Muestra ' + v.sampleId : 'Sin muestra asociada' }}</span
>
</p>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivos de exclusión">
@for (r of v.reasons; track r.code) {
<li [attr.data-code]="r.code">{{ r.text }}</li>
}
</ul>
}
</li>
}
</ul>
</details>
}
@if (s.cutoff) {
<p class="muted note">Visitas hasta la fecha de corte {{ s.cutoff }}.</p>
}
}
}
`,
styles: `
.note,
.detail {
font-size: 12px;
}
.state {
margin: 8px 0;
}
.scenario {
border-top: 1px solid #dce3e7;
padding: 6px 0;
}
.scenario summary {
cursor: pointer;
}
.visits {
list-style: none;
margin: 6px 0 0;
padding: 0;
}
.visit {
padding: 4px 0 4px 12px;
}
.head {
margin: 0;
}
.badge {
background: #f3d6dc;
border-radius: 10px;
color: #7a1f36;
font-size: 12px;
font-weight: 500;
margin-right: 6px;
padding: 1px 8px;
}
.badge.ok {
background: #dcefe4;
color: #1d5a3b;
}
.why {
margin: 2px 0 0;
padding-left: 22px;
}
`,
})
export class Eligibility {
readonly state = input.required<EligibilityState>();
protected plural = plural;
protected count(g: ScenarioGroup, eligible: boolean) {
return g.visits.filter((v) => v.eligible === eligible).length;
}
}
+31
View File
@@ -0,0 +1,31 @@
import type { EligibilityState, Visit } from './eligibility';
import { ineligibility } from './ineligibility';
const visit = (indexDate: string, ...reasons: string[]): Visit => ({
indexDate,
eligible: !reasons.length,
reasons: reasons.map((text) => ({ code: text, text })),
});
const state: EligibilityState = {
kind: 'evaluated',
groups: [
{
code: 'pre_colposcopy',
text: 'Precolposcopia',
visits: [visit('2025-01-01', 'Histerectomía previa al índice'), visit('2024-01-01')],
},
{ code: 'post_treatment', text: 'Postratamiento', visits: [visit('2025-01-01', 'Otro')] },
],
};
describe('ineligibility', () => {
it('speaks only when she is not eligible in her own scenario', () => {
expect(ineligibility(state, 'pre_colposcopy', '2025-06-01')).toBe(
'No disponible por: Histerectomía previa al índice.',
);
expect(ineligibility(state, 'pre_colposcopy', '2024-06-01')).toBeUndefined();
expect(ineligibility(state, 'post_colposcopy', '2025-06-01')).toBeUndefined();
expect(ineligibility(state, 'case', '2025-06-01')).toBeUndefined();
expect(ineligibility({ kind: 'error' }, 'pre_colposcopy', '2025-06-01')).toBeUndefined();
});
});
+31
View File
@@ -0,0 +1,31 @@
import type { EligibilityState } from './eligibility';
/** The `$eligibility` scenarios that stand for each follow-up status, the first that has a
* visit speaking for her. A case has no disease-risk estimate to be eligible for. */
const SCENARIOS: Record<string, string[]> = {
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
post_colposcopy: ['post_colposcopy'],
post_treatment: ['post_treatment'],
};
/** What the risk section says when she is not eligible in her clinical scenario, from its latest
* visit indexed by `day`; nothing when she is eligible or the backend has no visit of it. */
export function ineligibility(
state: EligibilityState,
status: string,
day: string,
): string | undefined {
if (state.kind !== 'evaluated') return undefined;
for (const scenario of SCENARIOS[status] ?? []) {
// visits come latest first
const latest = state.groups
.find((g) => g.code === scenario)
?.visits.find((v) => v.indexDate <= day);
if (latest) {
return latest.eligible
? undefined
: `No disponible por: ${latest.reasons.map((r) => r.text).join('; ')}.`;
}
}
return undefined;
}
+151 -70
View File
@@ -121,13 +121,6 @@
} }
<div data-section="etapas"> <div data-section="etapas">
<app-stages [stages]="s" [detail]="true" /> <app-stages [stages]="s" [detail]="true" />
<p class="muted route-note">
Etapas de la citología{{ s[0].day ? ' del ' + s[0].day : '' }} a la fecha de corte
{{ cutoff() }}. «Inferida por fechas» es una asociación por cercanía de fechas, no
un vínculo clínico confirmado; un intervalo «(inferido)» depende de una etapa
inferida; «Pendiente» es una biopsia solicitada sin reporte a la fecha de corte;
«Sin dato» indica que no hay dato.
</p>
</div> </div>
} }
<table class="plain"> <table class="plain">
@@ -253,66 +246,68 @@
</mat-card> </mat-card>
} }
<mat-card appearance="outlined" class="wide"> @if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) {
<mat-card-header <mat-card appearance="outlined" class="wide" data-section="riesgos">
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header <mat-card-content>
> @if (riskExclusion(); as reason) {
<mat-card-content> <p role="status">{{ reason }}</p>
@if (riskExclusion(); as reason) { } @else {
<p role="status">{{ reason }}</p> <app-risk-scales [groups]="groups()" />
} @else {
<app-risk-scales [groups]="groups()" />
@if (reference.value(); as ref) {
<app-reference-risk [view]="ref" />
} }
} @if (riskModels().length) {
@if (models().length) { <details data-section="modelos">
<table class="plain"> <summary>Modelos y valores</summary>
<thead> <table class="plain">
<tr> <thead>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Probabilidad</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (m of models(); track m.model) {
@for (p of m.predictions; track p.years) {
<tr> <tr>
<td>{{ $first ? m.text : '' }}</td> <th>Modelo</th>
<td>{{ $first ? m.index : '' }}</td> <th>Fecha índice</th>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td> <th>Horizonte</th>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td> <th>Probabilidad</th>
<td> <th>IC 95 %</th>
@if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }}
%
} @else {
—
}
</td>
</tr> </tr>
} </thead>
<tbody>
@for (m of riskModels(); track m.model) {
@for (p of m.predictions; track p.years) {
<tr>
<td>{{ $first ? m.text : '' }}</td>
<td>{{ $first ? m.index : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{
p.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
}
</tbody>
</table>
</details>
}
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
<details class="curves" open data-section="curvas">
<summary>Curvas de probabilidad con su intervalo</summary>
@if (riskSeries.value()?.length) {
<app-risk-series [series]="riskSeries.value()!" />
} @else {
<app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
} }
</tbody> </details>
</table> }
<details class="curves" open data-section="curvas"> @if (!riskModels().length && !riskExclusion()) {
<summary>Curvas de probabilidad con su intervalo</summary> <p class="muted">Sin evaluación de un modelo en producción.</p>
<ul class="curve-text"> }
@for (t of curveText(); track $index) { </mat-card-content>
<li>{{ t }}</li> </mat-card>
} }
</ul>
<app-plot [figure]="curve()" [height]="300" />
</details>
} @else if (!riskExclusion()) {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
</mat-card-content>
</mat-card>
@if (domain() === 'tea') { @if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea"> <mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -560,12 +555,76 @@
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} }
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { @if (models().some((m) => m.model.endsWith('.survival'))) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia"> <mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header><mat-card-title>Riesgo de muerte</mat-card-title></mat-card-header> <mat-card-header>
<mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
}}</mat-card-title>
</mat-card-header>
<mat-card-content> <mat-card-content>
<h3>Análisis de supervivencia</h3> @if (domain() !== 'cacu') {
@if (survival.isLoading()) { <h3>Análisis de supervivencia</h3>
}
@if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
@for (g of survivalScales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
v.risk!.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
</tbody>
</table>
</details>
}
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.figure) {
<p class="muted">
Kaplan-Meier de pacientes con sus mismos valores (IC 95 % Greenwood log-log; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p>
<app-plot [figure]="c.figure" [height]="340" [toolbar]="false" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" /> <app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) { } @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3> <h3>Escenario clínico de la paciente</h3>
@@ -574,17 +633,39 @@
<li>{{ name }}</li> <li>{{ name }}</li>
} }
</ul> </ul>
@if (s.methods.length) {
<details>
<summary>Métodos</summary>
<ul class="scenarios methods">
@for (name of s.methods; track name) {
<li>{{ name }}</li>
}
</ul>
</details>
}
@for (f of s.figures; track f.title) { @for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4> <h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" /> <app-plot [figure]="f.figure" [height]="340" />
} @empty { }
<p class="muted"> @for (name of s.unavailable; track name) {
Sus escenarios no tienen fallecimientos suficientes para trazar curvas. <h4>{{ name }}</h4>
<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> </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 {
<p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+149 -34
View File
@@ -13,6 +13,8 @@ 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 { 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';
import { readReport$Json } from '../api/fn/models/read-report-json'; import { readReport$Json } from '../api/fn/models/read-report-json';
@@ -25,10 +27,13 @@ import { HttpClient } from '@angular/common/http';
import type { Parameters as FhirParameters } from 'fhir/r4'; import type { Parameters as FhirParameters } from 'fhir/r4';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration'; import { ApiConfiguration } from '../api/api-configuration';
import { ANTECEDENTS, Fact, group, split } from './record-groups'; import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk'; import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
import { curveFigure, curveText } from './risk-curve'; import { ineligibility } from './ineligibility';
import { riskGroups, riskScales, RiskScales } from './risk-scales'; import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve';
import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationFigure, combinationOf, noCurveText } from './survival-combination';
import { route, Stages } from './stages'; import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -69,6 +74,31 @@ function facts(observations: Observation[]): Fact[] {
/** One patient: her history (conditions, procedures), her tests and results, and the /** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */ * champion models' risks with their curves. Everything read from the FHIR API. */
/** The names of the methods the figures draw, each once. */
function methods(figures: { figure: { data: unknown[] } }[]): string[] {
const names = figures.flatMap((f) => f.figure.data.map((t) => (t as { name?: string }).name));
return [...new Set(names.filter((n): n is string => !!n))];
}
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [ imports: [
@@ -81,7 +111,7 @@ function facts(observations: Observation[]): Fact[] {
RouterLink, RouterLink,
Plot, Plot,
RiskScales, RiskScales,
ReferenceRisk, RiskSeries,
Stages, Stages,
], ],
templateUrl: './paciente.html', templateUrl: './paciente.html',
@@ -148,14 +178,20 @@ export class Paciente {
}); });
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv')); protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff())); protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
* hysterectomy of her record is still held against her when the backend does not report it,
* as with evidence loaded without the day it was available. */
protected readonly riskExclusion = computed(() => { protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined; if (this.domain() !== 'cacu') return undefined;
const patient = this.patient(); const patient = this.patient();
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
const sample = this.citologia()?.slice(0, 10); const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff(); const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
const reported = ineligibility(this.eligibility(), status, index);
if (reported) return reported;
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index return recorded && recorded <= index
? `Sin estimación de riesgo por antecedente de histerectomía registrado el ${recorded}.` ? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined; : undefined;
}); });
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */ /** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
@@ -166,40 +202,92 @@ export class Paciente {
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0]; const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined; return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
}); });
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly scales = computed(() => protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.models()) : [], this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
); );
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */ /** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
* survival only there is nothing to draw here: its scales are in the survival section. */
protected readonly groups = computed(() => protected readonly groups = computed(() =>
this.domain() === 'cacu' ? riskGroups(this.models()) : [], this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
? riskGroups(this.riskModels())
: [],
); );
/** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API protected readonly survivalScales = computed(() =>
* answers 404 while the feature is off: then nothing is shown. */ this.domain() === 'cacu'
protected readonly reference = resource({ ? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
: [],
);
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
* the model version that scored her. */
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
},
loader: async ({ params: { version, inputs } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: 'cacu' as Domain,
name: 'survival',
version,
report: 'interpretability',
});
const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km
? { n: found.n, fallecidos: found.fallecidos, figure: combinationFigure(found.km) }
: { missing: noCurveText(report as Record<string, unknown>, found) };
},
});
/** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({
params: () => params: () =>
this.domain() === 'cacu' this.domain() === 'cacu'
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() } ? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
: undefined, : undefined,
loader: async ({ params }): Promise<ReferenceView | undefined> => { loader: async ({ params }): Promise<Series[] | undefined> => {
try { try {
const answer = await firstValueFrom( const answer = await firstValueFrom(
this.http.get<FhirParameters>( this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$reference-risk`, `${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
{ {
params: Object.fromEntries( params: Object.fromEntries(
Object.entries({ cutoff: params.cutoff, sample: params.sample }).filter( Object.entries({
([, v]) => !!v, cutoff: params.cutoff,
), sample: params.sample?.slice(0, 10),
) as Record<string, string>, }).filter((e): e is [string, string] => !!e[1]),
),
}, },
), ),
); );
return referenceView(answer); return parseSeries(answer);
} catch { } catch {
return undefined; return undefined;
} }
}, },
}); });
/** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a
* state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */
private readonly eligibilityData = resource({
params: () => (this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined),
loader: async ({ params }): Promise<EligibilityState> => {
try {
const answer = await this.api.invoke(cacuEligibility, {
domain: 'cacu' as Domain,
id: params.id,
cutoff: params.cutoff,
});
return eligibilityView(answer as FhirParameters);
} catch (error) {
return eligibilityFailure(error);
}
},
});
protected readonly eligibility = computed<EligibilityState>(() =>
this.eligibilityData.isLoading()
? { kind: 'loading' }
: (this.eligibilityData.value() ?? { kind: 'loading' }),
);
protected readonly saving = signal(false); protected readonly saving = signal(false);
protected readonly saveError = signal(''); protected readonly saveError = signal('');
/** CaCu: her record as a PDF. */ /** CaCu: her record as a PDF. */
@@ -236,14 +324,15 @@ export class Paciente {
protected readonly tests = computed(() => { protected readonly tests = computed(() => {
const d = this.data.value(); const d = this.data.value();
if (!d) return []; if (!d) return [];
return d.reports.map((r) => { return d.reports.flatMap((r) => {
const results = (r.result ?? []) const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1])) .map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[]; .filter((o) => !!o) as Observation[];
// the study's own results; the form's antecedents are in their own section and the extra // the study's own results; the form's antecedents are in their own section and the extra
// findings are collapsed (record-groups) // findings are collapsed (record-groups)
const found = group(facts(results)); const { hpv, rest } = hpvApart(facts(results));
return { const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '', date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate, reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code), kind: label(r.code),
@@ -251,6 +340,10 @@ export class Paciente {
results: found.results, results: found.results,
findings: found.findings, findings: found.findings,
}; };
// an HPV result is a study of its own: its own row, only when there is one
return hpv.length
? [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]
: [row];
}); });
}); });
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was /** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
@@ -296,6 +389,9 @@ export class Paciente {
text: r.method?.text ?? '', text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '', index: r.occurrenceDateTime ?? '',
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in // the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? []) scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico') .filter((e) => e.url === EXT + 'escenario-clinico')
@@ -345,6 +441,10 @@ export class Paciente {
return { return {
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[], factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
scenarios: m.scenarios, scenarios: m.scenarios,
unavailable: [] as string[],
insufficient: [] as Insufficient[],
missing: [] as string[],
methods: [] as string[],
figures: mine(r['escenarios'] ?? []).map((e) => figures: mine(r['escenarios'] ?? []).map((e) =>
scenarioFigure( scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`, `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
@@ -355,17 +455,29 @@ export class Paciente {
), ),
}; };
} }
const drawn = mine((report?.['escenarios'] ?? []) as any[]);
const figures = drawn.map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'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: mine((report?.['escenarios'] ?? []) as any[]).map((e) => figures,
scenarioFigure( // her scenarios the report draws no curve for
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, unavailable: domain === 'cacu' ? [] : undrawn,
e, insufficient,
e.horizons_months, missing,
'Supervivencia S(t)', methods: methods(figures),
),
),
}; };
}, },
}); });
@@ -479,11 +591,14 @@ export class Paciente {
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? [])); protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? [])); protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */ /** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
protected readonly curve = computed<Figure>(() => curveFigure(this.models(), this.top())); protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
protected readonly curveText = computed(() => curveText(this.models()));
private top(): number { private top(): number {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); return Math.max(
0,
...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(() => {
+8
View File
@@ -46,3 +46,11 @@ export function group(facts: Fact[]) {
} }
return { antecedents, results, findings }; return { antecedents, results, findings };
} }
const HPV_FIELDS = ['hpv', 'hpv_16', 'hpv_18'];
/** The cytology report's HPV results, apart from the cytology's own facts. */
export function hpvApart(facts: Fact[]) {
const isHpv = (f: Fact) => f.study === 'cervical_cytology' && HPV_FIELDS.includes(f.field);
return { hpv: facts.filter(isHpv), rest: facts.filter((f) => !isHpv(f)) };
}
+171 -1
View File
@@ -1,5 +1,5 @@
import type { Parameters } from 'fhir/r4'; import type { Parameters } from 'fhir/r4';
import { horizonLabel, referenceView } from './reference-risk'; import { groupReference, horizonLabel, outcomeText, referenceView } from './reference-risk';
const part = (name: string, extra: object) => ({ name, ...extra }) as any; const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const answer = (...parameter: object[]): Parameters => const answer = (...parameter: object[]): Parameters =>
@@ -88,3 +88,173 @@ describe('the reference answer as the section shows it', () => {
}); });
}); });
}); });
const cmp = (
model: string,
outcome: string,
status: string,
reasons: string[],
extra: object[] = [],
) =>
part('comparison', {
part: [
part('model', { valueCode: model }),
part('title', { valueString: model }),
part('outcome', { valueString: outcome }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const two = (a: object[], b: object[]) =>
answer(
part('status', { valueCode: 'resolved' }),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.001 }),
...a,
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 5 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.0027 }),
...b,
],
}),
);
describe('outcome names', () => {
it('translates the known outcomes for display and leaves the API identifier untouched', () => {
expect(outcomeText('cancer')).toBe('Cáncer');
expect(outcomeText('CIN2+ within one year')).toBe('CIN2+ en un año');
expect(outcomeText('CIN3+')).toBe('CIN3 o más grave (CIN3+)');
expect(outcomeText('something new')).toBe('something new');
expect(outcomeText(undefined)).toBe('');
const view = referenceView(
two([cmp('m', 'cancer', 'not_comparable', ['outcome_differs'])], []),
);
expect(view.horizons[0].comparisons[0].outcome).toBe('cancer');
});
});
describe('grouping the comparison', () => {
const reasons = ['outcome_differs', 'population_not_verified'];
it('keeps every model, horizon, value and interval, and says shared reasons once', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN2+',
'not_comparable',
[...reasons, 'index_date_differs'],
[part('institutional', { valueDecimal: 0.05 })],
),
cmp('b', 'cancer', 'not_comparable', reasons),
],
[
cmp('a', 'CIN2+', 'not_comparable', reasons, [
part('institutional', { valueDecimal: 0.07 }),
part('institutional-low', { valueDecimal: 0.05 }),
part('institutional-high', { valueDecimal: 0.09 }),
]),
cmp('b', 'cancer', 'not_comparable', [...reasons, 'horizon_not_published_by_model']),
],
),
),
);
expect(g.reference.map((r) => [r.years, r.reference])).toEqual([
[0, 0.001],
[5, 0.0027],
]);
expect(g.common).toEqual(reasons); // every model gives them
expect(g.models.map((m) => [m.model, m.outcome, m.rows.length])).toEqual([
['a', 'CIN2+', 2],
['b', 'cancer', 2],
]);
expect(g.models[0].reasons).toEqual([]); // nothing else shared by both of a's horizons
expect(g.models[0].rows[0].reasons).toEqual(['index_date_differs']);
expect(g.models[0].rows[1]).toMatchObject({
institutional: 0.07,
low: 0.05,
high: 0.09,
reasons: [],
});
expect(g.models[1].rows[1].reasons).toEqual(['horizon_not_published_by_model']);
});
it('never merges across outcomes: reasons are only shared where every compared row has them', () => {
const g = groupReference(
referenceView(
two(
[
cmp('a', 'CIN2+', 'not_comparable', ['outcome_differs']),
cmp('b', 'cancer', 'not_comparable', ['no_reference']),
],
[],
),
),
);
expect(g.common).toEqual([]);
expect(g.models.flatMap((m) => m.rows.flatMap((r) => r.reasons))).toEqual([
'outcome_differs',
'no_reference',
]);
});
it('a comparable row keeps its difference and a missing interval stays missing', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN3+',
'comparable',
[],
[
part('institutional', { valueDecimal: 0.01 }),
part('difference-pp', { valueDecimal: 0.9 }),
],
),
],
[],
),
),
);
expect(g.models[0].rows[0]).toMatchObject({
status: 'comparable',
differencePp: 0.9,
low: undefined,
});
});
it('without a model it says so once, with its reasons', () => {
const g = groupReference(
referenceView(
two(
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
),
),
);
expect(g.models).toEqual([]);
expect(g.withoutModel).toEqual(['no_institutional_model']);
});
});
+200 -64
View File
@@ -1,5 +1,5 @@
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core'; import { Component, computed, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The states a resolution ends in, as the screens say them. */ /** The states a resolution ends in, as the screens say them. */
@@ -205,6 +205,86 @@ export function referenceView(answer: Parameters): ReferenceView {
return view; return view;
} }
/** Outcome names as the screens say them; presentation only: the API's identifiers stay as they are
* (an outcome this map does not know is shown as the API gave it). */
export const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3 o más grave (CIN3+)',
'CIN2+': 'CIN2 o más grave (CIN2+)',
cancer: 'Cáncer',
'CIN2+ within one year': 'CIN2+ en un año',
'not stated as a histology outcome': 'No expresado como desenlace histológico',
};
export const outcomeText = (outcome?: string) => (outcome ? (OUTCOME_TEXT[outcome] ?? outcome) : '');
export interface ModelRow extends Omit<ComparisonView, 'reasons'> {
years: number;
label: string;
/** the reasons of this horizon that its model's other horizons do not share */
reasons: string[];
}
export interface ModelBlock {
model?: string;
title?: string;
outcome?: string;
/** reasons shared by every non-comparable horizon of this model, said once */
reasons: string[];
rows: ModelRow[];
}
export interface Grouped {
/** the reference by horizon: one table, whatever the models */
reference: { years: number; label: string; published: boolean; reference?: number }[];
/** reasons shared by every non-comparable comparison of every model, said once */
common: string[];
models: ModelBlock[];
/** no institutional model evaluated her: said once, with its reasons */
withoutModel: string[];
}
const shared = (lists: string[][]) =>
lists.length > 1 ? lists[0].filter((r) => lists.every((l) => l.includes(r))) : [];
/** Groups only what is equivalent: the reference once per horizon; a reason that every non-comparable
* comparison of a model (or of all models) gives, once; everything else stays where it is. Nothing is
* dropped, and a difference is never made: it is only the API's, on a comparable row. */
export function groupReference(v: ReferenceView): Grouped {
const reference = v.horizons.map((h) => ({
years: h.years,
label: h.label,
published: h.published,
reference: h.reference,
}));
const byModel = new Map<string, ModelBlock>();
const withoutModel: string[] = [];
for (const h of v.horizons)
for (const c of h.comparisons) {
if (!c.model) {
for (const r of c.reasons) if (!withoutModel.includes(r)) withoutModel.push(r);
continue;
}
const block = byModel.get(c.model) ?? {
model: c.model,
title: c.title,
outcome: c.outcome,
reasons: [],
rows: [],
};
byModel.set(c.model, block);
block.rows.push({ ...c, years: h.years, label: h.label });
}
const models = [...byModel.values()];
const notComparable = (b: ModelBlock) => b.rows.filter((r) => r.status !== 'comparable');
const common = shared(models.flatMap(notComparable).map((r) => r.reasons));
const everyModel = models.length > 1 ? common : [];
for (const b of models) {
const own = shared(notComparable(b).map((r) => r.reasons.filter((x) => !everyModel.includes(x))));
b.reasons = own;
for (const r of b.rows)
if (r.status !== 'comparable')
r.reasons = r.reasons.filter((x) => !everyModel.includes(x) && !own.includes(x));
}
return { reference, common: everyModel, models, withoutModel };
}
const OFFICIAL: Record<string, string> = { const OFFICIAL: Record<string, string> = {
match: 'coincide con la tabla del NCI', match: 'coincide con la tabla del NCI',
'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo', 'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo',
@@ -238,10 +318,12 @@ const OFFICIAL: Record<string, string> = {
<dd>{{ s.label }}</dd> <dd>{{ s.label }}</dd>
</div> </div>
} }
<div> @if (v.source?.outcome; as out) {
<dt>Desenlace</dt> <div>
<dd>CIN3 o más grave (CIN3+)</dd> <dt>Desenlace de la referencia</dt>
</div> <dd [attr.data-outcome]="out">{{ outcomeText(out) }}</dd>
</div>
}
@if (v.evaluationDate ?? v.index?.sampleDate; as day) { @if (v.evaluationDate ?? v.index?.sampleDate; as day) {
<div> <div>
<dt>Fecha de evaluación</dt> <dt>Fecha de evaluación</dt>
@@ -269,68 +351,112 @@ const OFFICIAL: Record<string, string> = {
</ul> </ul>
} }
@if (v.horizons.length) { @if (v.horizons.length) {
<table class="plain" aria-label="Comparación por horizonte"> @let g = grouped();
<table class="plain" aria-label="Referencia NCI por horizonte">
<thead> <thead>
<tr> <tr>
<th>Horizonte</th> <th>Horizonte</th>
<th>Modelo institucional</th>
<th>Referencia NCI</th> <th>Referencia NCI</th>
<th>Diferencia (puntos porcentuales)</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (h of v.horizons; track h.years) { @for (h of g.reference; track h.years) {
@for (c of h.comparisons.length ? h.comparisons : [none]; track $index) { <tr [attr.data-years]="h.years">
<tr [attr.data-years]="h.years"> <td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td> <td class="nowrap" data-label="Referencia NCI">
<td class="model" data-label="Modelo institucional"> @if (h.reference !== undefined) {
@if (c.model) { <strong>{{ h.reference * 100 | number: '1.2-2' }} %</strong>
<strong>{{ c.title }}</strong> } @else {
<span class="muted">{{ c.outcome }}</span> <span>No publicado</span>
} }
@if (c.institutional !== undefined) { </td>
{{ c.institutional * 100 | number: '1.2-2' }} % </tr>
@if (c.low !== undefined && c.high !== undefined) {
<span class="muted"
>(IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{
c.high * 100 | number: '1.2-2'
}}
%)</span
>
}
} @else {
<span>No disponible</span>
}
</td>
<td class="nowrap" data-label="Referencia NCI">
@if (h.reference !== undefined) {
<strong>{{ h.reference * 100 | number: '1.2-2' }} %</strong>
} @else {
<span>No publicado</span>
}
</td>
<td data-label="Diferencia (puntos porcentuales)">
@if (c.status === 'comparable' && c.differencePp !== undefined) {
<strong
>{{ c.differencePp > 0 ? '+' : ''
}}{{ c.differencePp | number: '1.2-2' }}</strong
>
} @else {
<span>No comparable</span>
@if (c.reasons.length) {
<ul class="why">
@for (r of c.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
}
</td>
</tr>
}
} }
</tbody> </tbody>
</table> </table>
<h4>Modelos institucionales</h4>
@if (g.withoutModel.length || !g.models.length) {
<p class="nomodel">
<strong>No disponible</strong>
</p>
<ul class="why" aria-label="Motivo">
@for (r of g.withoutModel; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (g.common.length) {
<p class="muted">Motivos que comparten todas las comparaciones no válidas:</p>
<ul class="why" aria-label="Motivos comunes">
@for (r of g.common; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@for (m of g.models; track m.model) {
<section class="model" [attr.data-model]="m.model" [attr.aria-label]="m.title">
<h5>
{{ m.title }}
<span class="muted" [attr.data-outcome]="m.outcome">{{ outcomeText(m.outcome) }}</span>
</h5>
@if (m.reasons.length) {
<p class="muted">No comparable en estos horizontes:</p>
<ul class="why" aria-label="Motivos del modelo">
@for (r of m.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
<table class="plain" [attr.aria-label]="'Comparación de ' + m.title">
<thead>
<tr>
<th>Horizonte</th>
<th>Modelo institucional</th>
<th>Diferencia (puntos porcentuales)</th>
</tr>
</thead>
<tbody>
@for (c of m.rows; track c.years) {
<tr [attr.data-years]="c.years">
<td class="nowrap" data-label="Horizonte">{{ c.label }}</td>
<td data-label="Modelo institucional">
@if (c.institutional !== undefined) {
{{ c.institutional * 100 | number: '1.2-2' }} %
@if (c.low !== undefined && c.high !== undefined) {
<span class="muted"
>(IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{
c.high * 100 | number: '1.2-2'
}}
%)</span
>
}
} @else {
<span>No disponible</span>
}
</td>
<td data-label="Diferencia (puntos porcentuales)">
@if (c.status === 'comparable' && c.differencePp !== undefined) {
<strong
>{{ c.differencePp > 0 ? '+' : ''
}}{{ c.differencePp | number: '1.2-2' }}</strong
>
} @else {
<span>No comparable</span>
@if (c.reasons.length) {
<ul class="why">
@for (r of c.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
}
</td>
</tr>
}
</tbody>
</table>
</section>
}
<p class="muted note"> <p class="muted note">
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados). estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
@@ -406,6 +532,7 @@ const OFFICIAL: Record<string, string> = {
table { table {
border-collapse: collapse; border-collapse: collapse;
width: 100%; width: 100%;
table-layout: fixed;
} }
th, th,
td { td {
@@ -413,9 +540,18 @@ const OFFICIAL: Record<string, string> = {
text-align: left; text-align: left;
vertical-align: top; vertical-align: top;
} }
.model strong, .model {
.model .muted { border-top: 1px solid #dce3e7;
display: block; margin-top: 8px;
padding-top: 4px;
}
h4,
h5 {
margin: 12px 0 4px;
}
h5 .muted {
font-weight: 400;
margin-left: 8px;
} }
.why { .why {
margin: 4px 0; margin: 4px 0;
@@ -463,10 +599,10 @@ const OFFICIAL: Record<string, string> = {
}) })
export class ReferenceRisk { export class ReferenceRisk {
readonly view = input.required<ReferenceView>(); readonly view = input.required<ReferenceView>();
protected readonly none: ComparisonView = { protected readonly grouped = computed(() => groupReference(this.view()));
status: 'not_comparable', protected outcomeText(outcome?: string) {
reasons: ['no_institutional_model'], return outcomeText(outcome);
}; }
protected statusText(status: string) { protected statusText(status: string) {
return STATUS_TEXT[status] ?? status; return STATUS_TEXT[status] ?? status;
} }
+44 -2
View File
@@ -1,4 +1,4 @@
import { horizon, riskGroups, riskScales } from './risk-scales'; import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high }); const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
@@ -35,7 +35,7 @@ describe('the risk scales', () => {
{ text: 'Recurrencia v2', index: '2026-03-01', predictions: [at(5, 0.98)] }, { text: 'Recurrencia v2', index: '2026-03-01', predictions: [at(5, 0.98)] },
{ text: 'Otro', index: '2026-03-02', predictions: [at(3, 0.3)] }, // no horizon of its own { text: 'Otro', index: '2026-03-02', predictions: [at(3, 0.3)] }, // no horizon of its own
]); ]);
expect(groups.map((g) => g.title)).toEqual(['Supervivencia v3', 'Recurrencia v2', 'Otro']); expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']); expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años']; const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años'];
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels); for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
@@ -60,3 +60,45 @@ describe('the risk scales', () => {
]); ]);
}); });
}); });
describe('which models feed the risk scales', () => {
it('excludes survival and recurrence estimates, which are not risks of the scales outcome', () => {
expect(['cacu.cin2_pim', 'cacu.cancer_pim', 'cacu.cin2_logistic'].every(isRiskModel)).toBe(
true,
);
expect(isRiskModel('cacu.survival')).toBe(false);
expect(isRiskModel('cama.recurrence')).toBe(false);
});
it('with no risk model both horizons are unavailable (nothing is converted from a survival)', () => {
const risk = [
{
text: 'm',
index: '2026-01-01',
predictions: [{ years: 5, p: 0.7 }],
model: 'cacu.survival',
},
].filter((m) => isRiskModel(m.model));
expect(riskGroups(risk).flatMap((g) => g.scales.map((s) => s.risk))).toEqual([
undefined,
undefined,
]);
});
});
describe('survival scales', () => {
it('complements mortality and reverses interval bounds at every published horizon', () => {
const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
expect(g.survival).toBe(true);
expect(g.index).toBe('2026-01-01');
expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
});
it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
.toEqual(inputs);
expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
.toBeUndefined();
});
});
+187 -14
View File
@@ -12,6 +12,11 @@ export interface RiskScale {
risk?: Prediction; risk?: Prediction;
} }
/** Whether a model's estimate is a risk of the outcome the scales and curves draw. Survival (S(t)) and
* recurrence-free survival are estimates of another outcome, shown in their own analysis: they are
* never drawn on these scales, and no conversion (1 − S) is made. */
export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(model);
/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */ /** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] { export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) => return models.flatMap((m) =>
@@ -41,24 +46,89 @@ export function horizon(predictions: Prediction[], years: number): Prediction |
export interface RiskGroup { export interface RiskGroup {
/** the model's own title and the day it was scored (none: no model has scored her) */ /** the model's own title and the day it was scored (none: no model has scored her) */
title?: string; title?: string;
scenario?: string;
index?: string; index?: string;
survival?: boolean;
inputs?: Record<string, unknown>;
/** the model and version that scored her, and the day it did */
model?: string;
evaluated?: string;
scales: { label: string; risk?: Prediction }[]; scales: { label: string; risk?: Prediction }[];
} }
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(
models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
text?: string;
evaluated?: string;
}[],
): RiskGroup[] {
return models
.map((m) => ({
title: 'Supervivencia',
index: m.index,
survival: true,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '),
scales: m.predictions.flatMap((p) => {
const v = horizon(m.predictions, p.years);
return v
? [
{
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
}))
.filter((g) => g.scales.length);
}
const HORIZONS: [number, string][] = [ const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'], [0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'], [5, 'Riesgo a 5 años'],
]; ];
/** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */
export function titleParts(text: string): { title: string; scenario?: string } {
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
return { title, scenario };
}
/** The scales the page draws: both horizons of every model, or, with no model, both horizons /** The scales the page draws: both horizons of every model, or, with no model, both horizons
* unavailable. */ * unavailable. */
export function riskGroups( export function riskGroups(
models: { text: string; index: string; predictions: Prediction[] }[], models: {
text: string;
index: string;
predictions: Prediction[];
inputs?: Record<string, unknown>;
evaluated?: string;
}[],
): RiskGroup[] { ): RiskGroup[] {
const scales = (predictions: Prediction[]) => const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) })); HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
return models.length return models.length
? models.map((m) => ({ title: m.text, index: m.index, scales: scales(m.predictions) })) ? models.map((m) => ({
...titleParts(m.text),
index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions),
}))
: [{ scales: scales([]) }]; : [{ scales: scales([]) }];
} }
@@ -69,12 +139,9 @@ export function riskGroups(
selector: 'app-risk-scales', selector: 'app-risk-scales',
imports: [DecimalPipe], imports: [DecimalPipe],
template: ` template: `
@if (groups().length) {
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
}
@for (g of groups(); track $index) { @for (g of groups(); track $index) {
@if (g.title) { @if (g.title) {
<h3>{{ g.title }}{{ g.index ? ' · fecha índice ' + g.index : '' }}</h3> <h3>{{ g.title }}</h3>
} }
@for (s of g.scales; track s.label) { @for (s of g.scales; track s.label) {
<div class="risk-scale" [attr.data-scale]="s.label"> <div class="risk-scale" [attr.data-scale]="s.label">
@@ -82,18 +149,24 @@ export function riskGroups(
<strong>{{ s.label }}</strong> <strong>{{ s.label }}</strong>
@if (s.risk; as r) { @if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) { @if (r.low !== undefined && r.high !== undefined) {
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ · IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }}
r.high * 100 | number: '1.1-2'
}}
% %
} }
} @else { } @else {
· No disponible · No disponible
} }
</p> </p>
<div class="risk-plot" [class.unavailable]="!s.risk"> <div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="risk-line" aria-hidden="true"></div> <div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) { @if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
<span
class="risk-interval"
[style.left.%]="r.low * 100"
[style.width.%]="(r.high - r.low) * 100"
aria-hidden="true"
></span>
}
<span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span> <span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
<strong <strong
class="risk-value" class="risk-value"
@@ -107,12 +180,60 @@ export function riskGroups(
</div> </div>
</div> </div>
} }
@if (g.index) {
<p class="muted foot">
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p>
}
@if (g.title && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (item of entries(g.inputs); track item[0]) {
<div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</section>
}
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (item of entries(g.inputs ?? {}); track item[0]) {
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
} }
`, `,
styles: ` styles: `
.note {
margin: 0 0 8px;
}
.risk-scale { .risk-scale {
margin: 8px 0 14px; margin: 8px 0 14px;
max-width: 740px; max-width: 740px;
@@ -121,7 +242,7 @@ export function riskGroups(
margin: 0; margin: 0;
} }
.risk-plot { .risk-plot {
padding-top: 24px; padding-top: 30px;
position: relative; position: relative;
} }
.risk-line { .risk-line {
@@ -143,6 +264,35 @@ export function riskGroups(
#fff 25% #fff 25%
); );
} }
.survival .risk-line {
background: linear-gradient(
to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
}
.risk-interval {
border-left: 2px solid #17324d;
border-right: 2px solid #17324d;
height: 8px;
min-width: 2px;
position: absolute;
top: 20px;
}
.risk-interval::before {
background: #17324d;
content: '';
height: 2px;
left: 0;
position: absolute;
right: 0;
top: 3px;
}
.foot {
font-size: 12px;
}
.risk-marker { .risk-marker {
background: #17324d; background: #17324d;
bottom: -2px; bottom: -2px;
@@ -169,4 +319,27 @@ export function riskGroups(
}) })
export class RiskScales { export class RiskScales {
readonly groups = input.required<RiskGroup[]>(); readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries;
protected readonly inputName = (name: string) =>
(
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
} }
+32
View File
@@ -0,0 +1,32 @@
import { parseSeries, seriesName } from './risk-series';
describe('risk series', () => {
it('reads each series and keeps an absent interval absent', () => {
const [series] = parseSeries({
resourceType: 'Parameters',
parameter: [
{
name: 'series',
part: [
{ name: 'id', valueString: 'cacu.cin2_pim' },
{ name: 'source', valueString: 'Institucional' },
{ name: 'outcome', valueString: 'CIN2+' },
{ name: 'status', valueCode: 'resolved' },
{
name: 'point',
part: [
{ name: 'years', valueInteger: 0 },
{ name: 'probability', valueDecimal: 0 },
],
},
],
},
],
});
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
'NCI, ingreso a LIEAG+',
);
});
});
+139
View File
@@ -0,0 +1,139 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import type { Parameters, ParametersParameter } from 'fhir/r4';
import { Plot } from '../plot';
import { curveFigure } from './risk-curve';
export interface SeriesPoint {
years: number;
p: number;
low?: number;
high?: number;
}
/** One series of `$risk-series`: a source, an outcome and her variables. */
export interface Series {
id: string;
source: string;
outcome: string;
label: string;
resolved: boolean;
reasons: string[];
assumptions: string[];
points: SeriesPoint[];
}
const OUTCOME_TEXT: Record<string, string> = {
'CIN2+': 'LIEAG+ (CIN2+)',
'CIN3+': 'CIN3+',
cancer: 'Cáncer',
};
export const seriesName = (s: Series) => {
const outcome = OUTCOME_TEXT[s.outcome] ?? s.outcome;
if (s.source === 'NCI (tabla de ingreso)')
return `NCI, ingreso a ${outcome.replace(' (CIN2+)', '').replace(/^Cáncer$/, 'cáncer')}`;
// the platform's own models are the hospital's: its name, and the outcome without its synonym
return s.source === 'Institucional'
? `ISSSTELEON, ${outcome.replace(' (CIN2+)', '')}`
: `${s.source} · ${outcome}`;
};
/** The series of the answer. A value absent from it stays absent. */
export function parseSeries(answer: Parameters): Series[] {
const all = (parts: ParametersParameter[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const one = (parts: ParametersParameter[] | undefined, name: string) => all(parts, name)[0];
return all(answer.parameter, 'series').map(({ part }) => ({
id: one(part, 'id')?.valueString ?? '',
source: one(part, 'source')?.valueString ?? '',
outcome: one(part, 'outcome')?.valueString ?? '',
label: one(part, 'label')?.valueString ?? '',
resolved: one(part, 'status')?.valueCode === 'resolved',
reasons: all(part, 'reason').map((r) => r.valueCode ?? ''),
assumptions: all(part, 'assumption').map((a) => a.valueString ?? ''),
points: all(part, 'point').map(({ part: at }) => ({
years: one(at, 'years')?.valueInteger ?? 0,
p: one(at, 'probability')?.valueDecimal ?? 0,
low: one(at, 'low')?.valueDecimal,
high: one(at, 'high')?.valueDecimal,
})),
}));
}
/** The chosen series as curves. Series are shown side by side; no difference is computed. */
@Component({
selector: 'app-risk-series',
imports: [MatCheckboxModule, Plot],
template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
<div class="choices">
@for (s of available(); track s.id) {
<mat-checkbox [checked]="chosen().has(s.id)" (change)="toggle(s.id)">
{{ name(s) }}
</mat-checkbox>
}
</div>
@if (selected().length) {
@for (assumption of assumptions(); track assumption) {
<p class="muted">{{ assumption }}</p>
}
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
}
@if (!available().length) {
<p class="muted">No disponible: datos insuficientes.</p>
}
`,
styles: `
:host {
display: block;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
`,
})
export class RiskSeries {
readonly series = input.required<Series[]>();
protected readonly name = seriesName;
protected readonly available = computed(() => this.series().filter((s) => s.points.length));
/** what the user toggled away from the default (the institutional series) */
private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed(
() =>
new Set(
this.available()
.filter((s) => (s.source === 'Institucional') !== this.toggled().has(s.id))
.map((s) => s.id),
),
);
protected readonly selected = computed(() =>
this.available().filter((s) => this.chosen().has(s.id)),
);
/** what the chosen series assume, each said once */
protected readonly assumptions = computed(() => [
...new Set(this.selected().flatMap((s) => s.assumptions)),
]);
protected readonly figure = computed(() => {
const shown = this.selected().map((s) => ({
model: s.id,
text: seriesName(s),
index: '',
predictions: s.points,
}));
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
const figure = curveFigure(shown, top);
// sources do not share an index date: the axis says only the horizon
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure;
});
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
}
+1 -1
View File
@@ -113,7 +113,7 @@ export function interval(from?: string, to?: string, inferred = false): string {
<span>{{ <span>{{
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha') s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
}}</span> }}</span>
@if (s.origin) { @if (s.origin && s.origin !== 'Formulario de citología') {
<span class="origin">Procedencia: {{ s.origin }}</span> <span class="origin">Procedencia: {{ s.origin }}</span>
} }
<span class="interval">Desde anterior: {{ s.previous }}</span> <span class="interval">Desde anterior: {{ s.previous }}</span>
@@ -0,0 +1,25 @@
import { combinationOf, noCurveText } from './survival-combination';
describe('combinationOf', () => {
const values = { age_group: '<30', cytology: 'NA', hpv: 'positive' };
const report = { km_combinaciones: [{ valores: values, n: 9, fallecidos: 6 }] };
it('takes only the entry with all her values, a missing one as NA', () => {
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'positive' })?.n).toBe(9);
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'negative' })).toBe(
undefined,
);
expect(combinationOf(report, { age_group: '<30' })).toBe(undefined);
expect(combinationOf({}, values)).toBe(undefined);
});
it('tells an old report apart from a combination with too few deaths', () => {
expect(noCurveText({}, undefined)).toContain('no publica esta curva');
expect(
noCurveText(
{ ...report, min_fallecidos_escenario: 5 },
{ valores: values, n: 9, fallecidos: 2 },
),
).toContain('n = 9, fallecidos = 2; mínimo requerido: 5');
});
});
+61
View File
@@ -0,0 +1,61 @@
import { Figure, PALETTE } from '../plot';
/** One entry of the survival report's `km_combinaciones`: the patients who share every value. */
export interface Combination {
valores: Record<string, string>;
n: number;
fallecidos: number;
km?: { months: number[]; S: number[]; low: number[]; high: number[] };
}
/** The entry with exactly her values (a missing one is the report's "NA"); never a partial match. */
export function combinationOf(
report: Record<string, unknown> | null | undefined,
inputs: Record<string, unknown>,
): Combination | undefined {
const all = report?.['km_combinaciones'];
return (Array.isArray(all) ? (all as Combination[]) : []).find((c) => {
const keys = Object.keys(c.valores);
return (
keys.length === Object.keys(inputs).length &&
keys.every((k) => k in inputs && c.valores[k] === String(inputs[k] ?? 'NA'))
);
});
}
/** Why there is no curve for her: these are not the same thing, so each is said apart. (A patient
* outside the survival scenario has no survival section at all.) */
export function noCurveText(
report: Record<string, unknown> | null | undefined,
found: Combination | undefined,
): string {
if (!Array.isArray(report?.['km_combinaciones']))
return 'No disponible: la versión del modelo que la evaluó no publica esta curva.';
const minimum = report['min_fallecidos_escenario'];
const counts = `n = ${found?.n ?? 0}, fallecidos = ${found?.fallecidos ?? 0}`;
return `No disponible: datos insuficientes para su combinación de valores (${counts}${
typeof minimum === 'number' ? `; mínimo requerido: ${minimum} fallecidos` : ''
}).`;
}
export function combinationFigure(km: NonNullable<Combination['km']>): Figure {
const line = (y: number[], more: object) => ({
type: 'scatter',
mode: 'lines',
x: km.months,
y,
line: { shape: 'hv', color: PALETTE[0], width: 0 },
...more,
});
return {
data: [
line(km.low, { showlegend: false, hoverinfo: 'skip' }),
line(km.high, { name: 'IC 95 %', fill: 'tonexty', fillcolor: 'rgba(23, 50, 77, 0.15)' }),
line(km.S, { name: 'Kaplan-Meier', line: { shape: 'hv', color: PALETTE[0], width: 2 } }),
],
layout: {
xaxis: { title: { text: 'Meses desde el índice' } },
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [0, 1.02], tickformat: '.0%' },
},
} as Figure;
}
+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('; ')})` : ''}.`;
}
+6 -1
View File
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
export class Plot implements OnDestroy { export class Plot implements OnDestroy {
readonly figure = input.required<Figure>(); readonly figure = input.required<Figure>();
readonly height = input(320); readonly height = input(320);
/** Plotly's buttons over the chart; a record's curves go without them */
readonly toolbar = input(true);
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host'); private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() { constructor() {
effect(() => { effect(() => {
const { data, layout } = this.figure(); const { data, layout } = this.figure();
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG); void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
...CONFIG,
...(this.toolbar() ? {} : { displayModeBar: false }),
});
}); });
} }
+1
View File
@@ -28,6 +28,7 @@ type Entity = Rejection['entity'];
type Row = Record<string, unknown>; type Row = Record<string, unknown>;
const ENTITIES: Record<Entity, string> = { const ENTITIES: Record<Entity, string> = {
cacu_eligibility_evidence: 'Evidencia de elegibilidad CaCu',
cervical_cytology: 'Citología cervical', cervical_cytology: 'Citología cervical',
cervical_biopsy: 'Biopsia cervical', cervical_biopsy: 'Biopsia cervical',
clinical_note: 'Nota médica', clinical_note: 'Nota médica',