Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a22ce12067 | |||
| a19874438b | |||
| c08a0b8874 | |||
| 5201340a13 | |||
| cca9517b7c | |||
| 3693991772 | |||
| e49dde10e7 | |||
| 2dec5af826 | |||
| 0316966374 | |||
| 3d72c153c5 | |||
| 422b408e37 | |||
| 211f02edad | |||
| 32b879edd2 | |||
| 9726d6faa3 | |||
| bafd6760d4 | |||
| 0666ce3077 | |||
| d2eada9385 | |||
| 0d458818b5 | |||
| 2970ce16b0 | |||
| a43cf4b51b | |||
| a4cc80fbe2 | |||
| 370da43695 | |||
| f7fdab950a | |||
| 1260e0ff2a | |||
| 09e5f4dd34 |
+7
-7
@@ -14,8 +14,8 @@ const TITLES = {
|
||||
cytology: 'Distribución de resultados citológicos',
|
||||
genotype: 'Resultados de VPH por genotipo',
|
||||
biopsy: 'Resultados de biopsia cervical',
|
||||
colposcopy: 'Valor predictivo positivo de la colposcopía',
|
||||
ppvBiopsy: 'Valor predictivo positivo de la biopsia',
|
||||
colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||
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 ({
|
||||
@@ -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()));
|
||||
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
|
||||
'Indicadores de oportunidad',
|
||||
'Tiempos de la ruta del tamizaje',
|
||||
'Días de la ruta del tamizaje',
|
||||
'Indicadores clínicos',
|
||||
'Resultados de citología, VPH y biopsia',
|
||||
'Distribución de resultados citológicos',
|
||||
'Resultados de VPH por genotipo',
|
||||
'Resultados de biopsia cervical',
|
||||
'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();
|
||||
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 expect(
|
||||
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)
|
||||
.click();
|
||||
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();
|
||||
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
|
||||
});
|
||||
|
||||
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
|
||||
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');
|
||||
await expect(list.first().locator('app-stages li')).toHaveCount(5);
|
||||
await list.first().getByRole('button', { name: 'Detalle' }).click();
|
||||
|
||||
+745
-31
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
|
||||
/** The record of the first patient of the risk list, as an address. */
|
||||
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
|
||||
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();
|
||||
await link.waitFor({ timeout: 120_000 });
|
||||
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 });
|
||||
}
|
||||
|
||||
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,
|
||||
}) => {
|
||||
const { url, sample } = await firstRecord(page);
|
||||
const previousDay = plus(sample, -1);
|
||||
await eligibilityIs(page, {}, 503);
|
||||
await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
|
||||
const response = await route.fetch();
|
||||
const patient = await response.json();
|
||||
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 });
|
||||
});
|
||||
@@ -136,7 +137,7 @@ test('ficha (simulado): states why a hysterectomy makes this risk assessment una
|
||||
|
||||
await open(page, url);
|
||||
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,
|
||||
}),
|
||||
).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);
|
||||
await withRisks(page, [
|
||||
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
|
||||
risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [
|
||||
[0, 0],
|
||||
[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],
|
||||
[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);
|
||||
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);
|
||||
const box = scale(page, FIVE);
|
||||
@@ -415,7 +416,7 @@ for (const width of [1440, 480]) {
|
||||
link: 'recorded',
|
||||
});
|
||||
await withRisks(page, [
|
||||
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
|
||||
risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [
|
||||
[0, 0],
|
||||
[5, 0.98, 0.95, 1],
|
||||
]),
|
||||
@@ -703,6 +704,7 @@ function fixture(
|
||||
part: [
|
||||
part('id', { valueString: 'fixture-table' }),
|
||||
part('file', { valueString: 'fixture.xlsx' }),
|
||||
part('outcome', { valueCode: 'CIN3+' }),
|
||||
],
|
||||
}),
|
||||
...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('CIN3 o más grave (CIN3+)');
|
||||
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.first()).toContainText('Inmediato (al índice)');
|
||||
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),
|
||||
);
|
||||
for (const [i, pct] of expected.entries())
|
||||
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`);
|
||||
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
|
||||
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
|
||||
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
|
||||
await expect(rows.nth(i).locator('td').nth(1)).toContainText(`${pct} %`);
|
||||
// no model evaluated her: said once, not on every horizon
|
||||
await expect(box.locator('.nomodel')).toContainText('No disponible');
|
||||
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
|
||||
const used = box.locator('details.used');
|
||||
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);
|
||||
const row = section(page).locator('tbody tr').first();
|
||||
await expect(row).toContainText('Modelo de prueba');
|
||||
const block = section(page).locator('[data-model]');
|
||||
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('IC 95 %: 0.50–2.00 %');
|
||||
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
|
||||
await expect(row.locator('td').nth(3)).toContainText('+1.00');
|
||||
await expect(row.locator('td').nth(3)).not.toContainText('No comparable');
|
||||
await expect(
|
||||
section(page).locator('table').first().locator('tbody tr').first().locator('td').nth(1),
|
||||
).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 ({
|
||||
@@ -863,15 +872,15 @@ test('referencia NCI (simulado): another outcome or horizon is "No comparable" w
|
||||
]),
|
||||
);
|
||||
await open(page, url);
|
||||
const first = section(page).locator('tbody tr').first();
|
||||
await expect(first.locator('td').nth(3)).toContainText('No comparable');
|
||||
await expect(first.locator('td').nth(3)).toContainText(
|
||||
const first = section(page).locator('[data-model] tbody tr').first();
|
||||
await expect(first.locator('td').nth(2)).toContainText('No comparable');
|
||||
await expect(first.locator('td').nth(2)).toContainText(
|
||||
'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',
|
||||
);
|
||||
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
|
||||
});
|
||||
|
||||
@@ -881,12 +890,12 @@ test('referencia NCI (simulado): a year-one reference is a year, never the immed
|
||||
const { url } = await firstRecord(page);
|
||||
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
|
||||
await open(page, url);
|
||||
const rows = section(page).locator('tbody tr');
|
||||
const rows = section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr');
|
||||
await expect(rows.first()).toContainText('1 año');
|
||||
await expect(section(page)).not.toContainText('Inmediato');
|
||||
await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado');
|
||||
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
|
||||
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %');
|
||||
await expect(rows.nth(1).locator('td').nth(1)).toContainText('No publicado');
|
||||
await expect(rows.nth(1).locator('td').nth(1)).not.toContainText('0.00');
|
||||
await expect(rows.first().locator('td').nth(1)).toContainText('1.36 %');
|
||||
});
|
||||
|
||||
for (const width of [1440, 480]) {
|
||||
@@ -929,12 +938,12 @@ for (const width of [1440, 480]) {
|
||||
),
|
||||
);
|
||||
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],
|
||||
[3, 0.21, 0.15, 0.28],
|
||||
[5, 0.34, 0.26, 0.44],
|
||||
]),
|
||||
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
|
||||
risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [
|
||||
[1, 0.002, 0.001, 0.005],
|
||||
[3, 0.008],
|
||||
[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);
|
||||
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
|
||||
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],
|
||||
[3, 0.21, 0.15, 0.28],
|
||||
[5, 0.34, 0.26, 0.44],
|
||||
]),
|
||||
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
|
||||
risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [
|
||||
[1, 0.002, 0.001, 0.005],
|
||||
[3, 0.008],
|
||||
[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');
|
||||
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
@@ -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 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 page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
||||
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
|
||||
|
||||
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 patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
|
||||
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');
|
||||
|
||||
await page.goto('/indicadores/cama');
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
||||
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
|
||||
await page.getByRole('option', { name: '12 meses' }).click();
|
||||
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 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.
|
||||
for (const domain of ['cama', 'tea']) {
|
||||
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()));
|
||||
const from = headings.indexOf('Indicadores de oportunidad');
|
||||
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).
|
||||
const drawn = await tab
|
||||
@@ -268,7 +278,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
['h2', 'h3', 'plot'].includes(i.kind),
|
||||
);
|
||||
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');
|
||||
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
|
||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
||||
|
||||
+285
@@ -292,6 +292,7 @@
|
||||
"default": "identity",
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"mammography",
|
||||
@@ -443,6 +444,7 @@
|
||||
"description": "Qu\u00e9 estudio se saca del documento.",
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"mammography",
|
||||
@@ -465,6 +467,10 @@
|
||||
"label": "Identidad de la persona",
|
||||
"value": "identity"
|
||||
},
|
||||
{
|
||||
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
|
||||
"value": "cacu_eligibility_evidence"
|
||||
},
|
||||
{
|
||||
"label": "Citolog\u00eda cervical",
|
||||
"value": "cervical_cytology"
|
||||
@@ -641,6 +647,7 @@
|
||||
"entity": {
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"mammography",
|
||||
@@ -663,6 +670,10 @@
|
||||
"label": "Identidad de la persona",
|
||||
"value": "identity"
|
||||
},
|
||||
{
|
||||
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
|
||||
"value": "cacu_eligibility_evidence"
|
||||
},
|
||||
{
|
||||
"label": "Citolog\u00eda cervical",
|
||||
"value": "cervical_cytology"
|
||||
@@ -1530,6 +1541,7 @@
|
||||
"entity": {
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"mammography",
|
||||
@@ -2117,6 +2129,7 @@
|
||||
"description": "En qu\u00e9 estudio de la plataforma se guarda.",
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"mammography",
|
||||
@@ -2139,6 +2152,10 @@
|
||||
"label": "Identidad de la persona",
|
||||
"value": "identity"
|
||||
},
|
||||
{
|
||||
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
|
||||
"value": "cacu_eligibility_evidence"
|
||||
},
|
||||
{
|
||||
"label": "Citolog\u00eda cervical",
|
||||
"value": "cervical_cytology"
|
||||
@@ -4056,6 +4073,7 @@
|
||||
"schema": {
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"mammography",
|
||||
@@ -4164,6 +4182,7 @@
|
||||
"schema": {
|
||||
"enum": [
|
||||
"identity",
|
||||
"cacu_eligibility_evidence",
|
||||
"cervical_cytology",
|
||||
"cervical_biopsy",
|
||||
"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": {
|
||||
"get": {
|
||||
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
|
||||
|
||||
@@ -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';
|
||||
@@ -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';
|
||||
@@ -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';
|
||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
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<{
|
||||
|
||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
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<{
|
||||
|
||||
@@ -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 type { ReadPatient$Params as ReadPatient$Params } 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 { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
|
||||
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
|
||||
*/
|
||||
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;
|
||||
record: string;
|
||||
value: string;
|
||||
|
||||
@@ -25,7 +25,7 @@ export interface Extract {
|
||||
/**
|
||||
* 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?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
|
||||
export interface Fhir {
|
||||
column?: string;
|
||||
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;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'fhir';
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
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;
|
||||
record: string;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ export interface Target {
|
||||
/**
|
||||
* 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;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'target';
|
||||
|
||||
@@ -10,23 +10,44 @@ interface Band {
|
||||
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>[] {
|
||||
const lines: Partial<Plotly.Data>[] = [];
|
||||
if (b.low && b.high) {
|
||||
lines.push({
|
||||
x: [...b.x, ...[...b.x].reverse()],
|
||||
y: [...b.high, ...[...b.low].reverse()] as number[],
|
||||
fill: 'toself',
|
||||
fillcolor: `${colour}33`,
|
||||
line: { width: 0 },
|
||||
hoverinfo: 'skip',
|
||||
showlegend: false,
|
||||
type: 'scatter',
|
||||
});
|
||||
for (const run of bandRuns(b)) {
|
||||
const x = run.map((i) => b.x[i]);
|
||||
lines.push({
|
||||
x: [...x, ...[...x].reverse()],
|
||||
y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
|
||||
fill: 'toself',
|
||||
fillcolor: `${colour}33`,
|
||||
line: { width: 0 },
|
||||
hoverinfo: 'skip',
|
||||
showlegend: false,
|
||||
type: 'scatter',
|
||||
});
|
||||
}
|
||||
}
|
||||
lines.push({
|
||||
x: b.x,
|
||||
y: b.y,
|
||||
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
|
||||
name,
|
||||
type: 'scatter',
|
||||
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(
|
||||
name: string,
|
||||
x: number[],
|
||||
p: { S: number[]; low: number[]; high: number[] },
|
||||
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
|
||||
): 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 {
|
||||
x,
|
||||
y: p.S,
|
||||
error_y: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
array: p.high.map((h, i) => h - p.S[i]),
|
||||
arrayminus: p.S.map((v, i) => v - p.low[i]),
|
||||
},
|
||||
y: p.S.map((v) => (finite(v) ? v : null)) as number[],
|
||||
...(errors.some((error) => error !== null)
|
||||
? {
|
||||
error_y: {
|
||||
type: 'data' as const,
|
||||
symmetric: false,
|
||||
array: errors.map((error) => error?.up ?? null) as number[],
|
||||
arrayminus: errors.map((error) => error?.down ?? null) as number[],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
name,
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
|
||||
@@ -36,28 +36,28 @@ import { Loading } from '../loading';
|
||||
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
|
||||
} @else {
|
||||
<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()!" />
|
||||
</mat-tab>
|
||||
<mat-tab label="Trazabilidad">
|
||||
<mat-tab label="Histórico">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
@if (domain() === 'cacu') {
|
||||
<mat-tab label="Análisis de riesgos">
|
||||
<mat-tab label="Seguimiento">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-riesgos [domain]="domain()" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'tea') {
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<mat-tab label="Seguimiento">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-riesgos-tea [domain]="domain()" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'cama') {
|
||||
<mat-tab label="Análisis de riesgos">
|
||||
<mat-tab label="Seguimiento">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-seguimiento [domain]="domain()" />
|
||||
</ng-template>
|
||||
|
||||
@@ -13,13 +13,14 @@ export const LAYOUTS: Record<string, Layout> = {
|
||||
'CACU_EU7',
|
||||
'CACU_EU_TIEMPO_REPORTE',
|
||||
'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||
'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
],
|
||||
route: [
|
||||
{
|
||||
label: 'Resultado de citología',
|
||||
step: 'Toma a resultado de citología',
|
||||
label: 'Días de toma de citología a resultado',
|
||||
step: 'Días de toma de citología a resultado',
|
||||
fromSample: 'CACU_EU_TIEMPO_REPORTE',
|
||||
fromStep: 'CACU_EU_TIEMPO_REPORTE',
|
||||
},
|
||||
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
|
||||
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
|
||||
},
|
||||
{
|
||||
label: 'Diagnóstico',
|
||||
label: 'Diagnóstico tras biopsia',
|
||||
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',
|
||||
},
|
||||
],
|
||||
|
||||
@@ -174,29 +174,34 @@ export const CACU: Page = {
|
||||
},
|
||||
{
|
||||
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,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
title: 'Días de tamizaje a primer diagnóstico',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||
title: 'Días de tamizaje a diagnóstico tras biopsia',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
title: 'Tiempo de tamizaje a tratamiento',
|
||||
title: 'Días de tamizaje a tratamiento',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
title: 'Tiempo de diagnóstico a tratamiento',
|
||||
title: 'Días de diagnóstico a tratamiento',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
],
|
||||
opportunity: [
|
||||
{
|
||||
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.',
|
||||
modes: [
|
||||
{
|
||||
@@ -204,10 +209,13 @@ export const CACU: Page = {
|
||||
tint: TINT,
|
||||
label: 'Acumulado desde la toma',
|
||||
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 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 +224,31 @@ export const CACU: Page = {
|
||||
label: 'Por pasos',
|
||||
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
|
||||
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: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
|
||||
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'days-by',
|
||||
kind: 'days',
|
||||
tint: TINT,
|
||||
label: 'Por CIE-10',
|
||||
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
|
||||
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
|
||||
stratum: 'diagnosis_code',
|
||||
label: 'Primer diagnóstico',
|
||||
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
|
||||
},
|
||||
{
|
||||
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 +283,10 @@ export const CACU: Page = {
|
||||
catalog: HPV,
|
||||
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 +312,7 @@ export const CACU: Page = {
|
||||
label: 'Colposcopía',
|
||||
section: ppv(
|
||||
'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.',
|
||||
),
|
||||
},
|
||||
@@ -297,7 +320,7 @@ export const CACU: Page = {
|
||||
label: 'Biopsia',
|
||||
section: ppv(
|
||||
'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.',
|
||||
{
|
||||
kind: 'counts',
|
||||
|
||||
@@ -263,16 +263,16 @@ export const PAGES: Record<string, Page> = {
|
||||
},
|
||||
{
|
||||
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,
|
||||
},
|
||||
{
|
||||
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,
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de diagnóstico a tratamiento',
|
||||
title: 'Días de diagnóstico a tratamiento',
|
||||
value: 'Indicador no disponible',
|
||||
note: PENDING,
|
||||
},
|
||||
@@ -280,12 +280,12 @@ export const PAGES: Record<string, Page> = {
|
||||
opportunity: [
|
||||
{
|
||||
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
|
||||
sample: [
|
||||
{ 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',
|
||||
},
|
||||
],
|
||||
@@ -476,22 +476,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',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
title: 'Días de tamizaje a primer diagnóstico',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
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',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de diagnóstico a tratamiento',
|
||||
title: 'Días de diagnóstico a tratamiento',
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
|
||||
@@ -33,10 +33,10 @@ interface Drawn {
|
||||
</mat-button-toggle-group>
|
||||
</section>
|
||||
@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()) {
|
||||
<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>
|
||||
</p>
|
||||
} @else {
|
||||
|
||||
@@ -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' });
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -121,13 +121,6 @@
|
||||
}
|
||||
<div data-section="etapas">
|
||||
<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>
|
||||
}
|
||||
<table class="plain">
|
||||
@@ -253,66 +246,66 @@
|
||||
</mat-card>
|
||||
}
|
||||
|
||||
<mat-card appearance="outlined" class="wide">
|
||||
<mat-card-header
|
||||
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
|
||||
>
|
||||
<mat-card appearance="outlined" class="wide" data-section="riesgos">
|
||||
<mat-card-content>
|
||||
@if (riskExclusion(); as reason) {
|
||||
<p role="status">{{ reason }}</p>
|
||||
} @else {
|
||||
<app-risk-scales [groups]="groups()" />
|
||||
@if (reference.value(); as ref) {
|
||||
<app-reference-risk [view]="ref" />
|
||||
}
|
||||
}
|
||||
@if (models().length) {
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<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>
|
||||
<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>
|
||||
@if (riskModels().length) {
|
||||
<details data-section="modelos">
|
||||
<summary>Modelos y valores</summary>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Modelo</th>
|
||||
<th>Fecha índice</th>
|
||||
<th>Horizonte</th>
|
||||
<th>Probabilidad</th>
|
||||
<th>IC 95 %</th>
|
||||
</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>
|
||||
</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>
|
||||
<ul class="curve-text">
|
||||
@for (t of curveText(); track $index) {
|
||||
<li>{{ t }}</li>
|
||||
}
|
||||
</ul>
|
||||
<app-plot [figure]="curve()" [height]="300" />
|
||||
@if (riskSeries.value()?.length) {
|
||||
<app-risk-series [series]="riskSeries.value()!" />
|
||||
} @else {
|
||||
<app-plot [figure]="curve()" [height]="300" />
|
||||
}
|
||||
</details>
|
||||
} @else if (!riskExclusion()) {
|
||||
}
|
||||
@if (!riskModels().length && !riskExclusion()) {
|
||||
<p class="muted">Sin evaluación de un modelo en producción.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
@if (domain() === 'tea') {
|
||||
<mat-card appearance="outlined" class="wide" data-section="tea">
|
||||
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
|
||||
@@ -560,13 +553,19 @@
|
||||
</mat-card-content>
|
||||
</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-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>
|
||||
<h3>Análisis de supervivencia</h3>
|
||||
@if (survival.isLoading()) {
|
||||
<app-loading what="las curvas de supervivencia" [figure]="true" />
|
||||
} @else if (domain() === 'cacu') {
|
||||
<p class="muted">No disponible: el informe no contiene la curva para esta combinación.</p>
|
||||
} @else if (survival.value(); as s) {
|
||||
<h3>Escenario clínico de la paciente</h3>
|
||||
<ul class="scenarios">
|
||||
@@ -574,17 +573,46 @@
|
||||
<li>{{ name }}</li>
|
||||
}
|
||||
</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) {
|
||||
<h4>{{ f.title }}</h4>
|
||||
<app-plot [figure]="f.figure" [height]="340" />
|
||||
} @empty {
|
||||
<p class="muted">
|
||||
Sus escenarios no tienen fallecimientos suficientes para trazar curvas.
|
||||
}
|
||||
@for (name of s.unavailable; track name) {
|
||||
<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>
|
||||
}
|
||||
<app-factores [rows]="s.factors" />
|
||||
} @else if (survival.error()) {
|
||||
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
||||
} @else {
|
||||
<p class="muted" data-state="sin-informe">
|
||||
@if (domain() === 'cacu') {
|
||||
No disponible: no hay un informe de supervivencia para los escenarios de la
|
||||
paciente.
|
||||
} @else {
|
||||
No disponible: datos insuficientes.
|
||||
}
|
||||
</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
@@ -13,6 +13,8 @@ import type {
|
||||
RiskAssessment,
|
||||
} from 'fhir/r4';
|
||||
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 { study as eegStudy } from '../api/fn/eeg/study';
|
||||
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||
@@ -25,10 +27,12 @@ import { HttpClient } from '@angular/common/http';
|
||||
import type { Parameters as FhirParameters } from 'fhir/r4';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { ANTECEDENTS, Fact, group, split } from './record-groups';
|
||||
import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk';
|
||||
import { curveFigure, curveText } from './risk-curve';
|
||||
import { riskGroups, riskScales, RiskScales } from './risk-scales';
|
||||
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
|
||||
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
|
||||
import { ineligibility } from './ineligibility';
|
||||
import { parseSeries, RiskSeries, Series } from './risk-series';
|
||||
import { curveFigure } from './risk-curve';
|
||||
import { isRiskModel, riskGroups, riskScales, RiskScales } from './risk-scales';
|
||||
import { route, Stages } from './stages';
|
||||
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
|
||||
import { LABELS, name, PRIORITY } from '../indicadores/measures';
|
||||
@@ -69,6 +73,12 @@ function facts(observations: Observation[]): Fact[] {
|
||||
|
||||
/** One patient: her history (conditions, procedures), her tests and results, and the
|
||||
* 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))];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente',
|
||||
imports: [
|
||||
@@ -81,7 +91,7 @@ function facts(observations: Observation[]): Fact[] {
|
||||
RouterLink,
|
||||
Plot,
|
||||
RiskScales,
|
||||
ReferenceRisk,
|
||||
RiskSeries,
|
||||
Stages,
|
||||
],
|
||||
templateUrl: './paciente.html',
|
||||
@@ -148,14 +158,20 @@ export class Paciente {
|
||||
});
|
||||
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
|
||||
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(() => {
|
||||
if (this.domain() !== 'cacu') return undefined;
|
||||
const patient = this.patient();
|
||||
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
|
||||
const sample = this.citologia()?.slice(0, 10);
|
||||
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
|
||||
? `Sin estimación de riesgo por antecedente de histerectomía registrado el ${recorded}.`
|
||||
? `No disponible por: histerectomía registrada el ${recorded}.`
|
||||
: undefined;
|
||||
});
|
||||
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
|
||||
@@ -166,40 +182,64 @@ export class Paciente {
|
||||
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
|
||||
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) => isRiskModel(m.model)));
|
||||
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`). */
|
||||
protected readonly groups = computed(() =>
|
||||
this.domain() === 'cacu' ? riskGroups(this.models()) : [],
|
||||
this.domain() === 'cacu' ? riskGroups(this.riskModels()) : [],
|
||||
);
|
||||
/** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API
|
||||
* answers 404 while the feature is off: then nothing is shown. */
|
||||
protected readonly reference = resource({
|
||||
/** CaCu, experimental: the series her record can compare; none while the API has it off. */
|
||||
protected readonly riskSeries = resource({
|
||||
params: () =>
|
||||
this.domain() === 'cacu'
|
||||
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
|
||||
: undefined,
|
||||
loader: async ({ params }): Promise<ReferenceView | undefined> => {
|
||||
loader: async ({ params }): Promise<Series[] | undefined> => {
|
||||
try {
|
||||
const answer = await firstValueFrom(
|
||||
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(
|
||||
Object.entries({ cutoff: params.cutoff, sample: params.sample }).filter(
|
||||
([, v]) => !!v,
|
||||
),
|
||||
) as Record<string, string>,
|
||||
Object.entries({
|
||||
cutoff: params.cutoff,
|
||||
sample: params.sample?.slice(0, 10),
|
||||
}).filter((e): e is [string, string] => !!e[1]),
|
||||
),
|
||||
},
|
||||
),
|
||||
);
|
||||
return referenceView(answer);
|
||||
return parseSeries(answer);
|
||||
} catch {
|
||||
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 saveError = signal('');
|
||||
/** CaCu: her record as a PDF. */
|
||||
@@ -236,14 +276,15 @@ export class Paciente {
|
||||
protected readonly tests = computed(() => {
|
||||
const d = this.data.value();
|
||||
if (!d) return [];
|
||||
return d.reports.map((r) => {
|
||||
return d.reports.flatMap((r) => {
|
||||
const results = (r.result ?? [])
|
||||
.map((x) => d.observations.get(x.reference?.split('/')[1]))
|
||||
.filter((o) => !!o) as Observation[];
|
||||
// the study's own results; the form's antecedents are in their own section and the extra
|
||||
// findings are collapsed (record-groups)
|
||||
const found = group(facts(results));
|
||||
return {
|
||||
const { hpv, rest } = hpvApart(facts(results));
|
||||
const found = group(rest);
|
||||
const row = {
|
||||
date: r.effectiveDateTime ?? '',
|
||||
reported: ext(r, 'report-date')?.valueDate,
|
||||
kind: label(r.code),
|
||||
@@ -251,6 +292,10 @@ export class Paciente {
|
||||
results: found.results,
|
||||
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
|
||||
@@ -345,6 +390,10 @@ export class Paciente {
|
||||
return {
|
||||
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
|
||||
scenarios: m.scenarios,
|
||||
unavailable: [] as string[],
|
||||
insufficient: [] as Insufficient[],
|
||||
missing: [] as string[],
|
||||
methods: [] as string[],
|
||||
figures: mine(r['escenarios'] ?? []).map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
|
||||
@@ -355,17 +404,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 {
|
||||
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
|
||||
scenarios: m.scenarios,
|
||||
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
|
||||
e,
|
||||
e.horizons_months,
|
||||
'Supervivencia S(t)',
|
||||
),
|
||||
),
|
||||
figures,
|
||||
// her scenarios the report draws no curve for
|
||||
unavailable: domain === 'cacu' ? [] : undrawn,
|
||||
insufficient,
|
||||
missing,
|
||||
methods: methods(figures),
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -479,11 +540,14 @@ export class Paciente {
|
||||
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
|
||||
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
|
||||
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
|
||||
protected readonly curve = computed<Figure>(() => curveFigure(this.models(), this.top()));
|
||||
protected readonly curveText = computed(() => curveText(this.models()));
|
||||
protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
|
||||
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 levelNames = LEVEL_NAMES;
|
||||
protected readonly identity = computed(() => {
|
||||
|
||||
@@ -46,3 +46,11 @@ export function group(facts: Fact[]) {
|
||||
}
|
||||
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)) };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 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']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
|
||||
/** The states a resolution ends in, as the screens say them. */
|
||||
@@ -205,6 +205,86 @@ export function referenceView(answer: Parameters): ReferenceView {
|
||||
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> = {
|
||||
match: 'coincide con la tabla del NCI',
|
||||
'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>
|
||||
</div>
|
||||
}
|
||||
<div>
|
||||
<dt>Desenlace</dt>
|
||||
<dd>CIN3 o más grave (CIN3+)</dd>
|
||||
</div>
|
||||
@if (v.source?.outcome; as out) {
|
||||
<div>
|
||||
<dt>Desenlace de la referencia</dt>
|
||||
<dd [attr.data-outcome]="out">{{ outcomeText(out) }}</dd>
|
||||
</div>
|
||||
}
|
||||
@if (v.evaluationDate ?? v.index?.sampleDate; as day) {
|
||||
<div>
|
||||
<dt>Fecha de evaluación</dt>
|
||||
@@ -269,68 +351,112 @@ const OFFICIAL: Record<string, string> = {
|
||||
</ul>
|
||||
}
|
||||
@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>
|
||||
<tr>
|
||||
<th>Horizonte</th>
|
||||
<th>Modelo institucional</th>
|
||||
<th>Referencia NCI</th>
|
||||
<th>Diferencia (puntos porcentuales)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (h of v.horizons; track h.years) {
|
||||
@for (c of h.comparisons.length ? h.comparisons : [none]; track $index) {
|
||||
<tr [attr.data-years]="h.years">
|
||||
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
|
||||
<td class="model" data-label="Modelo institucional">
|
||||
@if (c.model) {
|
||||
<strong>{{ c.title }}</strong>
|
||||
<span class="muted">{{ c.outcome }}</span>
|
||||
}
|
||||
@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 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>
|
||||
}
|
||||
@for (h of g.reference; track h.years) {
|
||||
<tr [attr.data-years]="h.years">
|
||||
<td class="nowrap" data-label="Horizonte">{{ h.label }}</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>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</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">
|
||||
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).
|
||||
@@ -406,6 +532,7 @@ const OFFICIAL: Record<string, string> = {
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
table-layout: fixed;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
@@ -413,9 +540,18 @@ const OFFICIAL: Record<string, string> = {
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.model strong,
|
||||
.model .muted {
|
||||
display: block;
|
||||
.model {
|
||||
border-top: 1px solid #dce3e7;
|
||||
margin-top: 8px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
h4,
|
||||
h5 {
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
h5 .muted {
|
||||
font-weight: 400;
|
||||
margin-left: 8px;
|
||||
}
|
||||
.why {
|
||||
margin: 4px 0;
|
||||
@@ -463,10 +599,10 @@ const OFFICIAL: Record<string, string> = {
|
||||
})
|
||||
export class ReferenceRisk {
|
||||
readonly view = input.required<ReferenceView>();
|
||||
protected readonly none: ComparisonView = {
|
||||
status: 'not_comparable',
|
||||
reasons: ['no_institutional_model'],
|
||||
};
|
||||
protected readonly grouped = computed(() => groupReference(this.view()));
|
||||
protected outcomeText(outcome?: string) {
|
||||
return outcomeText(outcome);
|
||||
}
|
||||
protected statusText(status: string) {
|
||||
return STATUS_TEXT[status] ?? status;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { horizon, riskGroups, riskScales } from './risk-scales';
|
||||
import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales';
|
||||
|
||||
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: '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']);
|
||||
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);
|
||||
@@ -60,3 +60,27 @@ 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,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,11 @@ export interface RiskScale {
|
||||
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. */
|
||||
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
|
||||
return models.flatMap((m) =>
|
||||
@@ -41,6 +46,7 @@ export function horizon(predictions: Prediction[], years: number): Prediction |
|
||||
export interface RiskGroup {
|
||||
/** the model's own title and the day it was scored (none: no model has scored her) */
|
||||
title?: string;
|
||||
scenario?: string;
|
||||
index?: string;
|
||||
scales: { label: string; risk?: Prediction }[];
|
||||
}
|
||||
@@ -50,6 +56,12 @@ const HORIZONS: [number, string][] = [
|
||||
[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
|
||||
* unavailable. */
|
||||
export function riskGroups(
|
||||
@@ -58,7 +70,11 @@ export function riskGroups(
|
||||
const scales = (predictions: Prediction[]) =>
|
||||
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
|
||||
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,
|
||||
scales: scales(m.predictions),
|
||||
}))
|
||||
: [{ scales: scales([]) }];
|
||||
}
|
||||
|
||||
@@ -74,7 +90,7 @@ export function riskGroups(
|
||||
}
|
||||
@for (g of groups(); track $index) {
|
||||
@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) {
|
||||
<div class="risk-scale" [attr.data-scale]="s.label">
|
||||
@@ -82,9 +98,7 @@ export function riskGroups(
|
||||
<strong>{{ s.label }}</strong>
|
||||
@if (s.risk; as r) {
|
||||
@if (r.low !== undefined && r.high !== undefined) {
|
||||
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{
|
||||
r.high * 100 | number: '1.1-2'
|
||||
}}
|
||||
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }}
|
||||
%
|
||||
}
|
||||
} @else {
|
||||
@@ -94,6 +108,14 @@ export function riskGroups(
|
||||
<div class="risk-plot" [class.unavailable]="!s.risk">
|
||||
<div class="risk-line" aria-hidden="true"></div>
|
||||
@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>
|
||||
<strong
|
||||
class="risk-value"
|
||||
@@ -107,6 +129,11 @@ export function riskGroups(
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (g.index) {
|
||||
<p class="muted foot">
|
||||
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
|
||||
</p>
|
||||
}
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
@@ -121,7 +148,7 @@ export function riskGroups(
|
||||
margin: 0;
|
||||
}
|
||||
.risk-plot {
|
||||
padding-top: 24px;
|
||||
padding-top: 30px;
|
||||
position: relative;
|
||||
}
|
||||
.risk-line {
|
||||
@@ -143,6 +170,26 @@ export function riskGroups(
|
||||
#fff 25%
|
||||
);
|
||||
}
|
||||
.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 {
|
||||
background: #17324d;
|
||||
bottom: -2px;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
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('Institucional · LIEAG+ (CIN2+)');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
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) => `${s.source} · ${OUTCOME_TEXT[s.outcome] ?? s.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 (s of selected(); track s.id) {
|
||||
@for (assumption of s.assumptions; track assumption) {
|
||||
<p class="muted">{{ name(s) }}: {{ assumption }}</p>
|
||||
}
|
||||
}
|
||||
<app-plot [figure]="figure()" [height]="340" />
|
||||
}
|
||||
@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)),
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -113,7 +113,7 @@ export function interval(from?: string, to?: string, inferred = false): string {
|
||||
<span>{{
|
||||
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
|
||||
}}</span>
|
||||
@if (s.origin) {
|
||||
@if (s.origin && s.origin !== 'Formulario de citología') {
|
||||
<span class="origin">Procedencia: {{ s.origin }}</span>
|
||||
}
|
||||
<span class="interval">Desde anterior: {{ s.previous }}</span>
|
||||
|
||||
@@ -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.');
|
||||
});
|
||||
});
|
||||
@@ -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('; ')})` : ''}.`;
|
||||
}
|
||||
@@ -28,6 +28,7 @@ type Entity = Rejection['entity'];
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const ENTITIES: Record<Entity, string> = {
|
||||
cacu_eligibility_evidence: 'Evidencia de elegibilidad CaCu',
|
||||
cervical_cytology: 'Citología cervical',
|
||||
cervical_biopsy: 'Biopsia cervical',
|
||||
clinical_note: 'Nota médica',
|
||||
|
||||
Reference in New Issue
Block a user