Compare commits

..

63 Commits

Author SHA1 Message Date
edgar 22edb0bf42 Marcar la curva NCI de CIN3+ y quitar la nota de que las series no se restan 2026-12-04 17:21:42 -06:00
edgar c128448317 Decir que la paciente ya fue tratada y nombrar el grado de la citología de referencia 2026-12-04 16:47:40 -06:00
edgar c28cf31e2a Mostrar solo el criterio de exclusión y anotar que el tamizaje es el actual 2026-12-04 16:02:40 -06:00
edgar f6dffb6dc2 Mostrar las referencias de los indicadores y del NCI 2026-12-04 16:02:40 -06:00
edgar 1820b8ce2b Mostrar el criterio de exclusión de los escenarios que no se evalúan 2026-12-04 12:47:07 -06:00
edgar 1abfc27013 Mostrar CIN 2 y CIN 3 en las gráficas de biopsia 2026-12-04 09:12:15 -06:00
edgar e31c128991 Nombrar la detección anterior y encadenar los tiempos de CaMa hasta el tratamiento 2026-12-04 05:49:56 -06:00
edgar 972bdf0d8a Separar la ronda subsecuente por última detección y encadenar los tiempos por paso 2026-12-04 05:38:07 -06:00
edgar 7167426283 Mostrar en español los tipos histológicos de mama 2026-12-04 04:42:24 -06:00
edgar cbc41ca365 Dibujar la ronda subsecuente por última detección y conectar diagnóstico a tratamiento de CaMa 2026-12-04 01:23:41 -06:00
edgar 94c3bb6d82 Restituir el desglose de la ronda subsecuente y sangrar las citologías anormales 2026-12-04 00:50:27 -06:00
edgar 72aa91af04 CaMa: tipo histológico, BI-RADS 4-6 primero y detección en el histórico 2026-12-03 23:47:37 -06:00
edgar 2a84eb56ca Agrupar las tarjetas de CaMa y elegir el periodo en Trazabilidad 2026-12-03 22:21:59 -06:00
edgar 84769cb0f4 Volver a nombrar como tiempos los indicadores de oportunidad 2026-12-03 20:09:50 -06:00
edgar cbcb524902 Ajustar indicadores, fecha de corte y ficha de CaMa y CaCu 2026-12-03 19:33:13 -06:00
edgar 0fe772ed6f Describir los motivos de exclusión de la referencia 2026-12-03 17:12:03 -06:00
Angel Capetillo Zavala 63f6e16d19 Clarify CaCu and CaMa chart labels 2026-12-03 15:18:22 -06:00
Angel Capetillo Zavala d38c795c8a Hide the CaMa diagnosis-to-treatment card until the indicator is defined
The card read "Indicador no disponible" and the route listed a step with no
measure. Both are removed from the CaMa summary, and the opportunity grid sizes
its columns to the cards it has so the remaining ones fill the row.
2026-12-03 11:00:55 -06:00
Angel Capetillo Zavala 3bff3d5e3f Añadir exportaciones de CaMa y conservar los filtros aplicados 2026-12-03 10:23:42 -06:00
edgar 4ec071332d Usar un solo selector de curvas para riesgo y supervivencia 2026-12-03 07:31:12 -06:00
edgar 5a82dc780e Elegir los ajustes de supervivencia que se comparan 2026-12-03 07:30:01 -06:00
edgar db74a19439 Dibujar todos los ajustes de supervivencia en la ficha 2026-12-03 07:28:48 -06:00
edgar 24415b79b6 Quitar la barra de Plotly en las curvas de la ficha 2026-12-03 00:24:50 -06:00
edgar b43c89befd Decir una sola vez el supuesto de la referencia NCI 2026-12-03 00:18:28 -06:00
edgar 9c17a383d1 Usar barras comunes en confirmación y renombrar la serie de ingreso del NCI 2026-12-03 00:06:32 -06:00
edgar 8e16de33b7 Mostrar tabla de valores de supervivencia 2026-12-02 23:44:28 -06:00
edgar 5d660b7043 Mostrar confirmación con intervalo en barra y ajustar etiquetas de la ficha 2026-12-02 23:43:18 -06:00
edgar a3a100450b Mostrar supervivencia con su curva de combinación y métodos por estimación 2026-12-02 23:20:51 -06:00
edgar a92515eb4d Mostrar factores usados en cada estimación 2026-12-02 23:13:59 -06:00
edgar 5f92c49ed4 Mostrar escalas de supervivencia publicadas 2026-12-02 23:00:06 -06:00
edgar a22ce12067 Mostrar solo curvas de probabilidad disponibles 2026-12-02 22:53:44 -06:00
edgar a19874438b Ajustar resumen y ocultar series no disponibles 2026-12-02 22:50:30 -06:00
edgar c08a0b8874 Ajustar pestañas y etiquetas de días 2026-12-02 21:54:54 -06:00
edgar 5201340a13 Aclarar etiquetas de días en indicadores CaCu 2026-12-02 21:50:01 -06:00
edgar cca9517b7c Conservar la exclusión por histerectomía cuando la API no la reporta 2026-12-02 20:26:14 -06:00
edgar 3693991772 Renombrar tasas de confirmación histopatológica 2026-12-02 20:23:32 -06:00
edgar e49dde10e7 Distinguir diagnósticos en la ruta de tamizaje 2026-12-02 20:19:36 -06:00
edgar 2dec5af826 Distinguir tiempos de diagnóstico en indicadores 2026-12-02 20:19:36 -06:00
edgar 0316966374 Ajustar la prueba de las escalas al título sin versión 2026-12-02 19:43:55 -06:00
edgar 3d72c153c5 Ficha: quitar la nota de las etapas de la citología 2026-12-02 19:42:55 -06:00
edgar 422b408e37 Ficha: quitar la procedencia del formulario de citología 2026-12-02 19:42:53 -06:00
edgar 211f02edad Ficha: mostrar el VPH como estudio aparte 2026-12-02 19:42:51 -06:00
edgar 32b879edd2 Ficha: mostrar la tabla de modelos como desplegable 2026-12-02 19:42:48 -06:00
edgar 9726d6faa3 Ficha: quitar el texto de las curvas de probabilidad 2026-12-02 19:42:46 -06:00
edgar bafd6760d4 Ficha: llevar la comparación y sus filtros a las curvas de probabilidad 2026-12-02 19:42:43 -06:00
edgar 0666ce3077 Ficha: no mostrar la comparación de riesgos de referencia 2026-12-02 19:42:41 -06:00
edgar d2eada9385 Ficha: titular cada riesgo por su desenlace y llevar el escenario al pie 2026-12-02 19:42:38 -06:00
edgar 0d458818b5 Ficha: dibujar el intervalo sobre la escala y llevar la fecha índice al pie 2026-12-02 19:42:36 -06:00
edgar 2970ce16b0 Ficha: quitar el título Riesgos y recomendaciones 2026-12-02 19:42:33 -06:00
Angel Capetillo Zavala a43cf4b51b Distinguir ausencias e insuficiencia en supervivencia CaCu 2026-12-02 19:26:50 -06:00
edgar a4cc80fbe2 Mostrar la elegibilidad CaCu solo cuando la paciente no es elegible 2026-12-02 19:04:00 -06:00
Angel Capetillo Zavala 370da43695 Agregar elegibilidad CaCu por escenario clínico 2026-12-02 18:47:09 -06:00
edgar f7fdab950a Comparar series de riesgo seleccionables en la ficha CaCu 2026-12-02 18:24:33 -06:00
edgar 1260e0ff2a Mostrar métodos y escenarios sin curva en la supervivencia de la ficha 2026-12-02 18:14:19 -06:00
Angel Capetillo Zavala 09e5f4dd34 CaCu record: grouped NCI comparison, Spanish outcome names, survival texts and risk-only scales
The NCI comparison shows the reference once per horizon and one block per model, saying the
reasons that every incompatible comparison shares only once. Outcome names are translated for
display only (the API identifiers stay), and the reference outcome is read from the answer.
The CaCu survival card is titled as survival and states that its curves estimate the clinical
scenario's group, not an individual. Survival and recurrence estimates no longer feed the risk
scales, curves, probability table or PDF.
2026-12-02 17:48:03 -06:00
Angel Capetillo Zavala f119ba048a Simplify CaCu distribution descriptions 2026-12-02 14:09:02 -06:00
edgar 9ae8254dee Mostrar el motivo de exclusión en la ficha CaCu 2026-12-02 09:35:25 -06:00
Angel Capetillo Zavala b9e210d825 Merge the CaMa diagnostic pathway and biopsy results into the CaCu rounds, record and risk work 2026-12-01 19:02:02 -06:00
Angel Capetillo Zavala 652fd45c29 CaCu record: the NCI reference comparison section and probability curves at the published horizons 2026-12-01 18:32:11 -06:00
Angel Capetillo Zavala 8fc06038fb CaCu record: stages with states and sources, segmented risk scales, antecedents and collapsible findings 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala e1e8da6093 CaCu indicators: one selector for the cytology and HPV genotype views, grouped bars and genotype labels 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala 81894a3777 CaCu: show screening rounds and restore category palettes 2026-12-01 14:22:23 -06:00
Angel Capetillo Zavala 749afe765d CaMa: present diagnostic pathway and biopsy results 2026-12-01 12:27:16 -06:00
112 changed files with 10725 additions and 5247 deletions
+280 -53
View File
@@ -1,10 +1,23 @@
import { expect, test } from '@playwright/test'; import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
test.beforeEach(async ({ page }) => { test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' }; const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204); expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
}); });
const ROUND = { name: 'Por detección inicial y subsecuente' };
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
const VIEWS = ['General', 'Por grupo de edad', ROUND.name];
const TITLES = {
cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical',
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 ({ test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page, page,
}) => { }) => {
@@ -26,66 +39,75 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
'Indicadores de oportunidad', 'Indicadores de oportunidad',
'Tiempos de tamizaje', 'Tiempos de tamizaje',
]); ]);
// one selector reads both the cytology and the HPV card by group const route = tab.locator('app-readings').filter({ has: page.getByRole('heading', { name: 'Tiempos de tamizaje' }) });
await tab.getByRole('radio', { name: 'Por detección inicial y anterior' }).first().click(); for (const mode of ['Por ventana de tiempo', 'Diagnóstico precolposcópico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
for (const card of ['Distribución de resultados citológicos', 'Resultados de VPH por genotipo'])
await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: card }) })
.locator('section.group')
.first(),
).toBeVisible();
const route = tab.locator('app-readings').last();
for (const mode of [
'Por ventana de tiempo',
'Diagnóstico precolposcópico',
'Diagnóstico tras biopsia',
'Acumulado desde la toma',
]) {
await route.getByRole('radio', { name: mode }).click(); await route.getByRole('radio', { name: mode }).click();
await expect( await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')), route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible(); ).toBeVisible();
} }
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click(); // one selector for the cytology distribution and the HPV by genotype; the biopsy card is apart
await expect( await expect(
tab.getByRole('heading', { tab.locator('app-readings', {
name: 'Tasa de confirmación histopatológica de referencia a biopsia', has: page.getByRole('heading', { name: 'Pacientes evaluadas por resultado de VPH' }),
}), }),
).toBeVisible(); ).toHaveCount(0);
}); const views = tab.getByRole('radiogroup', { name: VIEWS_LABEL });
await expect(views.getByRole('radio')).toHaveText(VIEWS);
test('indicadores cama: its sections in order, the route chained and the types by BI-RADS', async ({ await expect(views.getByRole('radio', { name: 'General' })).toBeChecked();
page, await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
}) => { for (const view of VIEWS.slice(1)) {
await page.goto('/indicadores/cama'); await views.getByRole('radio', { name: view }).click();
const tab = page.locator('app-tab-indicadores'); for (const card of [TITLES.cytology, TITLES.genotype]) {
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); const readings = tab.locator('app-readings', {
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); has: page.getByRole('heading', { name: card }),
const headings = await tab });
.locator('h2, h3') // each card has no toggle of its own: the selector drives both
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); await expect(readings.getByRole('radio')).toHaveCount(0);
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([ // no long description beside the bars: the cards read from their title, note and legend
'Indicadores de oportunidad', await expect(readings).not.toContainText(
'Pacientes evaluadas con BI-RADS 4, 5 o 6', /Cada barra|Cada paciente cuenta una vez|«Detección inicial»|una barra vacía|«Positivo»/,
'Tiempo de toma de mastografía a interpretación radiológica', );
'Tiempo de interpretación radiológica a diagnóstico', await expect(
'Tiempo de interpretación radiológica a resultado de biopsia', readings
'Tiempo de diagnóstico tras biopsia a tratamiento', .locator('.group')
'Tiempo de tamizaje a diagnóstico', .first()
'Tiempo de tamizaje a diagnóstico y tratamiento', .or(readings.getByText(/No disponible|Sin datos en el periodo/)),
'Indicadores clínicos', ).toBeVisible();
expect.stringMatching(/^Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en /), }
expect.stringMatching(/^Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en /), }
'Tipo histológico por categoría BI-RADS', const biopsyCard = tab.locator('app-readings', {
'Confirmación histopatológica', has: page.getByRole('heading', { name: TITLES.biopsy }),
]);
const types = tab.locator('app-readings', {
has: page.getByRole('heading', { name: 'Tipo histológico por categoría BI-RADS' }),
}); });
await expect(types.getByRole('columnheader', { name: '% maligno' })).toBeVisible(); await expect(biopsyCard.getByRole('radio')).toHaveCount(0);
await tab.getByRole('radio', { name: 'Mastografías con biopsia' }).click(); await views.getByRole('radio', { name: 'General' }).click();
await expect(tab.getByRole('table', { name: 'Con y sin biopsia' })).toBeVisible(); await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: TITLES.cytology }) })
.getByRole('table'),
).toBeVisible();
// the PPV cards keep their round tab, in the same words and order
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.colposcopy }),
});
await colposcopy.getByRole('radio', ROUND).click();
await expect(
colposcopy
.getByRole('table', ROUND)
.or(colposcopy.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.ppvBiopsy }),
})
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible();
await expect(tab.getByRole('radio', { name: 'Solicitudes' })).toHaveCount(0);
}); });
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => { test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
@@ -114,3 +136,208 @@ test('riesgos cacu: ages filter the whole list and a row opens its stages', asyn
await page.getByRole('button', { name: 'Exportar PDF' }).click(); await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf'); expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
}); });
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried on top of the API's own answers. They show how the page draws them, not the
// backend. The shared selector drives the cytology and the HPV-by-genotype cards; the PPV cards keep a tab.
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
const GENOTYPE_COLOURS = {
Negativo: '#42A77E',
'VPH 16': '#DF8640',
'VPH 18': '#C29C42',
'VPH 16 y 18': '#C24269',
Positivo: '#A8C243',
};
const CYTOLOGY_COLOURS = {
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const view = async (name: string) => {
await tab.getByRole('radiogroup', { name: VIEWS_LABEL }).getByRole('radio', { name }).click();
};
/** A PPV card on its round tab. */
const ppv = async (key: 'colposcopy' | 'ppvBiopsy') => {
await tab
.getByRole('radio', { name: key === 'colposcopy' ? 'Colposcopía' : 'Biopsia', exact: true })
.click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, card, view, ppv };
}
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first();
/** The groups of a card as the page draws them: "label<br>unit: N", the width of the first bar and the colour of
* each category (the first group's rows), in hex. */
const traces = (readings: Locator) =>
readings.evaluate((el) => {
const hex = (rgb: string) =>
'#' +
(rgb.match(/\d+/g) ?? [])
.slice(0, 3)
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const groups = [...el.querySelectorAll('.group')];
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>${g.querySelector('.n')!.textContent!.trim()}`,
),
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries(
[...groups[0].querySelectorAll('.row')].map((r) => [
r.querySelector('.name')!.textContent!.trim(),
hex(getComputedStyle(r.querySelector('.fill')!).backgroundColor),
]),
),
};
});
for (const key of ['colposcopy', 'ppvBiopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'as-is');
const readings = await ppv(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'no-initial');
const readings = await ppv(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'unpublished');
const readings = await ppv(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
for (const card of ['cytology', 'genotype'] as const) {
test(`rondas (simulado) ${card}: the selector draws the rounds in order, with the category colours`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'as-is');
await view(ROUND.name);
const readings = of(TITLES[card]);
await expect(plotOf(readings)).toBeVisible();
const found = await traces(readings);
expect(found.y.map((l) => l.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(found.colours).toMatchObject(card === 'cytology' ? CYTOLOGY_COLOURS : GENOTYPE_COLOURS);
});
test(`rondas (simulado) ${card}: an empty initial group is an empty bar with its zero`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name);
const found = await traces(of(TITLES[card]));
expect(found.y[0]).toBe('Detección inicial<br>Pacientes: 0');
expect(found.x[0]).toBe(0);
});
test(`rondas (simulado) ${card}: without the stratum the selector says it is not available`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'unpublished');
await view(ROUND.name);
await expect(of(TITLES[card])).toContainText('No disponible');
});
}
test('rondas (simulado): the genotype card never shows the incomplete positives, and carries no long description', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).not.toContainText('«Positivo»');
await expect(readings).not.toContainText('Cada barra');
await expect(readings.getByRole('rowheader')).not.toContainText([
'Otro de alto riesgo',
'incompleto',
]);
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim())).toEqual([
'Negativo',
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo sin genotipo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
const found = await traces(readings);
expect(Object.keys(found.colours)).toEqual(Object.keys(GENOTYPE_COLOURS));
}
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the shared selector on each view lays out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { view, ppv } = await withRounds(page, 'as-is');
for (const name of VIEWS) {
await view(name);
await page.waitForTimeout(1200);
// every option of the selector is inside the window (it wraps on a narrow screen)
for (const box of await page
.getByRole('radiogroup', { name: VIEWS_LABEL })
.getByRole('radio')
.evaluateAll((els) =>
els.map((e) => e.closest('mat-button-toggle')!.getBoundingClientRect().right),
))
expect(box).toBeLessThanOrEqual(width);
expect(await layoutProblems(page), name).toEqual([]);
}
await ppv('colposcopy');
await ppv('ppvBiopsy');
await page.waitForTimeout(1200);
expect(await layoutProblems(page)).toEqual([]);
});
}
+386
View File
@@ -0,0 +1,386 @@
import { expect, type Page, test } from '@playwright/test';
import { strFromU8, unzipSync } from 'fflate';
import { readFileSync } from 'node:fs';
// Exports of CaMa (the follow-up list as Excel and PDF, the record as PDF), and CaCu's still working.
// The contents are checked by the unit tests of their builders; here the real downloads are checked:
// the file's name and format, and for the filter regression the exported rows and query.
// "(simulado)" tests rewrite the API's answers in the browser to reach what the synthetic data lack.
const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
const SHOTS = process.env['SHOTS_DIR'];
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
async function saved(page: Page, click: () => Promise<unknown>) {
const [download] = await Promise.all([page.waitForEvent('download'), click()]);
const file = await download.path();
return { name: download.suggestedFilename(), bytes: readFileSync(file!) };
}
const isPdf = (b: Buffer) => b.subarray(0, 4).toString() === '%PDF';
const isXlsx = (b: Buffer) => b.subarray(0, 2).toString() === 'PK'; // a zip container
async function followUp(page: Page, domain: 'cama' | 'cacu') {
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('table.worklist tbody tr').first().waitFor({ timeout: 120_000 });
}
function workbookSheets(bytes: Buffer) {
const parts = unzipSync(bytes);
const strings = [
...strFromU8(parts['xl/sharedStrings.xml']).matchAll(/<t(?: [^>]*)?>(.*?)<\/t>/gs),
].map((match) => match[1]);
return [1, 2].map((sheet) =>
[...strFromU8(parts[`xl/worksheets/sheet${sheet}.xml`]).matchAll(/<row\b[^>]*>(.*?)<\/row>/gs)]
.map((row) => [...row[1].matchAll(/<v>(\d+)<\/v>/g)].map((cell) => strings[Number(cell[1])])),
);
}
async function pdfText(bytes: Buffer) {
const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
const task = getDocument({ data: Uint8Array.from(bytes) });
try {
const document = await task.promise;
const text: string[] = [];
for (let n = 1; n <= document.numPages; n++) {
const { items } = await (await document.getPage(n)).getTextContent();
text.push(...items.flatMap((item) => ('str' in item ? [item.str] : [])));
}
return text.join(' ').replace(/\s+/g, ' ');
} finally {
await task.destroy();
}
}
for (const domain of ['cama', 'cacu'] as const) {
for (const format of ['xlsx', 'pdf'] as const) {
test(`exportación (${domain}, ${format}): conserva los filtros aplicados en todas las páginas`, async ({
page,
}) => {
const original = 'Paciente original';
const changed = 'Paciente distinto';
const cutoff = '2026-11-30';
const studyDate = '2026-09-15';
const patients = [`${original} Alfa`, `${original} Beta`];
const requests: URLSearchParams[] = [];
const pending = Promise.withResolvers<void>();
const resume = Promise.withResolvers<void>();
await page.route(
(url) => url.pathname === `/api/${domain}/fhir/Patient` && url.searchParams.has('follow-up-window'),
async (route) => {
const self = new URL(route.request().url());
const filters = self.searchParams;
filters.set('follow-up-cutoff', cutoff);
const exportPage = filters.get('_count') === '200';
const offset = Number(filters.get('_offset') ?? '0');
if (exportPage) {
requests.push(new URLSearchParams(filters));
if (offset === 0) {
pending.resolve();
await resume.promise;
}
}
const matched = filters.get('name') !== changed;
const link = [{ relation: 'self', url: self.href }];
if (matched && exportPage && offset === 0) {
const next = new URL(self);
next.searchParams.set('_offset', '1');
link.push({ relation: 'next', url: next.href });
}
await route.fulfill({
json: {
resourceType: 'Bundle',
type: 'searchset',
total: matched ? patients.length : 0,
link,
entry: matched
? patients.flatMap((name, index) => {
if (exportPage && index !== offset) return [];
const id = `patient-${index}`;
return [
{
search: { mode: 'match' },
resource: { resourceType: 'Patient', id, birthDate: '1980-01-01', name: [{ text: name }] },
},
{
search: { mode: 'include' },
resource: {
resourceType: 'DiagnosticReport',
id: `report-${index}`,
subject: { reference: `Patient/${id}` },
code: { coding: [{ code: domain === 'cama' ? 'mammography' : 'cervical_cytology' }] },
effectiveDateTime: studyDate,
extension: [{ url: EXT + 'report-date', valueDate: studyDate }],
},
},
];
})
: [],
},
});
},
);
await followUp(page, domain);
const search = page.locator('app-patient-search input');
const searchFor = async (text: string) => {
await search.fill(text);
await search.press('Enter');
};
if (domain === 'cacu') {
await page.locator('input[name=ageFrom]').fill('25');
await page.locator('input[name=ageTo]').fill('64');
}
const applied = page.waitForResponse((response) => {
const url = new URL(response.url());
return url.pathname === `/api/${domain}/fhir/Patient` && url.searchParams.get('name') === original;
});
await searchFor(original);
await applied;
await expect(page.locator('table.worklist tbody tr')).toHaveCount(2);
const button = page.getByRole('button', { name: format === 'xlsx' ? 'Exportar Excel' : 'Exportar PDF' });
const download = page.waitForEvent('download');
await button.click();
await Promise.race([pending.promise, download.then(() => { throw new Error('Export request was not held'); })]);
try {
await searchFor(changed);
await page.getByRole('combobox', { name: 'Ventana de meses' }).click();
await page.getByRole('option', { name: '1 mes', exact: true }).click();
if (domain === 'cacu') {
await page.locator('input[name=ageFrom]').fill('40');
await page.getByRole('combobox', { name: 'Horizonte de la probabilidad' }).click();
await page.getByRole('option', { name: '1 año', exact: true }).click();
}
await expect(page.getByText('No hay registros para los filtros aplicados.')).toBeVisible();
} finally {
resume.resolve();
}
const file = await download;
expect(file.suggestedFilename()).toBe(`seguimiento-${domain}.${format}`);
const bytes = readFileSync((await file.path())!);
expect(requests.map((params) => params.get('_offset') ?? '0')).toEqual(['0', '1']);
for (const params of requests) {
expect(params.get('name')).toBe(original);
expect(params.get('follow-up-window')).toBe('3');
expect(params.get('follow-up-cutoff')).toBe(cutoff);
if (domain === 'cacu') {
expect(params.getAll('birthdate')).toEqual(['le2001-11-30', 'gt1961-11-30']);
expect(params.get('risk-horizon')).toBe('5');
}
}
const metadata = [
['Ventana consultada', `2026-08-31 al ${cutoff}`],
['Búsqueda', original],
['Registros', '2'],
...(domain === 'cacu'
? [['Edad mínima', '25'], ['Edad máxima', '64'], ['Horizonte de la probabilidad (años)', '5']]
: []),
];
if (format === 'xlsx') {
const [results, query] = workbookSheets(bytes);
expect(results.slice(1).map((row) => row[0])).toEqual(patients);
expect(results.slice(1).every((row) => row.some((cell) => cell.includes(studyDate)))).toBe(true);
expect(query).toEqual(expect.arrayContaining(metadata));
expect(query.flat()).not.toContain(changed);
} else {
const text = await pdfText(bytes);
for (const value of [...patients, studyDate, ...metadata.map(([key, value]) => `${key}: ${value}`)]) {
expect(text).toContain(value);
}
expect(text).not.toContain(changed);
}
});
}
}
test('exportación (CaMa): the follow-up list is saved as Excel and PDF with as many rows as the page asked for', async ({
page,
}) => {
await followUp(page, 'cama');
const total = await page.locator('table.worklist tbody tr').count();
const excel = await saved(page, () =>
page.getByRole('button', { name: 'Exportar Excel' }).click(),
);
expect(excel.name).toBe('seguimiento-cama.xlsx');
expect(isXlsx(excel.bytes)).toBe(true);
const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click());
expect(pdf.name).toBe('seguimiento-cama.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
expect(pdf.bytes.length).toBeGreaterThan(5_000);
expect(total).toBeGreaterThan(0);
await expect(page.getByText('No se generó el archivo.')).toHaveCount(0);
});
test('exportación (CaMa): the buttons wait for a cut-off and an empty search still saves a file', async ({
page,
}) => {
await followUp(page, 'cama');
await page.locator('app-patient-search input').fill('zzzz-sin-coincidencias');
await page.keyboard.press('Enter');
await expect(page.getByText('No hay registros para los filtros aplicados.')).toBeVisible({
timeout: 60_000,
});
const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click());
expect(isPdf(pdf.bytes)).toBe(true);
});
test('exportación (CaMa): the record is saved as a PDF', async ({ page }) => {
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}`);
const button = page.getByRole('button', { name: 'Exportar PDF' });
await expect(button).toBeVisible({ timeout: 120_000 });
const pdf = await saved(page, () => button.click());
expect(pdf.name).toBe('expediente-cama.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
expect(pdf.bytes.length).toBeGreaterThan(5_000);
});
test('exportación (CaMa, simulado): a record with published survival and recurrence estimates saves its PDF', async ({
page,
}) => {
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
const estimate = (id: string, method: string, model: string) => ({
resourceType: 'RiskAssessment',
id,
status: 'final',
method: { text: method, coding: [{ code: model }] },
occurrenceDateTime: '2026-02-01',
extension: [{ url: EXT + 'escenario-clinico', valueString: 'En observación' }],
prediction: [
{
whenRange: { high: { value: 0, unit: 'a', code: 'a' } },
probabilityDecimal: 0,
extension: [],
},
{
whenRange: { high: { value: 5, unit: 'a', code: 'a' } },
probabilityDecimal: 0.8,
extension: [
{ url: EXT + 'ic-bajo', valueDecimal: 0.7 },
{ url: EXT + 'ic-alto', valueDecimal: 0.9 },
],
},
],
});
await page.route('**/api/cama/fhir/RiskAssessment**', (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: [
estimate('s', 'Supervivencia v1', 'cama.survival'),
estimate('r', 'Recurrencia v1', 'cama.recurrence'),
].map((resource) => ({ resource })),
}),
}),
);
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
const button = page.getByRole('button', { name: 'Exportar PDF' });
await expect(button).toBeVisible({ timeout: 120_000 });
const pdf = await saved(page, () => button.click());
expect(isPdf(pdf.bytes)).toBe(true);
if (SHOTS)
(await import('node:fs')).writeFileSync(
`${SHOTS}/SIMULADO-expediente-cama-con-estimaciones.pdf`,
pdf.bytes,
);
});
test('exportación (CaCu): the list and the record still save their files', async ({ page }) => {
await followUp(page, 'cacu');
const excel = await saved(page, () =>
page.getByRole('button', { name: 'Exportar Excel' }).click(),
);
expect(excel.name).toBe('seguimiento-cacu.xlsx');
expect(isXlsx(excel.bytes)).toBe(true);
const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click());
expect(pdf.name).toBe('seguimiento-cacu.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cacu/pacientes/${patients.entry[0].resource.id}`);
const record = await saved(page, async () => {
await page.getByRole('button', { name: 'Exportar PDF' }).click();
});
expect(record.name).toBe('expediente-cacu.pdf');
expect(isPdf(record.bytes)).toBe(true);
});
for (const width of [1440, 480]) {
test(`exportación (CaMa) at ${width} px: the record's PDF button sits in the header beside the name, never over it`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
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}`);
const button = page.getByRole('button', { name: 'Exportar PDF' });
await expect(button).toBeVisible({ timeout: 120_000 });
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
// one button, in the header; the "Historial médico" card no longer holds it
await expect(button).toHaveCount(1);
await expect(
page.locator('.record-head').getByRole('button', { name: 'Exportar PDF' }),
).toHaveCount(1);
await expect(
page
.locator('mat-card', { has: page.getByText('Historial médico', { exact: true }) })
.getByRole('button', { name: 'Exportar PDF' }),
).toHaveCount(0);
const [title, action] = await Promise.all([
page.locator('.record-head h1').boundingBox(),
button.boundingBox(),
]);
const overlaps = !(
action!.x >= title!.x + title!.width ||
title!.x >= action!.x + action!.width ||
action!.y >= title!.y + title!.height ||
title!.y >= action!.y + action!.height
);
expect(overlaps).toBe(false);
if (width >= 1000) {
expect(action!.x + action!.width).toBeGreaterThan(width - 120); // at the right end
expect(
Math.abs(action!.y + action!.height / 2 - (title!.y + title!.height / 2)),
).toBeLessThan(30); // on the name's line
} else {
expect(action!.x + action!.width).toBeLessThanOrEqual(width);
}
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
if (SHOTS)
await page.screenshot({
path: `${SHOTS}/captura-cama-ficha-boton-${width}.png`,
fullPage: false,
});
const pdf = await saved(page, () => button.click());
expect(pdf.name).toBe('expediente-cama.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
if (SHOTS)
(await import('node:fs')).writeFileSync(
`${SHOTS}/descarga-ficha-cama-${width}.pdf`,
pdf.bytes,
);
});
}
test('exportación (CaCu): the record button stays in its "Historial médico" card', async ({
page,
}) => {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cacu/pacientes/${patients.entry[0].resource.id}`);
const card = page.locator('mat-card', {
has: page.getByText('Historial médico', { exact: true }),
});
await expect(card.getByRole('button', { name: 'Exportar PDF' })).toBeVisible({
timeout: 120_000,
});
await expect(page.locator('.record-head').getByRole('button')).toHaveCount(0);
});
File diff suppressed because it is too large Load Diff
+56 -48
View File
@@ -56,11 +56,10 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText( await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
`${count.toLocaleString('es-MX')} pacientes`, `${count.toLocaleString('es-MX')} pacientes`,
); );
// CaCu's readings are bars and tables, not plots await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await expect(page.locator('app-tab-indicadores app-readings').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(10); await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
@@ -91,19 +90,6 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr'); const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS'); await expect(camaRows.first()).toContainText('BI-RADS');
// the whole list and a record, each as its file
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cama.xlsx'],
['Exportar PDF', 'seguimiento-cama.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await camaRows.first().locator('a').first().click();
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cama.pdf');
await page.goto('/indicadores/tea'); await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
expect(problems).toEqual([]); expect(problems).toEqual([]);
@@ -219,12 +205,39 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>'); const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
// CaCu's (Phase 6) and CaMa's (Phase 7) pages are their own; TEA's follows the old one. for (const domain of ['cacu', 'cama', 'tea']) {
for (const domain of ['tea']) { test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Análisis de Riesgo', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Trazabilidad', 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 ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page, page,
}) => { }) => {
const old = captured(domain); const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// The histopathology figures are two cards: the result by BI-RADS and the confirmation.
const results = all.findIndex(
(i) => i.text === 'Tipo histológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Tipo histológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores'); const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
@@ -233,9 +246,29 @@ for (const domain of ['tea']) {
.locator('h2, h3') .locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad'); const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual( if (domain === 'cama') {
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), const ordered = [
); 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
'Tiempo de toma de mastografía a interpretación radiológica',
'Tiempo de interpretación radiológica a diagnóstico',
'Tiempo de interpretación radiológica a resultado de biopsia',
'Tiempo de diagnóstico a tratamiento',
'Tiempo de tamizaje a diagnóstico',
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'Tipo histológico por categoría BI-RADS',
'Confirmación histopatológica',
];
let last = -1;
for (const title of ordered) {
const next = headings.findIndex((h, index) => index > last && h.startsWith(title));
expect(next, title).toBeGreaterThan(last);
last = next;
}
} else {
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
}
// Each figure drawn is one of the old kinds (a figure with no data in the period is named). // Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab const drawn = await tab
.locator('.js-plotly-plot') .locator('.js-plotly-plot')
@@ -249,28 +282,6 @@ for (const domain of ['tea']) {
}); });
} }
/** Phase 7's Trazabilidad panels over the old tab's: an old title stands for these. */
const PANELS: Record<string, Record<string, string[]>> = {
cacu: {
'Tiempo de tamizaje a diagnóstico': [
'Tiempo de tamizaje a primer diagnóstico',
'Tiempo de tamizaje a diagnóstico tras biopsia',
],
'Tiempo de diagnóstico a tratamiento': ['Tiempo de diagnóstico tras biopsia a tratamiento'],
},
cama: {
'Días de la toma de la mastografía a su resultado': [
'Tiempo de diagnóstico tras biopsia a tratamiento',
'Días de la toma de la mastografía a su resultado',
],
'Días de tamizaje a diagnóstico': [
'Tiempo de tamizaje a diagnóstico',
'Tasa de detección histopatológica',
],
'Tasa de confirmación histopatológica': ['Confirmación histopatológica'],
},
};
for (const domain of ['cacu', 'cama', 'tea']) { for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({ test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page, page,
@@ -289,10 +300,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
const headings = await tab const headings = await tab
.locator('h2, h3') .locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const now = PANELS[domain] ?? {}; expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
expect(headings).toEqual(
old.filter((i) => i.kind !== 'plot').flatMap((i) => now[i.text] ?? [i.text]),
);
const drawn = await tab const drawn = await tab
.locator('.js-plotly-plot') .locator('.js-plotly-plot')
.evaluateAll((els) => .evaluateAll((els) =>
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from '@playwright/test';
/** SIMULATED answers. The pages read the API's aggregated MeasureReports; these helpers pass them
* through the browser and rewrite the screening-round strata, so the cards can be tried with the
* groups the contract of `rebuild` allows (stratum `round`, crossed `round-category`) without
* loading data. They prove how the page draws such answers, not what the backend computes.
*
* - `as-is`: the answers untouched, with a stratum named `screening_round` renamed `round`.
* - `no-initial`: nobody is in the initial group (the group is absent and the totals drop).
* - `unclassified`: the initial group folds into "Sin dato" (what 5740's answers look like).
* - `unpublished`: the round strata are not in the answers. */
export type Simulation = 'as-is' | 'no-initial' | 'unclassified' | 'unpublished';
type Stratum = {
value?: { text?: string };
component?: { value?: { text?: string } }[];
population?: { code?: { coding?: { code?: string }[] }; count: number }[];
};
type Stratifier = { code?: { coding?: { code?: string }[] }[]; stratum?: Stratum[] };
const named = (s: Stratifier) => (s.code ?? []).map((c) => c.coding?.[0]?.code).join('-');
const label = (x: Stratum) => x.component?.[0]?.value?.text ?? x.value?.text;
const pop = (o: { population?: Stratum['population'] }, code: string) =>
o.population?.find((p) => p.code?.coding?.[0]?.code === code);
function fold(into: Stratum, from: Stratum) {
for (const p of from.population ?? []) {
const q = pop(into, p.code!.coding![0].code!);
if (q) q.count += p.count;
else (into.population ??= []).push(structuredClone(p));
}
}
export function simulate(report: any, how: Simulation) {
const group = report?.group?.[0];
if (!group) return report;
for (const s of group.stratifier ?? ([] as Stratifier[]))
for (const c of s.code ?? []) {
const k = c.coding?.[0];
if (k?.code === 'screening_round') k.code = 'round';
}
const rounds: Stratifier[] = (group.stratifier ?? []).filter((s: Stratifier) =>
['round', 'round-category'].includes(named(s)),
);
if (how === 'unpublished')
group.stratifier = (group.stratifier ?? []).filter((s: Stratifier) => !rounds.includes(s));
if (how === 'no-initial' || how === 'unclassified')
for (const s of rounds) {
const initial = (s.stratum ?? []).filter((x) => label(x) === 'initial');
const rest = (s.stratum ?? []).filter((x) => label(x) !== 'initial');
for (const x of initial) {
if (how === 'unclassified') {
const other = x.component?.[1]?.value?.text;
const target = rest.find(
(y) => label(y) === 'no_data' && (!other || y.component?.[1]?.value?.text === other),
);
if (target) fold(target, x);
else {
(x.component ? x.component[0].value! : x.value!).text = 'no_data';
rest.push(x);
}
} else if (named(s) === 'round') {
// the group vanishes and the period's total drops by its patients: a real zero
for (const p of x.population ?? []) {
const total = pop(group, p.code!.coding![0].code!);
if (total && p.code!.coding![0].code !== 'numerator')
total.count = Math.max(0, total.count - p.count);
}
}
}
s.stratum = rest;
}
return report;
}
/** Answers every CaCu MeasureReport search through `simulate`. */
export async function simulateRounds(page: Page, how: Simulation) {
await page.route('**/api/cacu/fhir/MeasureReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const entry of body.entry ?? []) simulate(entry.resource, how);
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
+267 -507
View File
@@ -990,48 +990,6 @@
"title": "Join", "title": "Join",
"type": "object" "type": "object"
}, },
"LanguageModel": {
"properties": {
"available": {
"title": "Available",
"type": "boolean"
},
"model": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Model"
},
"reason": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Reason"
},
"vision": {
"title": "Vision",
"type": "boolean"
}
},
"required": [
"available",
"model",
"vision",
"reason"
],
"title": "LanguageModel",
"type": "object"
},
"Link": { "Link": {
"additionalProperties": false, "additionalProperties": false,
"description": "Identity rows from every input, grouped into persons (Splink).\n\nTwo records are the same person when any rule holds (Splink's SQL rule syntax, `l.`\nand `r.` for the two records); persons are the connected groups. A person whose\nrecords disagree on birth date or sex is held for review as a whole. Pairs Splink\nscores above `review` that ended up apart are queued as possible matches.", "description": "Identity rows from every input, grouped into persons (Splink).\n\nTwo records are the same person when any rule holds (Splink's SQL rule syntax, `l.`\nand `r.` for the two records); persons are the connected groups. A person whose\nrecords disagree on birth date or sex is held for review as a whole. Pairs Splink\nscores above `review` that ended up apart are queued as possible matches.",
@@ -1699,17 +1657,6 @@
], ],
"title": "Q" "title": "Q"
}, },
"reason": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Reason"
},
"reference_probability": { "reference_probability": {
"title": "Reference Probability", "title": "Reference Probability",
"type": "number" "type": "number"
@@ -2860,248 +2807,6 @@
] ]
} }
}, },
"/cacu/fhir/Patient/{id}/$eligibility": {
"get": {
"description": "Her indexed candidates of each CaCu cohort: eligible, or every reason she is not.",
"operationId": "cacu_eligibility",
"parameters": [
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "One CaCu scenario (default: every one)",
"in": "query",
"name": "scenario",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "One CaCu scenario (default: every one)",
"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"
]
}
},
"/cacu/fhir/Patient/{id}/$reference-risk": {
"get": {
"description": "Disabled: the NCI series, the master table's included, are in `$risk-series`.",
"operationId": "cacu_reference_risk",
"parameters": [
{
"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 (default: her latest)",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day (default: her latest)",
"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 Reference Risk",
"tags": [
"fhir"
]
}
},
"/cacu/fhir/Patient/{id}/$risk-series": {
"get": {
"description": "EXPERIMENTAL. The risk series her record can draw: the models' and the NCI tables',\nby outcome, with their published intervals.",
"operationId": "cacu_risk_series",
"parameters": [
{
"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 (default: her latest)",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day (default: her latest)",
"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"
]
}
},
"/domains": { "/domains": {
"get": { "get": {
"operationId": "domains", "operationId": "domains",
@@ -3279,28 +2984,6 @@
] ]
} }
}, },
"/ingest/llm": {
"get": {
"description": "The site's language model (LLM_URL): whether it answers, which, and whether it\nreads images. Autom\u00e1tico needs it; extract nodes use their patterns without it.",
"operationId": "language_model",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/LanguageModel"
}
}
},
"description": "Successful Response"
}
},
"summary": "Language Model",
"tags": [
"ingest"
]
}
},
"/ingest/pipelines": { "/ingest/pipelines": {
"get": { "get": {
"operationId": "pipelines", "operationId": "pipelines",
@@ -3445,65 +3128,6 @@
] ]
} }
}, },
"/ingest/pipelines/{pipeline_id}/draft": {
"post": {
"description": "Autom\u00e1tico: starts the `draft` job, which draws the whole pipeline from its saved\nsources (the only nodes it may hold), saves it as a new version and runs it (`run`\nfalse: drawn and saved only); follow it at /runs/{run_id}.",
"operationId": "start_draft",
"parameters": [
{
"in": "path",
"name": "pipeline_id",
"required": true,
"schema": {
"maxLength": 40,
"pattern": "^[a-z][a-z0-9_]*$",
"title": "Pipeline Id",
"type": "string"
}
},
{
"in": "query",
"name": "run",
"required": false,
"schema": {
"default": true,
"title": "Run",
"type": "boolean"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Start Draft",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Start Draft",
"tags": [
"ingest"
]
}
},
"/ingest/pipelines/{pipeline_id}/nodes/{node_id}/rows": { "/ingest/pipelines/{pipeline_id}/nodes/{node_id}/rows": {
"get": { "get": {
"description": "What a node produced in the last run (empty if it produced nothing yet).", "description": "What a node produced in the last run (empty if it produced nothing yet).",
@@ -4813,32 +4437,6 @@
] ]
} }
}, },
"/runs/rebuild": {
"post": {
"description": "Starts rebuilding silver and gold with the deployed code (after an upgrade, before any\nnew data); follow it at /runs/{run_id}. The risk tables keep their last scores.",
"operationId": "rebuild_gold",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Rebuild Gold",
"type": "object"
}
}
},
"description": "Successful Response"
}
},
"summary": "Rebuild Gold",
"tags": [
"runs"
]
}
},
"/runs/{run_id}": { "/runs/{run_id}": {
"get": { "get": {
"operationId": "run_status", "operationId": "run_status",
@@ -4999,91 +4597,6 @@
] ]
} }
}, },
"/tea/fhir/Patient/$eeg-summary": {
"get": {
"operationId": "eeg_summary",
"parameters": [
{
"description": "months",
"in": "query",
"name": "follow-up-window",
"required": false,
"schema": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
],
"description": "months",
"title": "Follow-Up-Window"
}
},
{
"in": "query",
"name": "follow-up-start",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"title": "Follow-Up-Start"
}
},
{
"in": "query",
"name": "follow-up-cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"title": "Follow-Up-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": "Eeg Summary",
"tags": [
"fhir"
]
}
},
"/users/me": { "/users/me": {
"get": { "get": {
"operationId": "users:current_user", "operationId": "users:current_user",
@@ -6117,7 +5630,7 @@
}, },
"/{domain}/fhir/Patient": { "/{domain}/fhir/Patient": {
"get": { "get": {
"description": "Patients; with `follow-up-window` or `follow-up-start` (or, where the domain has them,\nits filters or a cut-off: its whole history), the domain's follow-up list at the cut-off,\nfiltered and in reading order, with what the list shows of each patient included.", "description": "Patients; with `follow-up-window`, the domain's follow-up list at the cut-off,\nfiltered by status and in reading order, with what the list shows of each patient\nincluded.",
"operationId": "search_patient", "operationId": "search_patient",
"parameters": [ "parameters": [
{ {
@@ -6181,25 +5694,6 @@
"title": "Follow-Up-Cutoff" "title": "Follow-Up-Cutoff"
} }
}, },
{
"description": "the list from this day (in place of a window)",
"in": "query",
"name": "follow-up-start",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "the list from this day (in place of a window)",
"title": "Follow-Up-Start"
}
},
{ {
"in": "query", "in": "query",
"name": "follow-up-status", "name": "follow-up-status",
@@ -6432,6 +5926,272 @@
] ]
} }
}, },
"/{domain}/fhir/Patient/{id}/$eligibility": {
"get": {
"description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.",
"operationId": "cacu_eligibility",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Limit the report to one CaCu scenario",
"in": "query",
"name": "scenario",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Limit the report to one CaCu scenario",
"title": "Scenario"
}
},
{
"description": "Only index dates up to this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only index dates up to this day",
"title": "Cutoff"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Eligibility",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$reference-risk": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.",
"operationId": "reference_risk",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Reference Risk",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$risk-series": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.",
"operationId": "cacu_risk_series",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Risk Series",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Procedure": { "/{domain}/fhir/Procedure": {
"get": { "get": {
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).", "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
+292
View File
@@ -42,8 +42,10 @@
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5", "@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"vitest": "^5.0.0" "vitest": "^5.0.0"
@@ -2013,6 +2015,283 @@
"win32" "win32"
] ]
}, },
"node_modules/@napi-rs/canvas": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz",
"integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==",
"dev": true,
"license": "MIT",
"optional": true,
"workspaces": [
"e2e/*"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/canvas-android-arm64": "1.2.1",
"@napi-rs/canvas-darwin-arm64": "1.2.1",
"@napi-rs/canvas-darwin-x64": "1.2.1",
"@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1",
"@napi-rs/canvas-linux-arm64-gnu": "1.2.1",
"@napi-rs/canvas-linux-arm64-musl": "1.2.1",
"@napi-rs/canvas-linux-riscv64-gnu": "1.2.1",
"@napi-rs/canvas-linux-x64-gnu": "1.2.1",
"@napi-rs/canvas-linux-x64-musl": "1.2.1",
"@napi-rs/canvas-win32-arm64-msvc": "1.2.1",
"@napi-rs/canvas-win32-x64-msvc": "1.2.1"
}
},
"node_modules/@napi-rs/canvas-android-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz",
"integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz",
"integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-x64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz",
"integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz",
"integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz",
"integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz",
"integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz",
"integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==",
"cpu": [
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz",
"integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz",
"integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz",
"integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz",
"integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/nice": { "node_modules/@napi-rs/nice": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz",
@@ -6077,6 +6356,19 @@
"url": "https://github.com/fb55/entities?sponsor=1" "url": "https://github.com/fb55/entities?sponsor=1"
} }
}, },
"node_modules/pdfjs-dist": {
"version": "6.5.438",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
"integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=22.13.0 || >=24"
},
"optionalDependencies": {
"@napi-rs/canvas": "^1.0.13"
}
},
"node_modules/pdfkit": { "node_modules/pdfkit": {
"version": "0.20.2", "version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz", "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
+2
View File
@@ -46,8 +46,10 @@
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5", "@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"vitest": "^5.0.0" "vitest": "^5.0.0"
+5 -2
View File
@@ -7,12 +7,14 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response'; import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder'; import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuEligibility$Params { export interface CacuEligibility$Params {
domain: Domain;
id: string; id: string;
/** /**
* One CaCu scenario (default: every one) * Limit the report to one CaCu scenario
*/ */
scenario?: (string | null); scenario?: (string | null);
@@ -26,6 +28,7 @@ export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuE
}>> { }>> {
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get'); const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
if (params) { if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {}); rb.path('id', params.id, {});
rb.query('scenario', params.scenario, {}); rb.query('scenario', params.scenario, {});
rb.query('cutoff', params.cutoff, {}); rb.query('cutoff', params.cutoff, {});
@@ -42,4 +45,4 @@ export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuE
); );
} }
cacuEligibility.PATH = '/cacu/fhir/Patient/{id}/$eligibility'; cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
+5 -2
View File
@@ -7,8 +7,10 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response'; import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder'; import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuRiskSeries$Params { export interface CacuRiskSeries$Params {
domain: Domain;
id: string; id: string;
/** /**
@@ -17,7 +19,7 @@ export interface CacuRiskSeries$Params {
cutoff?: (string | null); cutoff?: (string | null);
/** /**
* The cytology's sample day (default: her latest) * The cytology's sample day
*/ */
sample?: (string | null); sample?: (string | null);
} }
@@ -26,6 +28,7 @@ export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRi
}>> { }>> {
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get'); const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
if (params) { if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {}); rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {}); rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {}); rb.query('sample', params.sample, {});
@@ -42,4 +45,4 @@ export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRi
); );
} }
cacuRiskSeries.PATH = '/cacu/fhir/Patient/{id}/$risk-series'; cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
-41
View File
@@ -1,41 +0,0 @@
/* 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';
export interface EegSummary$Params {
/**
* months
*/
'follow-up-window'?: (number | null);
'follow-up-start'?: (string | null);
'follow-up-cutoff'?: (string | null);
}
export function eegSummary(http: HttpClient, rootUrl: string, params?: EegSummary$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, eegSummary.PATH, 'get');
if (params) {
rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-start', params['follow-up-start'], {});
rb.query('follow-up-cutoff', params['follow-up-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<{
}>;
})
);
}
eegSummary.PATH = '/tea/fhir/Patient/$eeg-summary';
@@ -7,8 +7,10 @@ import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response'; import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder'; import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuReferenceRisk$Params { export interface ReferenceRisk$Params {
domain: Domain;
id: string; id: string;
/** /**
@@ -17,15 +19,16 @@ export interface CacuReferenceRisk$Params {
cutoff?: (string | null); cutoff?: (string | null);
/** /**
* The cytology's sample day (default: her latest) * The cytology's sample day
*/ */
sample?: (string | null); sample?: (string | null);
} }
export function cacuReferenceRisk(http: HttpClient, rootUrl: string, params: CacuReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{ export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> { }>> {
const rb = new RequestBuilder(rootUrl, cacuReferenceRisk.PATH, 'get'); const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
if (params) { if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {}); rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {}); rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {}); rb.query('sample', params.sample, {});
@@ -42,4 +45,4 @@ export function cacuReferenceRisk(http: HttpClient, rootUrl: string, params: Cac
); );
} }
cacuReferenceRisk.PATH = '/cacu/fhir/Patient/{id}/$reference-risk'; referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
-6
View File
@@ -22,11 +22,6 @@ export interface SearchPatient$Params {
* default: the last day with data * default: the last day with data
*/ */
'follow-up-cutoff'?: (string | null); 'follow-up-cutoff'?: (string | null);
/**
* the list from this day (in place of a window)
*/
'follow-up-start'?: (string | null);
'follow-up-status'?: (string | null); 'follow-up-status'?: (string | null);
/** /**
@@ -75,7 +70,6 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('_id', params['_id'], {}); rb.query('_id', params['_id'], {});
rb.query('follow-up-window', params['follow-up-window'], {}); rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {}); rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-start', params['follow-up-start'], {});
rb.query('follow-up-status', params['follow-up-status'], {}); rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {}); rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {}); rb.query('identifier', params.identifier, {});
-30
View File
@@ -1,30 +0,0 @@
/* 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 { LanguageModel } from '../../models/language-model';
export interface LanguageModel$Params {
}
export function languageModel(http: HttpClient, rootUrl: string, params?: LanguageModel$Params, context?: HttpContext): Observable<StrictHttpResponse<LanguageModel>> {
const rb = new RequestBuilder(rootUrl, languageModel.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<LanguageModel>;
})
);
}
languageModel.PATH = '/ingest/llm';
-37
View File
@@ -1,37 +0,0 @@
/* 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';
export interface StartDraft$Params {
pipeline_id: string;
run?: boolean;
}
export function startDraft(http: HttpClient, rootUrl: string, params: StartDraft$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, startDraft.PATH, 'post');
if (params) {
rb.path('pipeline_id', params.pipeline_id, {});
rb.query('run', params.run, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
startDraft.PATH = '/ingest/pipelines/{pipeline_id}/draft';
-33
View File
@@ -1,33 +0,0 @@
/* 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';
export interface RebuildGold$Params {
}
export function rebuildGold(http: HttpClient, rootUrl: string, params?: RebuildGold$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, rebuildGold.PATH, 'post');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
rebuildGold.PATH = '/runs/rebuild';
+32 -40
View File
@@ -5,40 +5,6 @@ export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login'; export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout'; export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout'; export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
export type { CacuReferenceRisk$Params as CacuReferenceRisk$Params } from './fn/fhir/cacu-reference-risk';
export { cacuReferenceRisk as cacuReferenceRisk } from './fn/fhir/cacu-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 { EegSummary$Params as EegSummary$Params } from './fn/fhir/eeg-summary';
export { eegSummary as eegSummary } from './fn/fhir/eeg-summary';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
export { searchCondition as searchCondition } from './fn/fhir/search-condition';
export type { SearchDiagnosticReport$Params as SearchDiagnosticReport$Params } from './fn/fhir/search-diagnostic-report';
export { searchDiagnosticReport as searchDiagnosticReport } from './fn/fhir/search-diagnostic-report';
export type { SearchEncounter$Params as SearchEncounter$Params } from './fn/fhir/search-encounter';
export { searchEncounter as searchEncounter } from './fn/fhir/search-encounter';
export type { SearchMeasure$Params as SearchMeasure$Params } from './fn/fhir/search-measure';
export { searchMeasure as searchMeasure } from './fn/fhir/search-measure';
export type { ReadMeasure$Params as ReadMeasure$Params } from './fn/fhir/read-measure';
export { readMeasure as readMeasure } from './fn/fhir/read-measure';
export type { SearchMeasureReport$Params as SearchMeasureReport$Params } from './fn/fhir/search-measure-report';
export { searchMeasureReport as searchMeasureReport } from './fn/fhir/search-measure-report';
export type { SearchObservation$Params as SearchObservation$Params } from './fn/fhir/search-observation';
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/search-patient';
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
export { readPatient as readPatient } from './fn/fhir/read-patient';
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';
export { searchRiskAssessment as searchRiskAssessment } from './fn/fhir/search-risk-assessment';
export type { Metadata$Params as Metadata$Params } from './fn/fhir/metadata';
export { metadata as metadata } from './fn/fhir/metadata';
export type { Domains$Params as Domains$Params } from './fn/operations/domains'; export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains'; export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health'; export type { Health$Params as Health$Params } from './fn/operations/health';
@@ -49,16 +15,12 @@ export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/g
export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map'; export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map';
export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map'; export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map';
export { saveConceptMap as saveConceptMap } from './fn/ingest/save-concept-map'; export { saveConceptMap as saveConceptMap } from './fn/ingest/save-concept-map';
export type { LanguageModel$Params as LanguageModel$Params } from './fn/ingest/language-model';
export { languageModel as languageModel } from './fn/ingest/language-model';
export type { Pipelines$Params as Pipelines$Params } from './fn/ingest/pipelines'; export type { Pipelines$Params as Pipelines$Params } from './fn/ingest/pipelines';
export { pipelines as pipelines } from './fn/ingest/pipelines'; export { pipelines as pipelines } from './fn/ingest/pipelines';
export type { Pipeline$Params as Pipeline$Params } from './fn/ingest/pipeline'; export type { Pipeline$Params as Pipeline$Params } from './fn/ingest/pipeline';
export { pipeline as pipeline } from './fn/ingest/pipeline'; export { pipeline as pipeline } from './fn/ingest/pipeline';
export type { SavePipeline$Params as SavePipeline$Params } from './fn/ingest/save-pipeline'; export type { SavePipeline$Params as SavePipeline$Params } from './fn/ingest/save-pipeline';
export { savePipeline as savePipeline } from './fn/ingest/save-pipeline'; export { savePipeline as savePipeline } from './fn/ingest/save-pipeline';
export type { StartDraft$Params as StartDraft$Params } from './fn/ingest/start-draft';
export { startDraft as startDraft } from './fn/ingest/start-draft';
export type { NodeRows$Params as NodeRows$Params } from './fn/ingest/node-rows'; export type { NodeRows$Params as NodeRows$Params } from './fn/ingest/node-rows';
export { nodeRows as nodeRows } from './fn/ingest/node-rows'; export { nodeRows as nodeRows } from './fn/ingest/node-rows';
export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run'; export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
@@ -111,8 +73,6 @@ export type { Reject$Params as Reject$Params } from './fn/review/reject';
export { reject as reject } from './fn/review/reject'; export { reject as reject } from './fn/review/reject';
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised'; export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
export { unrecognised as unrecognised } from './fn/review/unrecognised'; export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { RebuildGold$Params as RebuildGold$Params } from './fn/runs/rebuild-gold';
export { rebuildGold as rebuildGold } from './fn/runs/rebuild-gold';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status'; export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status'; export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run'; export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
@@ -133,3 +93,35 @@ export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/user
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user'; export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user'; export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user'; export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
export { postBundle as postBundle } from './fn/fhir/post-bundle';
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
export { searchCondition as searchCondition } from './fn/fhir/search-condition';
export type { SearchDiagnosticReport$Params as SearchDiagnosticReport$Params } from './fn/fhir/search-diagnostic-report';
export { searchDiagnosticReport as searchDiagnosticReport } from './fn/fhir/search-diagnostic-report';
export type { SearchEncounter$Params as SearchEncounter$Params } from './fn/fhir/search-encounter';
export { searchEncounter as searchEncounter } from './fn/fhir/search-encounter';
export type { SearchMeasure$Params as SearchMeasure$Params } from './fn/fhir/search-measure';
export { searchMeasure as searchMeasure } from './fn/fhir/search-measure';
export type { ReadMeasure$Params as ReadMeasure$Params } from './fn/fhir/read-measure';
export { readMeasure as readMeasure } from './fn/fhir/read-measure';
export type { SearchMeasureReport$Params as SearchMeasureReport$Params } from './fn/fhir/search-measure-report';
export { searchMeasureReport as searchMeasureReport } from './fn/fhir/search-measure-report';
export type { SearchObservation$Params as SearchObservation$Params } from './fn/fhir/search-observation';
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/search-patient';
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
export { 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';
export { searchRiskAssessment as searchRiskAssessment } from './fn/fhir/search-risk-assessment';
export type { Metadata$Params as Metadata$Params } from './fn/fhir/metadata';
export { metadata as metadata } from './fn/fhir/metadata';
-1
View File
@@ -19,7 +19,6 @@ export type { Group } from './models/group';
export type { Guided } from './models/guided'; export type { Guided } from './models/guided';
export type { HttpValidationError } from './models/http-validation-error'; export type { HttpValidationError } from './models/http-validation-error';
export type { Join } from './models/join'; export type { Join } from './models/join';
export type { LanguageModel } from './models/language-model';
export type { Link } from './models/link'; export type { Link } from './models/link';
export type { Listing } from './models/listing'; export type { Listing } from './models/listing';
export type { Login } from './models/login'; export type { Login } from './models/login';
-9
View File
@@ -1,9 +0,0 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface LanguageModel {
available: boolean;
model: (string | null);
reason: (string | null);
vision: boolean;
}
-1
View File
@@ -19,7 +19,6 @@ export interface Relation {
outcome_code: string; outcome_code: string;
probability: number; probability: number;
q: (number | null); q: (number | null);
reason?: (string | null);
reference_probability: number; reference_probability: number;
z: number; z: number;
zone: string; zone: string;
-18
View File
@@ -36,24 +36,6 @@
<span class="spacer"></span> <span class="spacer"></span>
<button mat-stroked-button (click)="save()">Guardar</button> <button mat-stroked-button (click)="save()">Guardar</button>
<button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button> <button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button>
@if (onlySources()) {
<span
[matTooltip]="
llm.value()?.available
? 'El modelo de lenguaje del sitio arma toda la canalización a partir de estas fuentes y la ejecuta.'
: 'No disponible: ' +
(llm.value()?.reason ?? 'no hay modelo de lenguaje configurado')
"
>
<button
mat-flat-button
(click)="automatic()"
[disabled]="running() || !llm.value()?.available"
>
<mat-icon>auto_awesome</mat-icon>Armar automáticamente
</button>
</span>
}
} }
</div> </div>
@if (message()) { @if (message()) {
+8 -40
View File
@@ -23,14 +23,12 @@ import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
import { withFormlyMaterial } from '@ngx-formly/material'; import { withFormlyMaterial } from '@ngx-formly/material';
import { Connection, NodeChange, Vflow } from 'ngx-vflow'; import { Connection, NodeChange, Vflow } from 'ngx-vflow';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { languageModel } from '../api/fn/ingest/language-model';
import { nodeRows } from '../api/fn/ingest/node-rows'; import { nodeRows } from '../api/fn/ingest/node-rows';
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline'; import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
import { pipelines } from '../api/fn/ingest/pipelines'; import { pipelines } from '../api/fn/ingest/pipelines';
import { savePipeline } from '../api/fn/ingest/save-pipeline'; import { savePipeline } from '../api/fn/ingest/save-pipeline';
import { schema } from '../api/fn/ingest/schema'; import { schema } from '../api/fn/ingest/schema';
import { sourcePreview } from '../api/fn/ingest/source-preview'; import { sourcePreview } from '../api/fn/ingest/source-preview';
import { startDraft } from '../api/fn/ingest/start-draft';
import { startRun } from '../api/fn/ingest/start-run'; import { startRun } from '../api/fn/ingest/start-run';
import { runStatus } from '../api/fn/runs/run-status'; import { runStatus } from '../api/fn/runs/run-status';
import type { Pipeline } from '../api/models/pipeline'; import type { Pipeline } from '../api/models/pipeline';
@@ -122,8 +120,6 @@ export class Conectar {
protected readonly rawError = signal(''); protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) }); protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
/** The site's language model: Automático needs it. */
protected readonly llm = resource({ loader: () => this.api.invoke(languageModel) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) }); private readonly schema = resource({ loader: () => this.api.invoke(schema) });
protected readonly pipelineId = signal<string | undefined>(undefined); protected readonly pipelineId = signal<string | undefined>(undefined);
@@ -140,10 +136,6 @@ export class Conectar {
protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected())); protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected()));
protected readonly message = signal(''); protected readonly message = signal('');
protected readonly run = signal<{ id: string; status: string } | undefined>(undefined); protected readonly run = signal<{ id: string; status: string } | undefined>(undefined);
/** Automático drafts a pipeline that holds its sources only. */
protected readonly onlySources = computed(
() => this.docs().length > 0 && this.docs().every((d) => d.kind === 'source'),
);
protected readonly running = computed(() => { protected readonly running = computed(() => {
const run = this.run(); const run = this.run();
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
@@ -403,44 +395,20 @@ export class Conectar {
const id = this.pipelineId(); const id = this.pipelineId();
if (!id || !(await this.save())) return; if (!id || !(await this.save())) return;
try { try {
await this.follow((await this.api.invoke(startRun, { pipeline_id: id, body: {} }))['run_id']); const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
} catch (e) { this.run.set({ id: run_id, status: 'STARTING' });
this.message.set(problem(e)); while (this.running()) {
} await new Promise((r) => setTimeout(r, 2000));
} this.run.set({
id: run_id,
/** "Armar automáticamente": saves the sources, starts the `draft` job (the site's model status: (await this.api.invoke(runStatus, { run_id }))['status'],
* draws the whole pipeline, saves it as a new version and runs it) and, once it ends, });
* shows the version drawn. */
protected async automatic(): Promise<void> {
const id = this.pipelineId();
if (!id || !(await this.save())) return;
try {
this.message.set('Armando la canalización: se leen los documentos y el modelo los revisa.');
await this.follow((await this.api.invoke(startDraft, { pipeline_id: id }))['run_id']);
if (this.run()?.status === 'SUCCESS') {
await this.open(id);
this.message.set(
`Versión ${this.version()} armada y ejecutada. Revise lo que queda en Revisión.`,
);
this.list.reload();
} }
} catch (e) { } catch (e) {
this.message.set(problem(e)); this.message.set(problem(e));
} }
} }
private async follow(run_id: string): Promise<void> {
this.run.set({ id: run_id, status: 'STARTING' });
while (this.running()) {
await new Promise((r) => setTimeout(r, 2000));
this.run.set({
id: run_id,
status: (await this.api.invoke(runStatus, { run_id }))['status'],
});
}
}
/** What the node gives: a source's first rows, or what any other node gave in the last run. */ /** What the node gives: a source's first rows, or what any other node gave in the last run. */
protected async show(): Promise<void> { protected async show(): Promise<void> {
const doc = this.doc(); const doc = this.doc();
+3 -2
View File
@@ -3,7 +3,8 @@ import type { Figure } from './plot';
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */ /** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
export const METRIC_NAMES: Record<string, string> = { export const METRIC_NAMES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior (Hz)', posterior_rhythm: 'Ritmo posterior (Hz)',
spindles: 'Husos de sueño NREM (por min)', spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)', paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior', anteroposterior_gradient: 'Gradiente anteroposterior',
}; };
@@ -25,7 +26,7 @@ export const ZONE_NAMES: Record<string, string> = {
/** The association's biomarkers (core.tea.association.BIOMARKERS). */ /** The association's biomarkers (core.tea.association.BIOMARKERS). */
export const BIOMARKER_NAMES: Record<string, string> = { export const BIOMARKER_NAMES: Record<string, string> = {
spikes: 'Picos paroxísticos', spikes: 'Picos paroxísticos',
spindles: 'Husos de sueño NREM', spindles: 'Husos de sueño N2',
posterior_rhythm: 'Ritmo posterior', posterior_rhythm: 'Ritmo posterior',
gradient: 'Gradiente anteroposterior', gradient: 'Gradiente anteroposterior',
}; };
+51 -33
View File
@@ -2,44 +2,58 @@ import type { Figure } from '../plot';
import { PALETTE } from '../plot'; import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels'; import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them; a value may be absent (null). */ /** A curve with its band, as the reports give them. */
interface Band { interface Band {
x: number[]; x: number[];
y: (number | null)[]; y: number[];
low?: (number | null)[]; low?: (number | null)[];
high?: (number | null)[]; high?: (number | null)[];
} }
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The value or a gap: an absent value is not drawn (zero is a value). */
const orGap = (ys: (number | null)[]) => ys.map((v) => (finite(v) ? v : null)) as number[];
/** The runs of consecutive indices where both limits are known: the band is drawn there only /** The stretches of x where the curve has both limits: a band is drawn only there, never from a
* (an absent limit is no zero). */ * limit that is absent (an absent limit is not zero). */
function runs(b: Band): number[][] { function bandRuns(b: Band): number[][] {
const found: number[][] = [[]]; const runs: number[][] = [];
let run: number[] = [];
b.x.forEach((x, i) => { b.x.forEach((x, i) => {
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) found.at(-1)!.push(i); if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
else if (found.at(-1)!.length) found.push([]); else {
if (run.length > 1) runs.push(run);
run = [];
}
}); });
return found.filter((r) => r.length > 1); if (run.length > 1) runs.push(run);
return runs;
} }
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] { function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const bands = runs(b).map((run) => ({ const lines: Partial<Plotly.Data>[] = [];
x: [...run, ...[...run].reverse()].map((i) => b.x[i]), if (b.low && b.high) {
y: [...run.map((i) => b.high![i]), ...[...run].reverse().map((i) => b.low![i])] as number[], for (const run of bandRuns(b)) {
fill: 'toself' as const, const x = run.map((i) => b.x[i]);
fillcolor: `${colour}33`, lines.push({
line: { width: 0 }, x: [...x, ...[...x].reverse()],
hoverinfo: 'skip' as const, y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
showlegend: false, fill: 'toself',
type: 'scatter' as const, fillcolor: `${colour}33`,
})); line: { width: 0 },
return [ hoverinfo: 'skip',
...bands, showlegend: false,
{ x: b.x, y: orGap(b.y), name, type: 'scatter', mode: 'lines', line: { color: colour, dash } }, type: 'scatter',
]; });
}
}
lines.push({
x: b.x,
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name,
type: 'scatter',
mode: 'lines',
line: { color: colour, dash },
});
return lines;
} }
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's /** What a model's interpretability report draws, by its kind: survival curves, the mixture's
@@ -302,26 +316,30 @@ export function scenarioFigure(
}; };
} }
/** The model's points; a point without both limits has no bar, and none has: no bars. */ /** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
* point without both limits has no bar. */
function points( function points(
name: string, name: string,
x: number[], x: number[],
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] }, p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> { ): Partial<Plotly.Data> {
const bars = p.S.map((v, i) => { const errors = p.S.map((value, i) => {
const [low, high] = [p.low?.[i], p.high?.[i]]; const low = p.low?.[i];
return finite(v) && finite(low) && finite(high) ? [high - v, v - low] : null; const high = p.high?.[i];
return finite(value) && finite(low) && finite(high)
? { up: high - value, down: value - low }
: null;
}); });
return { return {
x, x,
y: orGap(p.S), y: p.S.map((v) => (finite(v) ? v : null)) as number[],
...(bars.some((e) => e) ...(errors.some((error) => error !== null)
? { ? {
error_y: { error_y: {
type: 'data' as const, type: 'data' as const,
symmetric: false, symmetric: false,
array: bars.map((e) => e?.[0] ?? null) as number[], array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: bars.map((e) => e?.[1] ?? null) as number[], arrayminus: errors.map((error) => error?.down ?? null) as number[],
}, },
} }
: {}), : {}),
+527 -40
View File
@@ -1,10 +1,66 @@
import { bars, Mode } from './bars'; import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { scenarioBars } from './figures';
import { Reading } from './measures'; import { Reading } from './measures';
const read = (r: Reading) => () => r;
const cells = (mode: Mode, r: Reading) => bars(mode, read(r))!.rows.map((x) => x.cells);
describe('bars', () => { describe('bars', () => {
it('shows histologic types by BI-RADS while deriving malignancy from biopsy classification', () => {
const type: Reading = {
populations: {},
strata: {
category: { '8500/3': { 'initial-population': 1 }, no_data: { 'initial-population': 1 } },
birads: { '4A': { 'initial-population': 2 } },
'birads-category': {
'4A|8500/3': { 'initial-population': 1 },
'4A|no_data': { 'initial-population': 1 },
},
},
};
const classification: Reading = {
populations: {},
strata: {
'birads-category': {
'4A|benign': { 'initial-population': 1 },
'4A|invasive': { 'initial-population': 1 },
},
},
};
const mode: Mode = {
kind: 'outcomes',
label: 'Por categoría BI-RADS',
measure: 'types',
stratum: 'birads',
rows: [{ code: '4A', label: '4A', color: '#000' }],
results: [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#aaa' },
{ code: 'no_data', label: 'Sin dato', color: '#bbb' },
],
malignant: ['in_situ', 'invasive'],
dynamicResults: true,
malignancyMeasure: 'grades',
};
const table = bars(mode, (key) => (key === 'types' ? type : classification))!;
expect(table.head).toEqual(['Pacientes', 'Carcinoma ductal infiltrante', 'Sin biopsia', 'Sin dato', '% maligno']);
expect(table.rows[0].cells).toEqual(['2', '1', '0', '1', '1/2 (50.0 %)']);
expect(bars(mode, (key) => (key === 'types' ? type : undefined))!.rows[0].cells.at(-1)).toBe(
'No disponible',
);
});
it('lists histologic codes from gold and preserves missing types in the denominator', () => {
const r: Reading = {
populations: { 'initial-population': 4 },
strata: {
category: { '8500/3': { 'initial-population': 1 }, no_data: { 'initial-population': 3 } },
},
};
const table = bars(
{ kind: 'counts', label: 'Tipos histológicos', measure: 'M', catalog: [], unit: 'Biopsias' },
() => r,
)!;
expect(table.rows.map((row) => [row.label, ...row.cells])).toEqual([
['Carcinoma ductal infiltrante', '1', '25.0 %'],
['Sin dato', '3', '75.0 %'],
]);
});
it('list every category, so the shares add up', () => { it('list every category, so the shares add up', () => {
const r: Reading = { const r: Reading = {
populations: {}, populations: {},
@@ -13,60 +69,491 @@ describe('bars', () => {
}, },
}; };
const catalog = [{ code: 'a', label: 'A', color: '#000' }]; const catalog = [{ code: 'a', label: 'A', color: '#000' }];
expect(cells({ kind: 'counts', label: 'x', measure: 'M', catalog }, r)).toEqual([ const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '75.0 %'], ['3', '75.0 %'],
['1', '25.0 %'], ['1', '25.0 %'],
]); ]);
}); });
it('add up an aggregate after the first row and indent its parts', () => { it('aggregates only named abnormal cytology results without changing the denominator', () => {
const cell = (n: number) => ({ 'initial-population': n });
const r: Reading = { const r: Reading = {
populations: {}, populations: { 'initial-population': 10 },
strata: { strata: {
category: { category: { NILM: cell(4), LSIL: cell(2), HSIL: cell(1), no_data: cell(3) },
n: { 'initial-population': 6 }, 'age_group-category': {
a: { 'initial-population': 3 }, '25-34|NILM': cell(4),
b: { 'initial-population': 1 }, '25-34|LSIL': cell(2),
'25-34|HSIL': cell(1),
'25-34|no_data': cell(3),
}, },
}, },
}; };
const catalog = ['n', 'a', 'b'].map((code) => ({ code, label: code, color: '#000' })); const catalog = ['NILM', 'LSIL', 'HSIL'].map((code) => ({ code, label: code, color: '#000' }));
const aggregate = { label: 'Anormal', color: '#f00', codes: ['a', 'b'] }; const aggregate = { label: 'Anormal', color: '#f00', codes: ['LSIL', 'HSIL'] };
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, read(r))!; const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, () => r)!;
expect(t.rows.map((x) => [x.label, x.cells[0], !!x.sub])).toEqual([ expect(t.rows[1].cells).toEqual(['3', '30.0 %']);
['n', '6', false], expect(t.rows.map((row) => !!row.sub)).toEqual([false, false, true, true, false].slice(0, t.rows.length));
['Anormal', '4', false], const g = grouped(
['a', '3', true], {
['b', '1', true], kind: 'grouped',
label: 'x',
measure: 'M',
catalog,
aggregate,
stratum: 'age_group',
order: ['25-34'],
unit: 'pacientes',
ofAll: true,
},
() => r,
)!;
expect(g.groups[0].rows[1].text).toBe('3/10 · 30.0 %');
});
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: {},
strata: { s: { initial: { numerator: 0, denominator: 0 } } },
};
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
describe('screening rounds (complete)', () => {
const ORDER = ['initial', 'subsequent', 'no_data'];
const cell = (numerator: number, denominator: number) => ({ numerator, denominator });
const ppv = (strata: Record<string, any>, total: number): Reading => ({
populations: { 'initial-population': total, denominator: total },
strata: { round: strata },
});
const mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
} as const;
it('lists the three groups in order with their own counts', () => {
const r = ppv({ no_data: cell(1, 4), subsequent: cell(6, 10), initial: cell(0, 6) }, 20);
const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial',
'Con detección anterior',
'Sin dato',
]);
expect(t.rows.map((x) => x.cells)).toEqual([
['0/6', '0.0 %'],
['6/10', '60.0 %'],
['1/4', '25.0 %'],
]);
expect(t.note).toBeUndefined();
});
it('a group the report leaves out is zero patients when the counts add up', () => {
const r = ppv({ no_data: cell(0, 3), subsequent: cell(6, 10) }, 13);
const initial = bars(mode, () => r)!.rows[0];
expect(initial.cells).toEqual(['0/0', '—']);
expect(initial.hint).toBe('Sin pacientes en el periodo');
});
it('a group left out is not available when the counts do not add up', () => {
const r = ppv({ subsequent: cell(6, 10) }, 13);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['—', '—']);
expect(t.rows[0].hint).toBe('No disponible');
expect(t.note).toContain('no concilian');
});
it('a zero numerator over a positive denominator is 0 %, a zero denominator has no rate', () => {
const r = ppv({ initial: cell(0, 5), subsequent: cell(0, 0), no_data: cell(2, 3) }, 8);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['0/5', '0.0 %']);
expect(t.rows[1].cells).toEqual(['0/0', '—']);
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
});
it('warns when only "Sin dato" holds patients', () => {
const r = ppv({ no_data: cell(3, 7) }, 7);
const t = bars(mode, () => r)!;
expect(t.rows[2].cells).toEqual(['3/7', '42.9 %']);
expect(t.note).toContain('información no registrada');
});
it('draws nothing without patients and says "No disponible" without the stratifier', () => {
expect(bars(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 9))).toContain('No disponible');
expect(bars(mode, () => ppv({}, 9))).toBeUndefined();
});
it('a cell that is not whole or has a numerator above its denominator is not available', () => {
const r = ppv({ initial: cell(5, 3), subsequent: cell(1, 2), no_data: cell(0, 1) }, 6);
expect(bars(mode, () => r)!.rows[0].hint).toBe('No disponible');
});
it('VPH positives: groups from the crossed cells, absent ones reconciled', () => {
const r: Reading = {
populations: { 'initial-population': 12 },
strata: {
'round-category': {
'subsequent|positive': { 'initial-population': 3 },
'subsequent|negative': { 'initial-population': 7 },
'no_data|negative': { 'initial-population': 2 },
},
},
};
const t = bars(
{
kind: 'positives',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
},
() => r,
)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['0/0', '—'],
['3/10', '30.0 %'],
['0/2', '0.0 %'],
]);
});
});
describe('cytology by round', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#0a0', group: '' },
{ code: 'HSIL', label: 'LIEAG', color: '#a00', group: '' },
];
const reading = (cells: Record<string, number>, total: number): Reading => ({
populations: { 'initial-population': total },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const draw = (r: Reading) =>
scenarioBars(
r,
{ groups: [], categories: cats },
'round',
(c) =>
c === 'initial'
? 'Detección inicial'
: c === 'subsequent'
? 'Con detección anterior'
: 'Sin dato',
['initial', 'subsequent', 'no_data'],
{ fill: true },
);
it('keeps the order and shows each bar with its n, an empty one included', () => {
const f = draw(
reading({ 'subsequent|NILM': 6, 'subsequent|HSIL': 2, 'no_data|NILM': 2 }, 10),
);
const y = (f.data[0] as any).y;
expect(y).toEqual([
'Detección inicial<br>Pacientes: 0',
'Con detección anterior<br>Pacientes: 8',
'Sin dato<br>Pacientes: 2',
]);
expect((f.data[0] as any).x).toEqual([0, 75, 100]);
});
it('leaves out a group that does not reconcile', () => {
const f = draw(reading({ 'subsequent|NILM': 6 }, 10));
expect((f.data[0] as any).y).toEqual(['Con detección anterior<br>Pacientes: 6']);
});
});
});
describe('shared views of cytology and HPV by genotype', () => {
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' },
{ code: 'positive_other', label: 'Positivo sin genotipo', color: '#A8C243', group: '' },
];
const reading = (cells: Record<string, number>): Reading => ({
populations: { 'initial-population': Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
category: {
negative: { 'initial-population': 5 },
positive_other: { 'initial-population': 2 },
positive_incomplete: { 'initial-population': 3 },
},
'age_group-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const counts: Mode = {
kind: 'counts',
label: 'General',
measure: 'M',
catalog: HPV,
hidden: { codes: ['positive_incomplete', 'inconsistent'], unit: 'reportes' },
};
it('does not list a hidden category but keeps it in the total and the percentages', () => {
const t = bars(counts, () => reading({}))!;
expect(t.rows.map((x) => x.label)).toEqual(['Negativo', 'Positivo sin genotipo']);
expect(t.rows.map((x) => x.cells)).toEqual([
['5', '50.0 %'],
['2', '20.0 %'],
]); // of 10 reports
expect(t.note).toBe(
'3 reportes (Positivo con genotipificación incompleta) no se muestran desglosados; están incluidos en el total y en los porcentajes.',
);
});
it('says nothing when no report is hidden', () => {
const r: Reading = {
populations: {},
strata: { category: { negative: { 'initial-population': 1 } } },
};
expect(hiddenNote(counts, () => r)).toBeUndefined();
});
it('a figure by groups is not available without its breakdown, and counts every record of the group on request', () => {
const mode = {
kind: 'figure',
label: 'Por grupo de edad',
measure: 'M',
figure: 'scenarios',
stratum: 'age_group',
catalog: HPV,
} as const;
const noBreakdown: Reading = {
populations: { 'initial-population': 4 },
strata: { category: {} },
};
expect(unavailable(mode, () => noBreakdown)).toBe(
'No disponible: el informe de este periodo no publica el desglose «Por grupo de edad».',
);
const r: Reading = {
populations: { 'initial-population': 10 },
strata: {
'age_group-category': {
'25-34|negative': { 'initial-population': 4 },
'25-34|positive_other': { 'initial-population': 1 },
'25-34|positive_incomplete': { 'initial-population': 5 },
},
},
};
const label = (c: string) => c;
const own = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34']);
const all = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34'], {
ofAll: true,
});
expect((own.data[0] as any).x).toEqual([80]); // 4 of the 5 the catalog draws
expect((all.data[0] as any).x).toEqual([40]); // 4 of the group's 10 reports
expect((all.data[0] as any).y).toEqual(['25-34<br>Reportes: 10']);
});
});
describe('independent bars by group', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#408651' },
{ code: 'HSIL', label: 'LIEAG', color: '#CE4778' },
];
const mode = (more: object = {}): Mode =>
({
kind: 'grouped',
label: 'x',
measure: 'M',
catalog: cats,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
unit: 'pacientes',
...more,
}) as Mode;
const reading = (cells: Record<string, number>, total?: number): Reading => ({
populations: { 'initial-population': total ?? Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
it('draws one bar per category in each group: count, denominator and percent over its own records', () => {
const g = grouped(mode(), () =>
reading({ 'initial|NILM': 3, 'initial|HSIL': 1, 'subsequent|NILM': 6 }),
)!;
expect(g.groups.map((x) => [x.label, x.total])).toEqual([
['Detección inicial', 4],
['Con detección anterior', 6],
]);
expect(g.groups[0].rows.map((r) => [r.label, r.text, r.percent, r.color])).toEqual([
['Normal', '3/4 · 75.0 %', 75, '#408651'],
['LIEAG', '1/4 · 25.0 %', 25, '#CE4778'],
]);
expect(g.groups[1].rows.map((r) => r.text)).toEqual(['6/6 · 100.0 %', '0/6 · 0.0 %']); // a zero numerator is 0 %
});
it('an empty group has no percent; with complete it is drawn only when the counts reconcile', () => {
const empty = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2, 'no_data|HSIL': 1 }),
)!;
expect(empty.groups.map((x) => x.code)).toEqual(['initial', 'subsequent', 'no_data']);
expect(empty.groups[0]).toMatchObject({ total: 0, hint: 'Sin pacientes en el grupo' });
expect(empty.groups[0].rows.map((r) => [r.text, r.percent])).toEqual([
['0/0 · —', undefined],
['0/0 · —', undefined],
]);
expect(empty.note).toBeUndefined();
const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5),
)!;
expect(unreconciled.groups.map((x) => x.code)).toEqual(['subsequent']);
expect(unreconciled.note).toContain('no concilian');
const open = grouped(mode(), () => reading({ 'subsequent|NILM': 2 }))!;
expect(open.groups.map((x) => x.code)).toEqual(['subsequent']); // without complete: only the listed groups
});
it('each group may count all its records, hidden categories included', () => {
const r = reading({ 'initial|NILM': 2, 'initial|positive_incomplete': 2 });
const own = grouped(mode(), () => r)!;
const all = grouped(mode({ ofAll: true }), () => r)!;
expect(own.groups[0].total).toBe(2);
expect(all.groups[0].total).toBe(4);
expect(all.groups[0].rows[0].text).toBe('2/4 · 50.0 %');
});
it('is not available without the breakdown, and draws nothing without records', () => {
const none: Reading = { populations: { 'initial-population': 4 }, strata: {} };
expect(grouped(mode(), () => none)).toBeUndefined();
expect(unavailable(mode(), () => none)).toContain('No disponible');
expect(grouped(mode(), () => reading({}, 0))).toBeUndefined();
});
it('says that unclassified records leave a classified group empty, and warns when none is classified', () => {
const lone = grouped(mode({ complete: true }), () => reading({ 'no_data|NILM': 3 }))!;
expect(lone.note).toContain('información no registrada');
});
it('a proportion split into its parts shows both in units and shares', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const t = bars({ kind: 'split', label: 'x', measure: 'M', yes: 'Con', no: 'Sin' }, () => r)!;
expect(t.rows.map((x) => [x.label, ...x.cells])).toEqual([
['Con', '1', '25.0 %'],
['Sin', '3', '75.0 %'],
]); ]);
}); });
it('draw a proportion with its interval as marks', () => { it('rows with patients and no biopsy are not rows with no patients; malignant counts only graded', () => {
const r: Reading = { const r: Reading = {
populations: { numerator: 51, denominator: 70 }, populations: {},
strata: {}, strata: {
score: 0.729, birads: {
low: 0.615, '4A': { 'initial-population': 3 },
high: 0.819, '5': { 'initial-population': 4 },
'6': { 'initial-population': 2 },
},
'birads-category': {
'4A|no_biopsy': { 'initial-population': 3 },
'5|benign': { 'initial-population': 1 },
'5|invasive': { 'initial-population': 1 },
'5|no_data': { 'initial-population': 2 },
'6|no_data': { 'initial-population': 2 },
},
},
}; };
const t = bars({ kind: 'ratio', label: 'Total', measure: 'M' }, read(r))!; const results = [
expect(t.rows[0].cells).toEqual(['51/70', '72.9 %', '61.5 %–81.9 %']); { code: 'benign', label: 'Benigno', color: '#1' },
expect(t.rows[0].marks.map(Math.round)).toEqual([62, 82]); { code: 'invasive', label: 'Invasor', color: '#2' },
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#3' },
{ code: 'no_data', label: 'Sin dato', color: '#4' },
];
const rows = ['4A', '5', '6', '4B'].map((code) => ({ code, label: code, color: '#0' }));
const mode = {
kind: 'outcomes',
label: 'x',
measure: 'M',
stratum: 'birads',
rows,
results,
malignant: ['invasive'],
};
const t = bars(mode as any, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '0', '0', '3', '0', 'Sin biopsias'],
['4', '1', '1', '0', '2', '1/2 (50.0 %)'],
['2', '0', '0', '0', '2', 'Sin biopsias clasificables'],
['0', '—', '—', '—', '—', '—'],
]);
expect(t.rows.map((x) => x.none)).toEqual([
undefined,
undefined,
undefined,
'Sin pacientes en el periodo',
]);
expect(t.rows[1].segments!.map((x) => x.width)).toEqual([25, 25, 0, 50]);
}); });
it('stagger steps from where the step they follow ends', () => { it('bars on a percent scale are as long as the shares shown', () => {
const at: Record<string, Reading> = { const r: Reading = {
A: { populations: { 'measure-observation': 3 }, strata: {}, score: 10 }, populations: {},
B: { populations: { 'measure-observation': 2 }, strata: {}, score: 30 }, strata: { category: { a: { 'initial-population': 1 }, b: { 'initial-population': 3 } } },
C: { populations: { 'measure-observation': 1 }, strata: {}, score: 20 },
}; };
const catalog = [
{ code: 'a', label: 'A', color: '#0' },
{ code: 'b', label: 'B', color: '#1' },
{ code: 'c', label: 'C', color: '#2' },
];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, percent: true }, () => r)!;
expect(t.rows.map((x) => x.width)).toEqual([25, 75, 0]);
expect(t.rows.map((x) => x.cells)).toEqual([
['1', '25.0 %'],
['3', '75.0 %'],
['0', '0.0 %'],
]);
});
it('a split takes the colours it is given', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const mode = {
kind: 'split',
label: 'x',
measure: 'M',
yes: 'Con',
no: 'Sin',
colors: ['#a', '#b'],
};
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
});
});
describe('the subsequent round by last screening', () => {
it('chains the steps of a time window, quartiles moving with their bar', () => {
const median = (score: number, low: number, high: number): Reading => ({
populations: { 'measure-observation': 1 },
strata: {},
score,
low,
high,
});
const steps = [ const steps = [
{ label: 'a', measure: 'A' }, { label: 'a', measure: 'A' },
{ label: 'b', measure: 'B' }, { label: 'b', measure: 'B' },
{ label: 'c', measure: 'C', after: 0 },
{ label: 'd', measure: 'D' },
]; ];
const mode: Mode = { kind: 'days', label: 'x', steps, staggered: true, scale: true }; const table = bars({ kind: 'days', label: 'x', steps, staggered: true }, (m) =>
const t = bars(mode, (m) => at[m])!; m === 'A' ? median(10, 5, 10) : median(20, 10, 30),
expect(t.rows.map((x) => x.offset)).toEqual([0, 25, 25, undefined]); )!;
expect(t.rows[3].none).toBe('Sin mediciones en el periodo'); expect(table.rows.map((r) => [r.offset, r.width, r.marks])).toEqual([
expect(t.note).toBe('Escala: 0 a 40 días.'); [0, 25, [12.5, 25]],
[25, 50, [50, 100]],
]);
});
it('splits the subsequent round by last screening, drawing only those with an answer', () => {
const one = { 'initial-population': 1 };
const r: Reading = {
populations: { 'initial-population': 3 },
strata: {
'round-category': { 'initial|a': one, 'subsequent|a': { 'initial-population': 2 } },
'subsequent_history-category': { 'within_1_year|a': one, 'no_data|a': one },
},
};
const mode: Mode = {
kind: 'grouped',
label: 'x',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent'],
unit: 'pacientes',
catalog: [{ code: 'a', label: 'A', color: '#000' }],
};
const { groups } = grouped(mode, () => r)!;
expect(groups.map((g) => [g.code, g.total])).toEqual([
['initial', 1],
['within_1_year', 1],
['2_years', 0],
['3_or_more_years', 0],
]);
}); });
}); });
+554 -164
View File
@@ -1,42 +1,32 @@
import { name } from './labels'; import { CIE10 } from './cie10';
import { Reading } from './measures'; import { chainStarts } from './durations';
import { NEUTRAL_DARK } from './palette-cacu'; import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */ /** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string }; export type Category = { code: string; label: string; color: string };
/** A colour by code (the category decides it, never its place in the report). */
export type Colors = Record<string, string>;
/** Categories a card leaves out of its rows: their records stay in its total and its shares. */
export type Hidden = { codes: string[]; unit: string };
/** A row adding up some categories, drawn after the first one; those are indented under it. */
export type Aggregate = { label: string; color: string; codes: string[] };
/** A step of a route; staggered, it starts where step `after` (by default, the previous) ends. */
export type Step = { label: string; measure: string; after?: number };
export type Read = (measure: string) => Reading | undefined;
/** One way of reading a card: the bars of a table, or groups of bars (`grouped`). */ /** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = { export type Mode = {
label: string; label: string;
caption?: string; caption?: string;
/** said above the table: what its rows count */ /** said above the table: what its rows count (patients, reported biopsies…) */
heading?: string; heading?: string;
/** the header of the rows' names */
rowsLabel?: string;
} & ( } & (
| { | {
kind: 'counts'; kind: 'counts';
measure: string; measure: string;
catalog: Category[]; catalog: Category[];
aggregate?: Aggregate; aggregate?: { label: string; color: string; codes: string[] };
/** The records counted in the category distribution. */
unit?: string; unit?: string;
/** What the share in the second column is a share of. */
percentLabel?: string; percentLabel?: string;
hidden?: Hidden; hidden?: Hidden;
/** every bar on 0 to 100 % of the total, its length the share shown */ /** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
percent?: boolean; percent?: boolean;
} }
| { | {
/** a proportion by group; `complete`: every group of `order`, those left out as zero
* when the listed ones add up to every patient (see `reconciles`) */
kind: 'shares'; kind: 'shares';
measure: string; measure: string;
stratum: string; stratum: string;
@@ -46,34 +36,62 @@ export type Mode = {
percentLabel?: string; percentLabel?: string;
} }
| { | {
/** per group (`<stratum>-category` cells), an independent bar per category */ kind: 'positives';
kind: 'grouped';
measure: string; measure: string;
catalog: Category[];
aggregate?: Aggregate;
stratum: string; stratum: string;
order: string[]; order: string[];
unit: string;
complete?: boolean; complete?: boolean;
/** a group's denominator is all its records, not only its categories' */ colors?: Colors;
percentLabel?: string;
}
| {
kind: 'signs';
measure: string;
strata: string[];
colors?: Colors;
percentLabel?: string;
}
| {
kind: 'grouped';
measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
stratum: string;
order: string[];
/** what the records are called ("pacientes", "reportes") */
unit: string;
/** The denominator of the percentage shown with each grouped result. */
percentLabel?: string;
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
complete?: boolean;
/** each group's denominator is all its records, not only those of the catalog's categories */
ofAll?: boolean; ofAll?: boolean;
hidden?: Hidden; hidden?: Hidden;
} }
| { kind: 'days'; steps: Step[]; tint?: Tint; staggered?: boolean; scale?: boolean } | {
/** a proportion as one bar of 0 to 100 %, its 95 % interval the two marks */ kind: 'days';
| { kind: 'ratio'; measure: string; color?: string; percentLabel?: string } steps: { label: string; measure: string }[];
/** a proportion as its two parts, what counted and what did not */ tint?: Tint;
/** each bar starts where the previous one ends (a schematic sequence, as a Gantt chart) */
staggered?: boolean;
}
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
| { kind: 'ratio'; measure: string; colors?: Colors; percentLabel?: string }
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { | {
kind: 'split'; kind: 'split';
measure: string; measure: string;
yes: string; yes: string;
no: string; no: string;
colors: [string, string]; colors?: [string, string];
unit: string; unit?: string;
percentLabel: string; percentLabel?: string;
} }
/** each row's units by result, in segments, and the malignant share of those with a grade /** Each row's units by result (a bar in segments), and the share of the row's units with a
* (read from `malignancy`); the results are the period's, then `results` */ * result that are `malignant`; a row with units and no result is not a row with none */
| { | {
kind: 'outcomes'; kind: 'outcomes';
measure: string; measure: string;
@@ -81,211 +99,583 @@ export type Mode = {
rows: Category[]; rows: Category[];
results: Category[]; results: Category[];
malignant: string[]; malignant: string[];
malignancy: string; dynamicResults?: boolean;
malignancyMeasure?: string;
}
| {
kind: 'figure';
measure: string;
figure: 'donut' | 'scenarios';
/** a donut's colour by part (a category, or numerator and rest); none: the page's palette */
colors?: Colors;
catalog?: Category[];
/** the stratifier a scenarios figure crosses with the category (default: the follow-up status) */
stratum?: string;
order?: string[];
/** draw the groups of `order` the report leaves out as zero (see `reconciles`) */
complete?: boolean;
/** each bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
hidden?: Hidden;
} }
); );
/** Categories a card does not draw: their records stay in the total and in the percentages. */
export type Hidden = { codes: string[]; unit: string };
/** A colour by category code (the category decides it, not its place in the report). */
export type Colors = Record<string, string>;
/** The colours of a median bar and of the marks of its quartiles. */
export type Tint = { bar: string; mark: string }; export type Tint = { bar: string; mark: string };
/** One bar: its start, length and marks in % of the scale, and its cells of text. */ /** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
export interface Bar { export interface GroupRow {
label: string;
/** indented under the aggregate above it */
sub?: boolean; sub?: boolean;
/** why the row has no figures */ label: string;
color: string;
count: number;
/** the group's records (the denominator) */
of: number;
/** none when the group has no records: a rate over nothing is not drawn */
percent?: number;
/** "2/5 · 40.0 %"; "0/0 · —" for an empty group */
text: string;
}
export interface Group {
code: string;
label: string;
/** the group's records */
total: number;
/** why the group has no figures */
hint?: string;
rows: GroupRow[];
}
export interface Groups {
groups: Group[];
note?: string;
}
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar {
/** one of the categories the aggregate row above adds up */
sub?: boolean;
label: string;
/** why the row has no figures: no patients in the group, or not available */
hint?: string; hint?: string;
color?: string; color?: string;
/** where the bar starts, in % of the scale */
offset?: number; offset?: number;
width: number; width: number;
marks: number[]; marks: number[];
cells: string[]; cells: string[];
/** the bar in parts, each with what it says when hovered */ /** the bar in parts (in % of the bar), each with what it says when hovered */
segments?: { width: number; color: string; title: string }[]; segments?: { width: number; color: string; title: string }[];
/** said in place of the bar */ /** said in place of the bar (a row with nothing to draw) */
none?: string; none?: string;
} }
export interface Bars { export interface Bars {
head: string[]; head: string[];
rows: Bar[]; rows: Bar[];
/** the colour of the quartile marks, when the card has its own */
markColor?: string; markColor?: string;
/** what the reader must know to take the rows right */ /** what the reader must know to take the rows right */
note?: string; note?: string;
/** the colours of the segments */
legend?: { label: string; color: string }[]; legend?: { label: string; color: string }[];
} }
export const NOT_AVAILABLE = 'No disponible'; export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo'; export const NO_PATIENTS = 'Sin pacientes en el periodo';
export const NO_ROUND = const NO_ROUND =
'Ninguna paciente del periodo tiene clasificación de detección inicial o anterior: los ' + 'Ninguna paciente del periodo tiene clasificación de detección inicial o anterior: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
'grupos en cero reflejan información no registrada, no ausencia de pacientes.';
export const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—'); const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
export const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
export const whole = (n: unknown): n is number =>
typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** The patients of a reading: its cohort, or a proportion's denominator. */ /** A group the report does not list is zero patients only when the groups it lists add up to every
* patient of the period (the report leaves out empty groups); otherwise it is not available. */
export function reconciles(listed: number[], total: number): boolean {
return listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
}
/** The patients of a reading: its cohort, or the denominator of a proportion. */
export const patients = (r?: Reading) => export const patients = (r?: Reading) =>
r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0; r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
/** A group the report leaves out is zero only when the listed groups add up to every record /** Why a card of a "complete" mode, or a figure by groups, has nothing to draw though its period
* (the report omits empty groups); otherwise it is not available. */ * has records: the report does not publish the breakdown. Undefined when there is nothing to say. */
export const reconciles = (listed: number[], total: number) => export function unavailable(
listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total; mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
const groups = mode.kind === 'grouped' || (mode.kind === 'figure' && mode.figure === 'scenarios');
const complete = 'complete' in mode && mode.complete;
if (!(groups || complete) || !('stratum' in mode) || !mode.stratum) return undefined;
const r = of(mode.measure);
if (!patients(r)) return undefined;
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
return Object.keys(r?.strata[key] ?? {}).length
? undefined
: `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
}
/** What a card says of the categories it does not draw, when the period has any. */ /** What a card says about the categories it does not draw: how many records they hold and that
export function hiddenNote(mode: Mode, read: Read): string | undefined { * they stay in the total and the percentages. Undefined when none is in the period. */
export function hiddenNote(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
if (!('hidden' in mode) || !mode.hidden) return undefined; if (!('hidden' in mode) || !mode.hidden) return undefined;
const cells = read(mode.measure)?.strata['category'] ?? {}; const { codes, unit } = mode.hidden;
const found = mode.hidden.codes.filter((c) => size(cells[c])); const cells = of(mode.measure)?.strata['category'] ?? {};
const found = codes.filter((c) => size(cells[c]));
if (!found.length) return undefined;
const n = found.reduce((t, c) => t + size(cells[c]), 0); const n = found.reduce((t, c) => t + size(cells[c]), 0);
if (!n) return undefined; const names = found.map((c) => name(c)).join(', ');
const [unit, words] = const one = n === 1;
n === 1 return `${n} ${one ? unit.replace(/s$/, '') : unit} (${names}) ${one ? 'no se muestra desglosado; está incluido' : 'no se muestran desglosados; están incluidos'} en el total y en los porcentajes.`;
? [mode.hidden.unit.replace(/s$/, ''), 'no se muestra desglosado; está incluido']
: [mode.hidden.unit, 'no se muestran desglosados; están incluidos'];
return `${n} ${unit} (${found.map(name).join(', ')}) ${words} en el total y en los porcentajes.`;
} }
/** Rows with an aggregate's row after the first, its parts marked by `sub`. */ const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
export function withAggregate<T>( const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
rows: T[], const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
codes: string[],
aggregate: Aggregate | undefined,
sum: () => T,
sub: (row: T) => T,
): T[] {
if (!aggregate || !rows.length) return rows;
const marked = rows.map((row, i) => (aggregate.codes.includes(codes[i]) ? sub(row) : row));
return [marked[0], sum(), ...marked.slice(1)];
}
/** The bars of a mode; none when the period has nothing to draw. */ /** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, read: Read): Bars | undefined { export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) { switch (mode.kind) {
case 'counts':
return counts(mode, read);
case 'ratio': { case 'ratio': {
const r = read(mode.measure); const r = of(mode.measure);
const { numerator: n = 0, denominator: total = 0 } = r?.populations ?? {}; const n = r?.populations['numerator'] ?? 0;
const total = r?.populations['denominator'] ?? 0;
if (r?.score === undefined || !total) return undefined; if (r?.score === undefined || !total) return undefined;
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : []; const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
const cells = [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'];
return { return {
head: ['n/N', mode.percentLabel ?? 'Porcentaje', 'IC 95 %'], head: ['n/N', mode.percentLabel ?? 'Porcentaje', 'IC 95 %'],
rows: [ rows: [
{ {
label: 'Total', label: 'Total',
color: mode.color, color: mode.colors?.['numerator'],
width: 100 * r.score, width: 100 * r.score,
cells,
marks: ends.map((v) => 100 * v), marks: ends.map((v) => 100 * v),
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
}, },
], ],
}; };
} }
case 'split': { case 'counts': {
const { numerator: n = 0, denominator: total = 0 } = read(mode.measure)?.populations ?? {}; const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
if (!total) return undefined; if (!total) return undefined;
// a category outside the catalog is listed after it, so the shares add up
const hidden = mode.hidden?.codes ?? [];
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c) && !hidden.includes(c));
const all = [
...mode.catalog.filter((c) => !hidden.includes(c.code)),
...rest.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
];
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return { return {
head: [mode.unit, mode.percentLabel], head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: ( rows: all.flatMap(({ code, label, color }, index) => {
[ const n = size(cells[code]);
[mode.yes, n], const cols = [`${n}`, pct(n, total)];
[mode.no, total - n], const part = !!mode.aggregate?.codes.includes(code);
] as const const row = { label, color, width: (100 * n) / most, marks: [], cells: cols, sub: part };
).map(([label, k], i) => ({ if (index !== 0 || !mode.aggregate) return [row];
const a = mode.aggregate;
const sum = a.codes.reduce((total, key) => total + size(cells[key]), 0);
return [
row,
{
label: a.label,
color: a.color,
width: (100 * sum) / most,
marks: [],
cells: [`${sum}`, pct(sum, total)],
},
];
}),
note: hiddenNote(mode, of),
};
}
case 'shares': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
if (!mode.complete)
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [
name(c),
cells[c]['numerator'] ?? 0,
cells[c]['denominator'] ?? 0,
mode.colors?.[c],
]),
mode.percentLabel,
);
if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) =>
whole(cells[c]?.['numerator']) &&
whole(cells[c]?.['denominator']) &&
cells[c]['numerator'] <= cells[c]['denominator'];
const ok = reconciles(
Object.keys(cells).map((c) => cells[c]['denominator']),
patients(r),
);
return complete(
mode.order,
Object.keys(cells),
ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors,
mode.percentLabel,
);
}
case 'positives': {
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
if (!mode.complete)
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
}),
mode.percentLabel,
);
if (!patients(r) || !found.size) return undefined;
const ok = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
return complete(
mode.order,
[...found],
ok,
(c) => {
const positive = size(cells[`${c}|positive`]);
return [positive, positive + size(cells[`${c}|negative`])];
},
mode.colors,
mode.percentLabel,
);
}
case 'signs': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}),
mode.percentLabel,
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
mode.tint,
mode.staggered,
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
mode.tint,
);
}
case 'split': {
const { numerator = 0, denominator = 0 } = of(mode.measure)?.populations ?? {};
if (!denominator) return undefined;
const parts: [string, number][] = [
[mode.yes, numerator],
[mode.no, denominator - numerator],
];
return {
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: parts.map(([label, n], i) => ({
label, label,
color: mode.colors[i], color: mode.colors?.[i],
width: (100 * k) / total, width: (100 * n) / denominator,
marks: [], marks: [],
cells: [`${k}`, pct(k, total)], cells: [`${n}`, pct(n, denominator)],
})), })),
}; };
} }
case 'days': case 'outcomes': {
return medians(mode, read); const r = of(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const colors = ['#5C42C2', '#C24269', '#9C42C2', '#A8C243', '#2778B8', '#B19525'];
const actual = Object.keys(r?.strata['category'] ?? {})
.filter((code) => !['no_biopsy', 'no_data'].includes(code))
.sort();
const results = mode.dynamicResults
? [
...actual.map((code, i) => ({
code,
label: name(code),
color: colors[i % colors.length],
})),
...mode.results,
]
: mode.results;
const malignancy = mode.malignancyMeasure ? of(mode.malignancyMeasure) : r;
const hasMalignancy = !!malignancy?.strata[`${mode.stratum}-category`];
const malignancyCells = malignancy?.strata[`${mode.stratum}-category`] ?? {};
const grades = ['benign', 'in_situ', 'invasive'];
return {
head: ['Pacientes', ...results.map((x) => x.label), '% maligno'],
legend: results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]);
const by = results.map((x) => size(cells[`${code}|${x.code}`]));
const den = grades.reduce((t, grade) => t + size(malignancyCells[`${code}|${grade}`]), 0);
const bad = mode.malignant.reduce(
(t, grade) => t + size(malignancyCells[`${code}|${grade}`]),
0,
);
return {
label,
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: results.map((x, i) => ({
width: n ? (100 * by[i]) / n : 0,
color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
})),
cells: [
`${n}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? !hasMalignancy
? 'No disponible'
: den
? `${bad}/${den} (${pct(bad, den)})`
: size(malignancyCells[`${code}|no_data`])
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
}),
};
}
default: default:
return undefined; return undefined;
} }
} }
function counts(mode: Extract<Mode, { kind: 'counts' }>, read: Read): Bars | undefined { /** The subsequent round split by the form's last screening, drawn in place of that round's group. */
const cells = read(mode.measure)?.strata['category'] ?? {}; const LAST_SCREENING: [string, string][] = [
const total = Object.values(cells).reduce((n, c) => n + size(c), 0); ['within_1_year', 'Detección anterior hace un año o menos'],
if (!total) return undefined; ['2_years', 'Detección anterior hace dos años'],
// a category outside the catalog is listed after it, so the shares add up ['3_or_more_years', 'Detección anterior hace tres años o más'],
const hidden = mode.hidden?.codes ?? []; ];
const named = mode.catalog.map((c) => c.code);
const all = [ /** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with
...mode.catalog.filter((c) => !hidden.includes(c.code)), * one independent bar per category over the group's own records. A group the report leaves out is
...Object.keys(cells) * drawn empty only when the listed ones add up to every record of the period (`complete`). */
.filter((c) => !named.includes(c) && !hidden.includes(c)) export function grouped(
.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })), mode: Mode,
of: (measure: string) => Reading | undefined,
): Groups | undefined {
if (mode.kind !== 'grouped') return undefined;
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
if (!patients(r) || !found.length) return undefined;
const history =
mode.stratum === 'round' ? (r?.strata['subsequent_history-category'] ?? {}) : {};
const answers = LAST_SCREENING.map(([code]) => code);
/** the cells that make up a group, with their category */
const cellsOf = (g: string): [string, Record<string, number>][] =>
Object.entries(answers.includes(g) ? history : cells)
.filter(([k]) => k.split('|')[0] === g)
.map(([k, c]) => [k.split('|')[1], c]);
const n = (g: string, c: string) =>
cellsOf(g).reduce((t, [category, cell]) => (category === c ? t + size(cell) : t), 0);
const reconciled = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
const codes = [
...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
...found.filter((g) => !mode.order.includes(g)),
]; ];
const scale = mode.percent ? total : Math.max(...Object.values(cells).map(size)); const total = (g: string) =>
const row = (label: string, n: number, color?: string): Bar => ({ mode.ofAll
label, ? cellsOf(g).reduce((t, [, c]) => t + size(c), 0)
color, : mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
width: (100 * n) / scale, const at = codes.indexOf('subsequent');
marks: [], const drawn =
cells: [`${n}`, pct(n, total)], mode.stratum === 'round' && at >= 0 && r?.strata['subsequent_history-category']
? [...codes.slice(0, at), ...answers, ...codes.slice(at + 1)]
: codes;
const groups: Group[] = drawn.map((code) => {
const den = total(code);
return {
code,
label:
LAST_SCREENING.find(([answer]) => answer === code)?.[1] ??
(mode.stratum === 'age_group' &&
code === '<25' &&
['CACU_EU7', 'CACU_VPH_GENOTIPO'].includes(mode.measure)
? '15-24'
: name(code)),
total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
rows: mode.catalog.flatMap((c, index) => {
const count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined;
const row = {
label: c.label,
color: c.color,
count,
of: den,
percent,
sub: !!mode.aggregate?.codes.includes(c.code),
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`,
};
if (index !== 0 || !mode.aggregate) return [row];
const a = mode.aggregate;
const sum = a.codes.reduce((total, key) => total + n(code, key), 0);
const share = den ? (100 * sum) / den : undefined;
return [
row,
{
label: a.label,
color: a.color,
count: sum,
of: den,
percent: share,
text: `${sum}/${den} · ${share === undefined ? '—' : share.toFixed(1) + ' %'}`,
},
];
}),
};
}); });
const a = mode.aggregate; let note = hiddenNote(mode, of);
const summed = () => if (mode.complete) {
row( const unclassified = total('no_data');
a!.label, const classified = groups.filter((g) => g.code !== 'no_data');
a!.codes.reduce((t, c) => t + size(cells[c]), 0), const none = classified.every((g) => !g.total);
a!.color, const sentence = !reconciled
); ? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
: none && unclassified
? NO_ROUND
: undefined;
note = [sentence, note].filter(Boolean).join(' ') || undefined;
}
return { groups, note };
}
/** Every group of a stratifier the card names, in its order: those the report lists with their
* counts; those it leaves out as no patients when the counts add up to the period's patients,
* else as not available. "Sin dato" keeps its own counts. */
function complete(
order: string[],
listed: string[],
reconciled: boolean,
counts: (code: string) => [number, number] | undefined,
colors: Colors = {},
percentLabel = 'Porcentaje',
): Bars {
const extra = listed.filter((c) => !order.includes(c));
const rows: Bar[] = [...order, ...extra].map((code) => {
const label = name(code);
const color = colors[code];
if (!listed.includes(code))
return reconciled
? { label, color, hint: NO_PATIENTS, width: 0, marks: [], cells: ['0/0', '—'] }
: { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const found = counts(code);
if (!found)
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const [n, total] = found;
return {
label,
color,
hint: total ? undefined : NO_PATIENTS,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
};
});
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length;
return { return {
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'], head: ['n/N', percentLabel],
rows: withAggregate( rows,
all.map((c) => row(c.label, size(cells[c.code]), c.color)), note: !reconciled
all.map((c) => c.code), ? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
a, : none && listed.includes('no_data')
summed, ? NO_ROUND
(r) => ({ ...r, sub: true }), : undefined,
),
note: hiddenNote(mode, read),
}; };
} }
/** Median days per step, with their quartiles; staggered, each from where its step ends. */ function ratios(
function medians(mode: Extract<Mode, { kind: 'days' }>, read: Read): Bars | undefined { rows: [string, number, number, string?][],
const found = mode.steps.map((s) => read(s.measure)); percentLabel = 'Porcentaje',
if (!found.some((r) => r?.score !== undefined)) return undefined; ): Bars | undefined {
const starts: number[] = []; if (!rows.length) return undefined;
mode.steps.forEach(({ after }, i) => { return {
const j = after ?? i - 1; head: ['n/N', percentLabel],
starts.push(mode.staggered && j >= 0 ? starts[j] + (found[j]?.score ?? 0) : 0); rows: rows.map(([label, n, total, color]) => ({
}); label,
const top = color,
Math.max(...found.map((r, i) => starts[i] + Math.max(r?.score ?? 0, r?.high ?? 0))) || 1; width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = { score?: number; low?: number; high?: number };
function medians(
rows: { label: string; n: number; score?: Score }[],
tint?: Tint,
staggered?: boolean,
): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const starts = staggered
? chainStarts(rows.map((r) => ({ median: r.score?.score })))
: rows.map(() => 0);
const ends = rows.map(
(r, i) => starts[i] + Math.max(r.score?.score ?? 0, r.score?.high ?? 0),
);
const top = Math.max(...ends) || 1;
const at = (v: number) => (100 * v) / top; const at = (v: number) => (100 * v) / top;
return { return {
head: ['Mediana', 'Observaciones', 'Q1–Q3'], head: ['Mediana', 'Observaciones', 'Q1–Q3'],
markColor: mode.tint?.mark, markColor: tint?.mark,
note: mode.scale ? `Escala: 0 a ${days(top)} días.` : undefined, rows: rows.map(({ label, n, score: s }, i) => {
rows: mode.steps.map(({ label }, i) => { if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const r = found[i]; const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
const n = `${r?.populations['measure-observation'] ?? 0}`;
if (r?.score === undefined)
return {
label,
width: 0,
marks: [],
none: 'Sin mediciones en el periodo',
cells: ['—', n, '—'],
};
const spread = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return { return {
label, label,
color: mode.tint?.bar, color: tint?.bar,
offset: mode.staggered ? at(starts[i]) : undefined, offset: staggered ? at(starts[i]) : undefined,
width: at(r.score), width: at(s.score),
marks: spread.map((v) => at(starts[i] + v)), marks: spread.map((v) => at(starts[i] + v)),
cells: [`${days(r.score)} días`, n, spread.map(days).join('–') || '—'], cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
}; };
}), }),
}; };
+76
View File
@@ -0,0 +1,76 @@
import { bars, Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
HPV_COLORS,
NEUTRAL,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
REQUEST_COLORS,
ROUND_COLORS,
STEEL,
} from './cacu-palette';
import type { Measure } from 'fhir/r4';
import { donut, Reading } from './measures';
const VPH = { negative: HPV_COLORS['negative'], positive: HPV_COLORS['positive_other'] };
describe('CaCu palette', () => {
it('a PPV group has the colour of its category elsewhere on the page', () => {
expect(PPV_CYTOLOGY_COLORS['ascus_plus']).toBe(CYTOLOGY_COLORS['ASC-US']);
expect(PPV_CYTOLOGY_COLORS['lsil_plus']).toBe(CYTOLOGY_COLORS['LSIL']);
expect(PPV_CYTOLOGY_COLORS['hsil_plus']).toBe(CYTOLOGY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['cin1_plus']).toBe(BIOPSY_COLORS['LSIL']);
expect(PPV_LEVEL_COLORS['cin2_plus']).toBe(BIOPSY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['carcinoma']).toBe(BIOPSY_COLORS['carcinoma']);
expect(HPV_COLORS['hpv_16']).toBe(HPV_COLORS['positive_16']);
expect(HPV_COLORS['hpv_18']).toBe(HPV_COLORS['positive_18']);
expect(HPV_COLORS['positive']).toBe(HPV_COLORS['positive_other']);
expect(REQUEST_COLORS['high_grade']).toBe(CYTOLOGY_COLORS['HSIL']);
});
it('"Sin dato" and what is not classified are neutral everywhere', () => {
for (const colors of [
CYTOLOGY_COLORS,
HPV_COLORS,
BIOPSY_COLORS,
ROUND_COLORS,
PPV_CYTOLOGY_COLORS,
])
expect(colors['no_data']).toBe(NEUTRAL);
expect(REQUEST_COLORS['pending']).toBe(NEUTRAL);
expect(PPV_DONUT['rest']).toBe(NEUTRAL);
expect(ROUND_COLORS['initial']).toBe(STEEL);
});
it('a donut colours by category, not by place in the report', () => {
const measure = { scoring: { coding: [{ code: 'cohort' }] } } as unknown as Measure;
const cells = (order: string[]): Reading => ({
populations: {},
strata: { category: Object.fromEntries(order.map((c) => [c, { 'initial-population': 1 }])) },
});
const colours = (order: string[]) =>
(donut(measure, cells(order), 'category', VPH).data[0] as any).marker.colors;
expect(colours(['negative', 'positive'])).toEqual([VPH['negative'], VPH['positive']]);
expect(colours(['positive', 'negative'])).toEqual([VPH['positive'], VPH['negative']]);
});
it('bars take their colour from the mode by group, absent groups included', () => {
const r: Reading = {
populations: { 'initial-population': 5 },
strata: { round: { subsequent: { numerator: 1, denominator: 5 } } },
};
const mode: Mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
complete: true,
colors: ROUND_COLORS,
};
expect(bars(mode, () => r)!.rows.map((x) => x.color)).toEqual([
ROUND_COLORS['initial'],
ROUND_COLORS['subsequent'],
ROUND_COLORS['no_data'],
]);
});
});
+92
View File
@@ -0,0 +1,92 @@
/** The colours of CaCu's charts, by category. A colour names a category (never a position in a
* report, never a threshold), so the same category looks the same on every card; neutral greys
* are for what is absent or not classified. They live here, not in the shared palette, so that no
* other domain (CaMa, TEA) takes them. */
/** Not classified, or no data. */
export const NEUTRAL = '#C9CDD2';
/** Not classified, a little darker: what a report names but a card does not. */
export const NEUTRAL_DARK = '#9AA3AB';
/** The steel tones of the groups that are not results: rounds, ages, follow-up status. */
export const STEEL = '#5F7F9A';
export const STEEL_MID = '#8FA7BB';
export const STEEL_LIGHT = '#B5C5D3';
/** Cytology by Bethesda category. */
export const CYTOLOGY_COLORS: Record<string, string> = {
NILM: '#408651',
'ASC-US': '#2778B8',
LSIL: '#B19525',
'ASC-H': '#7955B1',
CIN2: '#E07A9C',
HSIL: '#CE4778',
CIN3: '#BC4163',
CIS: '#AA394D',
no_data: NEUTRAL,
};
/** HPV by genotype; `positive` (any high-risk type) is the colour of "positive other". */
export const HPV_COLORS: Record<string, string> = {
negative: '#42A77E',
positive_16: '#DF8640',
positive_18: '#C29C42',
positive_16_18: '#C24269',
positive_other: '#A8C243',
positive_incomplete: '#9C42C2',
inconsistent: '#687786',
positive: '#A8C243',
hpv_16: '#DF8640',
hpv_18: '#C29C42',
no_data: NEUTRAL,
};
/** Biopsy by the grade it states; the levels of a PPV (that grade or worse) take its colour. */
export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651',
LSIL: '#B19525',
CIN2: '#E07A9C',
HSIL: '#CE4778',
CIN3: '#BC4163',
CIS: '#AA394D',
carcinoma: '#8D4C79',
cin1_plus: '#B19525',
cin2_plus: '#CE4778',
no_data: NEUTRAL,
};
/** What became of the biopsy requests: high grade is the colour of LIEAG, the rest steel. */
export const REQUEST_COLORS: Record<string, string> = {
high_grade: '#CE4778',
below_high_grade: STEEL_MID,
pending: NEUTRAL,
no_grade: NEUTRAL_DARK,
};
/** Detection round: steel tones; "Sin dato" is neutral. */
export const ROUND_COLORS: Record<string, string> = {
initial: STEEL,
subsequent: STEEL_MID,
no_data: NEUTRAL,
};
/** Referral PPV groups: cytology and histology levels by the colour of their category, HPV by
* genotype. */
export const PPV_CYTOLOGY_COLORS: Record<string, string> = {
ascus_plus: CYTOLOGY_COLORS['ASC-US'],
lsil_plus: CYTOLOGY_COLORS['LSIL'],
hsil_plus: CYTOLOGY_COLORS['HSIL'],
no_data: NEUTRAL,
};
export const PPV_LEVEL_COLORS: Record<string, string> = {
cin1_plus: BIOPSY_COLORS['LSIL'],
cin2_plus: BIOPSY_COLORS['HSIL'],
carcinoma: BIOPSY_COLORS['carcinoma'],
};
/** The whole of a PPV card as a donut: the colours of its two parts. */
export const PPV_DONUT: Record<string, string> = { numerator: '#6A8000', rest: NEUTRAL };
/** Median bars of the screening route, and the marks of their quartiles. */
export const DURATION = '#42A77E';
export const QUARTILE = '#17324D';
@@ -0,0 +1,9 @@
import { HISTORY, PAGES } from './pages';
describe('tiempo de diagnóstico tras biopsia a tratamiento en CaMa', () => {
it('conecta la tarjeta y el histórico con la medida', () => {
const measure = 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO';
expect(PAGES['cama'].kpis.some((card) => card.measure === measure)).toBe(true);
expect(HISTORY['cama'].panels.some((panel) => panel.measure === measure)).toBe(true);
});
});
@@ -0,0 +1,46 @@
import type { CamaRow } from './follow-up';
import { camaFollowUpSheet } from './follow-up-sheet';
const row = (over: Partial<CamaRow> = {}): CamaRow =>
({
patient: { resourceType: 'Patient', id: 'abcdefghijklmnop' },
status: 'pending_biopsy',
priority: 'high',
ageGroup: '50-59',
mammogram: { date: '2026-10-26', birads: '4A' },
...over,
}) as CamaRow;
const priority = (c: string) => ({ high: 'Alta' })[c as 'high'] ?? c;
// Each test fails if the list file invented a result or lost the query it answers.
describe('CaMa follow-up list as a file', () => {
it('has CaMa columns, the query and the count', () => {
const sheet = camaFollowUpSheet([row()], [['Búsqueda', 'Ninguna']], priority);
expect(sheet.head).toEqual([
'Paciente', 'CURP', 'Grupo de edad', 'Última mastografía (BI-RADS)', 'Fecha de la mastografía',
'Última biopsia', 'Fecha de reporte de la biopsia', 'Estatus de seguimiento', 'Prioridad',
]);
expect(sheet.query).toEqual([['Búsqueda', 'Ninguna'], ['Registros', '1']]);
expect(sheet.head.join()).not.toMatch(/LIEAG|VPH|Cáncer|Etapas/);
});
it('says what is missing: no biopsy, no BI-RADS, no CURP, no priority, never a made-up value', () => {
const [r] = camaFollowUpSheet(
[row({ mammogram: { date: '' }, priority: '' })],
[],
priority,
).rows;
expect(r.slice(0, 2)).toEqual(['abcdefghij', 'No disponible']);
expect(r.slice(3, 7)).toEqual(['Sin dato', 'No disponible', 'No disponible', 'No disponible']);
expect(r[8]).toBe('No disponible');
});
it('shows a biopsy with its date, or no grade when it has none', () => {
const rows = camaFollowUpSheet(
[row({ biopsy: { date: '2026-11-30', histology: 'benign' } }), row({ biopsy: { date: '2026-11-01' } })],
[],
priority,
).rows;
expect(rows[0].slice(5, 7)).toEqual(['Benigno', '2026-11-30']);
expect(rows[1].slice(5, 7)).toEqual(['Sin resultado', '2026-11-01']);
expect(rows[0][8]).toBe('Alta');
});
});
+19
View File
@@ -0,0 +1,19 @@
/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
+62
View File
@@ -0,0 +1,62 @@
import { chainStarts, durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
describe('durationRows', () => {
const reads: Record<string, Reading> = {
A: reading(0, 3, 0, 1),
B: reading(6, 20, 4, 8),
C: reading(undefined, 0),
};
const rows = durationRows(
[
{ label: 'zero', measure: 'A' },
{ label: 'value', measure: 'B' },
{ label: 'nothing measured', measure: 'C' },
{ label: 'no report', measure: 'D' },
{ label: 'not in the catalog', measure: 'E' },
{ label: 'no measure' },
],
(m) => reads[m],
(m) => m !== 'E',
);
it('keeps a real zero as a value', () => {
expect(rows[0]).toEqual({
label: 'zero',
status: 'value',
median: 0,
observations: 3,
low: 0,
high: 1,
});
});
it('tells no measurements from an unpublished measure', () => {
expect(rows.map((r) => r.status)).toEqual([
'value',
'value',
'empty',
'empty',
'unpublished',
'unpublished',
]);
});
it('scales from zero to the largest median or third quartile', () => {
expect(durationMax(rows)).toBe(8);
expect(durationMax([])).toBe(0);
});
});
describe('chainStarts', () => {
it('starts each step where the one it follows ends, two of them sharing a start', () => {
expect(chainStarts([{ median: 4 }, { median: 6 }, { median: 2, after: 0 }])).toEqual([0, 4, 4]);
expect(chainStarts([{ median: 4 }, {}, { median: 2 }])).toEqual([0, 4, 4]);
});
});
+68
View File
@@ -0,0 +1,68 @@
import { Reading } from './measures';
/** One step of a route: its name and the measure that times it. A step with no measure is
* not published yet. */
export interface RouteStep {
label: string;
measure?: string;
/** the step (its position) this one starts after; the previous one by default */
after?: number;
}
/** One row of a duration table: the median days, how many measurements and the quartiles.
* `empty` (published, nothing measured in the period) is not `unpublished` (no measure), and
* neither is a zero: a median of 0 days is a value. */
export interface DurationRow {
label: string;
status: 'value' | 'empty' | 'unpublished';
median?: number;
observations?: number;
low?: number;
high?: number;
after?: number;
/** where its bar starts, in days, when the steps are chained */
start?: number;
}
/** Where each step's bar starts when drawn as a schematic sequence (a Gantt chart): where the
* step it follows ends. A step without a median moves nothing after it. */
export function chainStarts(steps: { median?: number; after?: number }[]): number[] {
const starts: number[] = [];
steps.forEach(({ after }, i) => {
const j = after ?? i - 1;
starts.push(j < 0 ? 0 : starts[j] + (steps[j].median ?? 0));
});
return starts;
}
export function chained(rows: DurationRow[]): DurationRow[] {
const starts = chainStarts(rows);
return rows.map((row, i) => ({ ...row, start: starts[i] }));
}
/** The rows of a route in one reading; every step keeps its row. `published` says which
* measures the catalog has. */
export function durationRows(
steps: RouteStep[],
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure, after }) => {
if (!measure || !published(measure)) return { label, after, status: 'unpublished' };
const r = read(measure);
if (r?.score === undefined) return { label, after, status: 'empty' };
return {
label,
after,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
low: r.low,
high: r.high,
};
});
}
/** The scale of a table of durations, from zero: the farthest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => (r.start ?? 0) + Math.max(r.median ?? 0, r.high ?? 0)));
+193 -11
View File
@@ -1,8 +1,7 @@
import { type Figure, PALETTE } from '../plot'; import { type Figure, PALETTE } from '../plot';
import { name } from './labels'; import { reconciles } from './bars';
import { type Reading } from './measures'; import { name, type Reading } from './measures';
import type { HistoryPanel } from './history'; import type { Catalog, Category, HistoryPanel } from './pages';
import type { Catalog, Category } from './pages';
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
@@ -19,20 +18,115 @@ function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0; return r.strata['category']?.[code]?.['initial-population'] ?? 0;
} }
/** Groups inside, their categories outside, the total in the centre. */
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`<b>${count(total)}</b><br>${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
// along the thin ring, so a label fits its slice
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
},
] as Partial<Plotly.Data>[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */ /** Each clinical scenario's results as shares of its patients, one stacked bar each. */
export function scenarioBars( export function scenarioBars(
r: Reading, r: Reading,
catalog: Catalog, catalog: Catalog,
stratum: string, stratum: string,
label: (code: string) => string, label: (code: string) => string,
/** the groups in this order (the ones the report lists, then any other) */
order?: string[],
options: {
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
fill?: boolean;
/** a bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
} = {},
): Figure { ): Figure {
const cells = r.strata[`${stratum}-category`] ?? {}; const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) => const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
label(a).localeCompare(label(b), 'es'), const listed = Object.values(cells).map((c) => c['initial-population']);
); const empty = reconciles(listed, r.populations['initial-population'] ?? 0);
const scenarios = order
? [
...order.filter((s) => found.includes(s) || (options.fill && empty)),
...found.filter((s) => !order.includes(s)),
]
: found.sort((a, b) => label(a).localeCompare(label(b), 'es'));
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0; const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0)); const totals = scenarios.map((s) =>
const y = scenarios.map(label); options.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === s)
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0)
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
);
const y = order
? scenarios.map((s, i) => `${label(s)}<br>${options.ofAll ? 'Reportes' : 'Pacientes'}: ${totals[i]}`)
: scenarios.map(label);
return { return {
data: catalog.categories.map((c) => ({ data: catalog.categories.map((c) => ({
type: 'bar', type: 'bar',
@@ -47,7 +141,13 @@ export function scenarioBars(
layout: { layout: {
barmode: 'stack', barmode: 'stack',
xaxis: { xaxis: {
title: { text: '% de pacientes del escenario con resultado' }, title: {
text: order
? options.ofAll
? '% de los reportes del grupo'
: '% de pacientes con resultado'
: '% de pacientes del escenario con resultado',
},
ticksuffix: ' %', ticksuffix: ' %',
range: [0, 100.5], range: [0, 100.5],
dtick: 20, dtick: 20,
@@ -63,6 +163,86 @@ export function scenarioBars(
}; };
} }
/** Wilson score interval at 95 %, in percent. */
export function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 }); const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
/** A card's template filled from its measure's reading in the period: {n} counted, {obs} /** A card's template filled from its measure's reading in the period: {n} counted, {obs}
@@ -124,7 +304,9 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
line: { color: '#FFFFFF', width: 2 }, line: { color: '#FFFFFF', width: 2 },
}, },
// an empty slice says nothing (its label would sit on its neighbours') // an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? `%{label}<br>%{percent} del total de ${center}` : '')), texttemplate: values.map((v) =>
v ? `%{label}<br>%{percent} del total de ${center}` : '',
),
textposition: 'outside', textposition: 'outside',
hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`, hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`,
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
+48
View File
@@ -0,0 +1,48 @@
import type { Bundle } from 'fhir/r4';
import { type Sheet, saveExcel, savePdf } from '../export';
import type { Fhir } from '../fhir';
import { windowStart } from './follow-up';
import { name } from './measures';
/** The bundle's self link carries the filters that produced the displayed page. */
function exportQuery(page: Bundle) {
const self = page.link?.find((link) => link.relation === 'self')?.url;
if (!self) throw new Error('Missing follow-up query');
const applied = new URL(self).searchParams;
const cutoff = applied.get('follow-up-cutoff');
if (!cutoff) throw new Error('Missing follow-up cut-off');
applied.delete('_offset');
applied.set('_count', '200');
const params = Object.fromEntries(
[...new Set(applied.keys())].map((key) => [key, applied.getAll(key)]),
);
const start = windowStart(cutoff, Number(applied.get('follow-up-window')));
const status = applied.get('follow-up-status');
return {
params,
cutoff,
start,
window: `${start} al ${cutoff}`,
status: status ? name(status) : 'Todos',
search: applied.get('name') ?? applied.get('identifier') ?? 'Ninguna',
horizon: Number(applied.get('risk-horizon')),
birthdates: applied.getAll('birthdate'),
};
}
export async function saveFollowUp(
fhir: Fhir,
domain: string,
page: Bundle,
kind: 'xlsx' | 'pdf',
sheetFor: (pages: Bundle[], query: ReturnType<typeof exportQuery>) => Sheet,
): Promise<void> {
const query = exportQuery(page);
const pages = await fhir.all(domain, 'Patient', query.params);
const sheet = sheetFor(pages, query);
const file = `seguimiento-${domain}`;
if (kind === 'xlsx') await saveExcel(sheet, file);
else await savePdf([sheet], file, true);
}
+38 -35
View File
@@ -1,7 +1,7 @@
import type { Sheet } from '../export'; import type { Sheet } from '../export';
import { STATES } from '../paciente/stages'; import { STATES } from '../paciente/stages';
import type { CamaRow, Row } from './follow-up'; import type { CamaRow, Row } from './follow-up';
import { name } from './labels'; import { name } from './measures';
const NONE = 'No disponible'; const NONE = 'No disponible';
const HEAD = [ const HEAD = [
@@ -24,40 +24,6 @@ export function cytologyResult(c: NonNullable<Row['cytology']>): string {
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente'; return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
} }
/** CaMa's follow-up list as a table to save: what the page shows, a missing value said so. */
export function camaFollowUpSheet(
rows: CamaRow[],
query: [string, string][],
priority: (code: string) => string,
): Sheet {
return {
title: 'Resultados de seguimiento de cáncer de mama',
query: [...query, ['Registros', `${rows.length}`]],
head: [
'Paciente',
'CURP',
'Grupo de edad',
'Última mastografía (BI-RADS)',
'Fecha de la mastografía',
'Última biopsia',
'Fecha de reporte de la biopsia',
'Estatus de seguimiento',
'Prioridad',
],
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
r.ageGroup || NONE,
(r.mammogram.birads && name(r.mammogram.birads)) || 'Sin dato',
r.mammogram.date || NONE,
r.biopsy ? name(r.biopsy.histology ?? '') || 'Sin resultado' : NONE,
r.biopsy?.date ?? NONE,
name(r.status),
priority(r.priority) || NONE,
]),
};
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`); const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */ /** The follow-up list as a table to save, with the query it answers. */
@@ -84,3 +50,40 @@ export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
]), ]),
}; };
} }
const CAMA_HEAD = [
'Paciente',
'CURP',
'Grupo de edad',
'Última mastografía (BI-RADS)',
'Fecha de la mastografía',
'Última biopsia',
'Fecha de reporte de la biopsia',
'Estatus de seguimiento',
'Prioridad',
];
/** CaMa's follow-up list as a table to save: what the page shows, a missing value said as such and
* never filled in. */
export function camaFollowUpSheet(
rows: CamaRow[],
query: [string, string][],
priority: (code: string) => string,
): Sheet {
return {
title: 'Resultados de seguimiento de cáncer de mama',
query: [...query, ['Registros', `${rows.length}`]],
head: CAMA_HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
r.ageGroup || NONE,
(r.mammogram.birads && name(r.mammogram.birads)) || 'Sin dato',
r.mammogram.date || NONE,
r.biopsy ? name(r.biopsy.histology ?? '') || 'Sin resultado' : NONE,
r.biopsy?.date ?? NONE,
name(r.status),
priority(r.priority) || NONE,
]),
};
}
+11 -1
View File
@@ -1,6 +1,6 @@
import type { RiskAssessment } from 'fhir/r4'; import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up'; import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures'; import { historyPeriods, periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
it('starts the window the day after the same day months before (core.follow_up)', () => { it('starts the window the day after the same day months before (core.follow_up)', () => {
@@ -36,6 +36,16 @@ describe('follow-up list', () => {
expect(currentRisk(risks, 'cin2', 3)).toBeUndefined(); expect(currentRisk(risks, 'cin2', 3)).toBeUndefined();
}); });
it('ends history at the selected complete period for months and semesters', () => {
const monthly = historyPeriods('month', '2025-03');
expect(monthly.slice(-3)).toEqual(['2025-01', '2025-02', '2025-03']);
expect(monthly).toHaveLength(72);
const firstSemester = historyPeriods('semester', '2025-S1');
expect(firstSemester.slice(-3)).toEqual(['2024-S1', '2024-S2', '2025-S1']);
const secondSemester = historyPeriods('semester', '2025-S2');
expect(secondSemester.slice(-2)).toEqual(['2025-S1', '2025-S2']);
});
it('lists periods most recent first', () => { it('lists periods most recent first', () => {
expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']); expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']);
expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([ expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([
-136
View File
@@ -1,136 +0,0 @@
import { Mode, NO_PATIENTS, NOT_AVAILABLE } from './bars';
import { grouped, outcomes, shares, unavailable } from './groups';
import { Reading } from './measures';
const read = (r: Reading) => () => r;
const cell = (n: number) => ({ 'initial-population': n });
const catalog = [
{ code: 'NILM', label: 'Normal', color: '#0f0' },
{ code: 'HSIL', label: 'LIEAG', color: '#f00' },
];
describe('shares', () => {
const mode: Mode = {
kind: 'shares',
label: 'Ronda',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
complete: true,
};
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: { denominator: 0 },
strata: { round: { initial: { numerator: 0, denominator: 0 } } },
};
const plain = { ...mode, complete: false } as Mode;
expect(shares(plain, read(r))!.rows[0].cells).toEqual(['0/0', '—']);
});
it('draw a group left out as zero only when the listed ones add up', () => {
const listed = { initial: { numerator: 1, denominator: 4 } };
const whole = shares(
mode,
read({ populations: { denominator: 4 }, strata: { round: listed } }),
)!;
expect(whole.rows[1]).toMatchObject({ hint: NO_PATIENTS, cells: ['0/0', '—'] });
const short = shares(
mode,
read({ populations: { denominator: 5 }, strata: { round: listed } }),
)!;
expect(short.rows[1]).toMatchObject({ hint: NOT_AVAILABLE, cells: ['—', '—'] });
expect(short.note).toContain('no concilian');
});
it('say when the report does not break the period down', () => {
const r: Reading = { populations: { denominator: 4 }, strata: {} };
expect(unavailable(mode, read(r))).toContain('no publica el desglose «Ronda»');
});
});
describe('grouped', () => {
const mode: Mode = {
kind: 'grouped',
label: 'Por ronda',
measure: 'CACU_EU7',
catalog,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
unit: 'pacientes',
complete: true,
ofAll: true,
};
it('split the subsequent round by the last screening, each group over its own', () => {
const r: Reading = {
populations: { 'initial-population': 5 },
strata: {
'round-category': {
'initial|NILM': cell(1),
'subsequent|NILM': cell(2),
'subsequent|HSIL': cell(2),
},
'subsequent_history-category': {
'within_1_year|NILM': cell(2),
'2_years|HSIL': cell(1),
'3_or_more_years|HSIL': cell(1),
},
},
};
const g = grouped(mode, read(r))!;
expect(g.groups.map((x) => [x.code, x.total])).toEqual([
['initial', 1],
['within_1_year', 2],
['2_years', 1],
['3_or_more_years', 1],
['no_data', 0],
]);
expect(g.groups[1].label).toBe('Detección anterior hace un año o menos');
expect(g.groups[2].rows.map((x) => x.text)).toEqual(['0/1 · 0.0 %', '1/1 · 100.0 %']);
expect(g.groups[4].hint).toBe('Sin pacientes en el grupo');
});
it('name the youngest results group from 15', () => {
const r: Reading = {
populations: { 'initial-population': 1 },
strata: { 'age_group-category': { '<25|NILM': cell(1) } },
};
const byAge = { ...mode, stratum: 'age_group', order: ['<25'] } as Mode;
expect(grouped(byAge, read(r))!.groups[0].label).toBe('15-24');
});
});
describe('outcomes', () => {
it('segment each row by result and give the malignant share of the graded', () => {
const types: Reading = {
populations: {},
strata: {
category: { '8500/3': cell(1), no_biopsy: cell(1) },
birads: { '5': cell(2), '4A': cell(0) },
'birads-category': { '5|8500/3': cell(1), '5|no_biopsy': cell(1) },
},
};
const grades: Reading = {
populations: {},
strata: { 'birads-category': { '5|invasive': cell(1), '5|no_biopsy': cell(1) } },
};
const mode: Mode = {
kind: 'outcomes',
label: 'x',
measure: 'T',
stratum: 'birads',
rows: [
{ code: '5', label: 'BI-RADS 5', color: '' },
{ code: '4A', label: 'BI-RADS 4A', color: '' },
],
results: [{ code: 'no_biopsy', label: 'Sin biopsia', color: '#ccc' }],
malignant: ['in_situ', 'invasive'],
malignancy: 'G',
};
const t = outcomes(mode, (m) => (m === 'T' ? types : grades))!;
expect(t.head).toEqual([
'Pacientes',
'Carcinoma ductal infiltrante',
'Sin biopsia',
'% maligno',
]);
expect(t.rows[0].cells).toEqual(['2', '1', '1', '1/1 (100.0 %)']);
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
});
});
-231
View File
@@ -1,231 +0,0 @@
import {
Bar,
Bars,
hiddenNote,
Mode,
NO_PATIENTS,
NO_ROUND,
NOT_AVAILABLE,
patients,
pct,
Read,
reconciles,
size,
whole,
withAggregate,
} from './bars';
import { name } from './labels';
/** One category of a group as a bar of 0 to 100 %: its records over the group's. */
export interface GroupRow {
label: string;
color: string;
sub?: boolean;
/** none when the group has no records */
percent?: number;
/** "2/5 · 40.0 %" */
text: string;
}
export interface Group {
code: string;
label: string;
total: number;
hint?: string;
rows: GroupRow[];
}
/** The subsequent round, split by the form's last screening, drawn in place of that group. */
const LAST_SCREENING: Record<string, string> = {
within_1_year: 'Detección anterior hace un año o menos',
'2_years': 'Detección anterior hace dos años',
'3_or_more_years': 'Detección anterior hace tres años o más',
};
/** Results counted from 15 years old: their youngest group starts there. */
const FROM_15 = ['CACU_EU7', 'CACU_VPH_GENOTIPO'];
const cellsOf = (strata: Record<string, Record<string, number>>, group: string) =>
Object.entries(strata)
.filter(([k]) => k.split('|')[0] === group)
.map(([k, c]) => [k.split('|')[1], size(c)] as const);
/** The groups of a `grouped` mode, each with a bar per category over its own records. A group
* the report leaves out is drawn empty only when the listed ones add up (`complete`). */
export function grouped(mode: Mode, read: Read): { groups: Group[]; note?: string } | undefined {
if (mode.kind !== 'grouped') return undefined;
const r = read(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
if (!patients(r) || !found.length) return undefined;
const history = (mode.stratum === 'round' && r?.strata['subsequent_history-category']) || {};
const split = Object.keys(history).length > 0;
const reconciled = reconciles(Object.values(cells).map(size), patients(r));
const codes = [
...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
...found.filter((g) => !mode.order.includes(g)),
].flatMap((g) => (split && g === 'subsequent' ? Object.keys(LAST_SCREENING) : [g]));
const count = (g: string) => cellsOf(g in LAST_SCREENING ? history : cells, g);
const n = (g: string, code: string) =>
count(g).reduce((t, [c, k]) => (c === code ? t + k : t), 0);
const total = (g: string) =>
mode.ofAll
? count(g).reduce((t, [, k]) => t + k, 0)
: mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
const row = (label: string, color: string, k: number, of: number): GroupRow => {
const percent = of ? (100 * k) / of : undefined;
return { label, color, percent, text: `${k}/${of} · ${of ? pct(k, of) : '—'}` };
};
const groups = codes.map((code): Group => {
const of = total(code);
const a = mode.aggregate;
return {
code,
label:
LAST_SCREENING[code] ??
(code === '<25' && mode.stratum === 'age_group' && FROM_15.includes(mode.measure)
? '15-24'
: name(code)),
total: of,
hint: of ? undefined : `Sin ${mode.unit} en el grupo`,
rows: withAggregate(
mode.catalog.map((c) => row(c.label, c.color, n(code, c.code), of)),
mode.catalog.map((c) => c.code),
a,
() =>
row(
a!.label,
a!.color,
a!.codes.reduce((t, c) => t + n(code, c), 0),
of,
),
(x) => ({ ...x, sub: true }),
),
};
});
const unrounded =
mode.complete &&
reconciled &&
total('no_data') > 0 &&
groups.every((g) => g.code === 'no_data' || !g.total);
const sentence =
mode.complete && !reconciled
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se ' +
'muestran como cero.'
: unrounded
? NO_ROUND
: undefined;
const note = [sentence, hiddenNote(mode, read)].filter(Boolean).join(' ') || undefined;
return { groups, note };
}
/** Why a grouped mode has nothing to draw though its period has records. */
export function unavailable(mode: Mode, read: Read): string | undefined {
if (mode.kind !== 'grouped' && !(mode.kind === 'shares' && mode.complete)) return undefined;
const r = read(mode.measure);
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
if (!patients(r) || Object.keys(r?.strata[key] ?? {}).length) return undefined;
return `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
}
const RESULT_COLORS = ['#5C42C2', '#C24269', '#9C42C2', '#A8C243', '#2778B8', '#B19525'];
const GRADES = ['benign', 'in_situ', 'invasive'];
/** Each row's units by result, as one bar in segments, and the malignant share. */
export function outcomes(mode: Mode, read: Read): Bars | undefined {
if (mode.kind !== 'outcomes') return undefined;
const r = read(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
if (!Object.keys(units).length) return undefined;
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const fixed = mode.results.map((x) => x.code);
const results = [
...Object.keys(r?.strata['category'] ?? {})
.filter((code) => !fixed.includes(code))
.sort()
.map((code, i) => ({ code, label: name(code), color: RESULT_COLORS[i % 6] })),
...mode.results,
];
const graded = read(mode.malignancy)?.strata[`${mode.stratum}-category`];
const of = (row: string, codes: string[]) =>
codes.reduce((t, c) => t + size(graded?.[`${row}|${c}`]), 0);
const malignant = (row: string) => {
if (!graded) return NOT_AVAILABLE;
const [bad, known] = [of(row, mode.malignant), of(row, GRADES)];
if (known) return `${bad}/${known} (${pct(bad, known)})`;
return size(graded[`${row}|no_data`]) ? 'Sin biopsias clasificables' : 'Sin biopsias';
};
return {
head: ['Pacientes', ...results.map((x) => x.label), '% maligno'],
legend: results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]);
const by = results.map((x) => size(cells[`${code}|${x.code}`]));
return {
label,
width: 100,
marks: [],
hint: n ? undefined : 'Sin pacientes en el periodo',
segments: results.map((x, i) => ({
width: n ? (100 * by[i]) / n : 0,
color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
})),
cells: n ? [`${n}`, ...by.map(String), malignant(code)] : ['0', ...by.map(() => '—'), '—'],
};
}),
};
}
/** A proportion by group; complete, every group of the order, as the counts allow. */
export function shares(mode: Mode, read: Read): Bars | undefined {
if (mode.kind !== 'shares') return undefined;
const r = read(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
const listed = Object.keys(cells);
const head = ['n/N', mode.percentLabel ?? 'Porcentaje'];
const of = (code: string): Bar => {
const [n, total] = [cells[code]?.['numerator'], cells[code]?.['denominator']];
const label = name(code);
const color = mode.colors?.[code];
if (!whole(n) || !whole(total) || n > total)
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
return {
label,
color,
hint: total ? undefined : NO_PATIENTS,
marks: [],
width: total ? (100 * n) / total : 0,
cells: [`${n}/${total}`, pct(n, total)],
};
};
if (!mode.complete) {
const found = mode.order.filter((c) => cells[c]);
return found.length ? { head, rows: found.map(of) } : undefined;
}
if (!patients(r) || !listed.length) return undefined;
const reconciled = reconciles(
listed.map((c) => cells[c]['denominator']),
patients(r),
);
const rows = [...mode.order, ...listed.filter((c) => !mode.order.includes(c))].map((code) =>
listed.includes(code)
? of(code)
: {
label: name(code),
color: mode.colors?.[code],
width: 0,
marks: [],
...(reconciled
? { hint: NO_PATIENTS, cells: ['0/0', '—'] }
: { hint: NOT_AVAILABLE, cells: ['—', '—'] }),
},
);
const classified = mode.order.filter((c) => c !== 'no_data' && listed.includes(c));
const none = classified.every((c) => !cells[c]['denominator']) && listed.includes('no_data');
const note = !reconciled
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no ' +
'se muestran como cero.'
: none
? NO_ROUND
: undefined;
return { head, rows, note };
}
-216
View File
@@ -1,216 +0,0 @@
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
export interface HistoryPanel {
title: string;
measure: string;
kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string;
group?: string;
}
export interface History {
panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number;
}
const GREY = '#C9CDD2';
const stack = (
title: string,
measure: string,
axis: string,
series: [string, string, string][],
): HistoryPanel => ({
title,
measure,
kind: 'stack',
axis,
series: series.map(([code, label, color]) => ({ code, label, color })),
});
const BIRADS_SERIES: [string, string, string][] = [
['4A', 'BI-RADS 4A', '#C24269'],
['4B', 'BI-RADS 4B', '#9C42C2'],
['4C', 'BI-RADS 4C', '#5C42C2'],
['5', 'BI-RADS 5', '#C2429C'],
['6', 'BI-RADS 6', '#8E2F62'],
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
];
export const HISTORY: Record<string, History> = {
cacu: {
line: '#6A8000',
months: 5,
panels: [
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
['NILM', 'Normal', '#9DBFE3'],
['ASC-US', 'ASC-US', '#2F6DB3'],
['LSIL', 'LIEBG', '#9C42C2'],
['ASC-H', 'ASC-H', '#5C42C2'],
['HSIL', 'LIEAG', '#C2429C'],
['CIS', 'Carcinoma in situ', '#8E2F62'],
['no_data', 'Sin dato', GREY],
]),
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
stack(
'Resultado de biopsia tras citología de alto grado',
'CACU_CONFIRMACION_CITOLOGIA',
'Pacientes',
[
['normal', 'Normal', '#9DBFE3'],
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
['CIN2', 'CIN 2', '#E07A9C'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
['CIN3', 'CIN 3', '#A8325A'],
['CIS', 'Carcinoma in situ', '#9C42C2'],
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
['no_biopsy', 'Sin biopsia aún', GREY],
['no_data', 'Biopsia sin grado', GREY],
],
),
{
title: 'Días de la toma de la citología a su resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median',
},
{
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
{
title: 'Riesgo CIN2+ por banda',
measure: 'CACU_RIESGO_BANDA',
kind: 'stack',
axis: 'Pacientes',
},
],
},
cama: {
line: '#9C42C2',
panels: [
{
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
{
title: 'Días de la toma de la mastografía a su resultado',
measure: 'CAMA_EU38A',
kind: 'median',
},
{
title: 'Días del resultado de la mastografía al diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tasa de detección histopatológica',
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
kind: 'percent',
},
stack(
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_MASTOGRAFIA',
'Mastografías',
BIRADS_SERIES,
),
stack(
'Pacientes con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_PACIENTE',
'Pacientes',
BIRADS_SERIES,
),
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
['benign', 'Benigno', '#9DBFE3'],
['in_situ', 'Carcinoma in situ', '#C24269'],
['invasive', 'Carcinoma invasor', '#9C42C2'],
['no_biopsy', 'Sin biopsia reportada', GREY],
['no_data', 'Sin dato', GREY],
]),
{
title: 'Confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent',
},
],
},
tea: {
line: '#9C42C2',
panels: [
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a ADOS-2',
measure: 'M26_DIAS_MCHAT_ADOS2',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de ADOS-2 a diagnóstico',
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a diagnóstico positivo',
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
kind: 'median',
},
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
['in_process', 'En proceso', '#B8433A'],
]),
{
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
kind: 'percent',
},
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
['mchat_only', 'Solo M-CHAT', '#B8433A'],
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
['eeg', 'Con EEG', '#A8C243'],
]),
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
['good', 'Bueno', '#A8C243'],
['bad', 'No aceptable', '#B8433A'],
['not_analyzed', 'Sin analizar', GREY],
]),
],
},
};
-91
View File
@@ -1,91 +0,0 @@
/** Codes as the screens name them. */
export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)',
LSIL: 'LIEBG',
HSIL: 'LIEAG',
CIN2: 'CIN 2',
CIN3: 'CIN 3',
normal: 'Normal',
carcinoma: 'Carcinoma',
no_data: 'Sin dato',
'<25': '<25 años (sin límite inferior)',
no_biopsy: 'Sin biopsia',
pre_colposcopy: 'Pre colposcopia',
post_colposcopy: 'Post colposcopia',
post_treatment: 'Post tratamiento',
case: 'Caso (cáncer)',
low: 'Bajo',
intermediate: 'Intermedio',
high: 'Alto',
satisfactory: 'satisfactoria',
unsatisfactory: 'insatisfactoria',
benign: 'Benigno',
in_situ: 'Carcinoma in situ',
invasive: 'Carcinoma invasor',
cancer: 'Diagnóstico confirmado',
pending_biopsy: 'Pendiente de biopsia',
biopsy_no_result: 'Biopsia sin resultado',
benign_biopsy: 'Biopsia benigna',
confirmed: 'Diagnóstico confirmado',
in_process: 'En proceso',
not_confirmed: 'Sin TEA',
mchat_only: 'Solo M-CHAT',
psychology: 'Psicología (ADOS-2)',
neuropediatrics: 'Neuropediatría',
neurology: 'Neurología',
eeg: 'EEG',
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Detección inicial',
subsequent: 'Con detección anterior',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
positive_incomplete: 'Positivo con genotipificación incompleta',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
};
/** A follow-up priority's label. */
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
export const STRATA: Record<string, string> = {
category: 'Categoría',
age_group: 'Grupo de edad',
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Detección inicial o anterior',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
};
/** Breast histologic types (ICD-O-3 morphology) the sites report; any other shows its code. */
const HISTOLOGIC_TYPES: Record<string, string> = {
'8500/2': 'Carcinoma ductal in situ',
'8500/3': 'Carcinoma ductal infiltrante',
'8520/2': 'Carcinoma lobulillar in situ',
'8520/3': 'Carcinoma lobulillar infiltrante',
'8522/3': 'Carcinoma ductal y lobulillar infiltrante',
'8480/3': 'Adenocarcinoma mucinoso',
'8211/3': 'Carcinoma tubular',
'8510/3': 'Carcinoma medular',
'8530/3': 'Carcinoma inflamatorio',
'8540/3': 'Enfermedad de Paget de la mama',
'9010/0': 'Fibroadenoma',
'9016/0': 'Fibroadenoma gigante',
};
export const name = (value: string) => LABELS[value] ?? HISTOLOGIC_TYPES[value] ?? value;
+3 -3
View File
@@ -13,6 +13,7 @@ export const LAYOUTS: Record<string, Layout> = {
'CACU_EU7', 'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE', 'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO', 'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
'CACU_DIAS_TOMA_TRATAMIENTO', 'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
], ],
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA', fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
}, },
{ {
label: 'Diagnóstico', label: 'Diagnóstico tras biopsia',
step: 'Del resultado de biopsia al diagnóstico', step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO', fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO', fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
}, },
], ],
@@ -50,7 +51,6 @@ export const LAYOUTS: Record<string, Layout> = {
'CAMA_EU38A', 'CAMA_EU38A',
'CAMA_DIAS_TOMA_DIAGNOSTICO', 'CAMA_DIAS_TOMA_DIAGNOSTICO',
'CAMA_CONFIRMACION_BIRADS45', 'CAMA_CONFIRMACION_BIRADS45',
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
], ],
route: [ route: [
{ {
+107 -9
View File
@@ -1,4 +1,3 @@
import { name } from './labels';
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4'; import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
import { code, ext } from '../fhir'; import { code, ext } from '../fhir';
import { Figure, PALETTE } from '../plot'; import { Figure, PALETTE } from '../plot';
@@ -24,11 +23,11 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
return found; return found;
} }
/** A period's first day ("2026-S2": July 1st; "2026-03": March 1st). */ /** Historical periods ending in the selected month or semester, oldest first. */
export function periodStart(period: string): Date { export function historyPeriods(type: PeriodType, selected: string): string[] {
const [year, part] = period.split('-'); const [year, part] = selected.split('-');
const month = part.startsWith('S') ? (part === 'S1' ? 0 : 6) : Number(part) - 1; const month = type === 'semester' ? (part === 'S1' ? 0 : 6) : Number(part) - 1;
return new Date(Number(year), month, 1); return periods(type, 6, new Date(Number(year), month, 1)).reverse();
} }
export function periodLabel(period: string): string { export function periodLabel(period: string): string {
@@ -106,6 +105,97 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
}; };
} }
/** Codes as the screens name them. */
export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)',
LSIL: 'LIEBG',
HSIL: 'LIEAG',
CIN2: 'CIN 2',
CIN3: 'CIN 3',
normal: 'Normal',
carcinoma: 'Carcinoma',
no_data: 'Sin dato',
'<25': '<25 años (sin límite inferior)',
no_biopsy: 'Sin biopsia',
pre_colposcopy: 'Pre colposcopia',
post_colposcopy: 'Post colposcopia',
post_treatment: 'Post tratamiento',
case: 'Caso (cáncer)',
low: 'Bajo',
intermediate: 'Intermedio',
high: 'Alto',
satisfactory: 'satisfactoria',
unsatisfactory: 'insatisfactoria',
benign: 'Benigno',
in_situ: 'Carcinoma in situ',
invasive: 'Carcinoma invasor',
cancer: 'Diagnóstico confirmado',
pending_biopsy: 'Pendiente de biopsia',
biopsy_no_result: 'Biopsia sin resultado',
benign_biopsy: 'Biopsia benigna',
confirmed: 'Diagnóstico confirmado',
in_process: 'En proceso',
not_confirmed: 'Sin TEA',
mchat_only: 'Solo M-CHAT',
psychology: 'Psicología (ADOS-2)',
neuropediatrics: 'Neuropediatría',
eeg: 'EEG',
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Detección inicial',
subsequent: 'Con detección anterior',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
positive_incomplete: 'Positivo con genotipificación incompleta',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
};
/** Breast histologic types (ICD-O-3 morphology); a code not listed is shown as it is. */
const HISTOLOGIC_TYPES: Record<string, string> = {
'8500/2': 'Carcinoma ductal in situ',
'8500/3': 'Carcinoma ductal infiltrante',
'8520/2': 'Carcinoma lobulillar in situ',
'8520/3': 'Carcinoma lobulillar infiltrante',
'8522/3': 'Carcinoma ductal y lobulillar infiltrante',
'8480/3': 'Adenocarcinoma mucinoso',
'8211/3': 'Carcinoma tubular',
'8510/3': 'Carcinoma medular',
'8530/3': 'Carcinoma inflamatorio',
'8540/3': 'Enfermedad de Paget de la mama',
'9010/0': 'Fibroadenoma',
'9016/0': 'Fibroadenoma gigante',
};
/** A follow-up priority's label. */
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
export const STRATA: Record<string, string> = {
category: 'Categoría',
age_group: 'Grupo de edad',
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Detección inicial o anterior',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
};
export const name = (value: string) => LABELS[value] ?? HISTOLOGIC_TYPES[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string { export function formatScore(measure: Measure, r: Reading | undefined): string {
if (!r || r.score === undefined) return 'Sin dato'; if (!r || r.score === undefined) return 'Sin dato';
switch (scoring(measure)) { switch (scoring(measure)) {
@@ -138,15 +228,23 @@ export function detail(measure: Measure, r: Reading | undefined, unit = 'pacient
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`); const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */ /** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure { export function donut(
let labels: string[], values: number[]; measure: Measure,
r: Reading,
stratifier = 'category',
/** a colour by category code (a proportion: `numerator` and `rest`); a part without one takes the palette's */
colors?: Record<string, string>,
): Figure {
let labels: string[], values: number[], codes: string[];
if (scoring(measure) === 'proportion') { if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations; const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto']; labels = ['Numerador', 'Resto'];
codes = ['numerator', 'rest'];
values = [numerator, denominator - numerator]; values = [numerator, denominator - numerator];
} else { } else {
const cells = Object.entries(r.strata[stratifier] ?? {}); const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v)); labels = cells.map(([v]) => name(v));
codes = cells.map(([v]) => v);
values = cells.map(([, c]) => c['initial-population'] ?? 0); values = cells.map(([, c]) => c['initial-population'] ?? 0);
} }
return { return {
@@ -158,7 +256,7 @@ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Fi
values, values,
sort: false, sort: false,
textinfo: 'value+percent', textinfo: 'value+percent',
marker: { colors: PALETTE }, marker: { colors: codes.map((c, i) => colors?.[c] ?? PALETTE[i % PALETTE.length]) },
}, },
], ],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } }, layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
+194 -131
View File
@@ -1,110 +1,139 @@
import type { Category, Mode } from './bars'; import type { Mode } from './bars';
import { import {
BIOPSY, BIOPSY_COLORS,
CONFIRMED, CYTOLOGY_COLORS,
CYTOLOGY, DURATION,
HPV, HPV_COLORS,
LEVEL, PPV_CYTOLOGY_COLORS,
PRIOR_CYTOLOGY, PPV_DONUT,
ROUND, PPV_LEVEL_COLORS,
TINT, QUARTILE,
} from './palette-cacu'; ROUND_COLORS,
import type { Page, ReadingsCard } from './pages'; } from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
const of = (colors: Record<string, string>, rows: [string, string][]): Category[] => const ABNORMAL = { label: 'Anormal', color: ROSE, codes: ['ASC-US', 'LSIL', 'ASC-H', 'HSIL', 'CIS', 'carcinoma'] };
rows.map(([code, label]) => ({ code, label, color: colors[code] }));
/** Bethesda results; the abnormal ones also added up under "Anormal". */ /** Bethesda results as the old app grouped and coloured them. */
const RESULTS = of(CYTOLOGY, [ const CYTOLOGY: Catalog = {
['NILM', 'Normal'], groups: [
['ASC-US', 'ASC-US'], { id: 'normal', label: 'Sin anomalía', color: OLIVE },
['LSIL', 'LIEBG'], { id: 'abnormal', label: 'Anormal', color: ROSE },
['ASC-H', 'ASC-H'], ],
['HSIL', 'LIEAG'], categories: [
['CIS', 'Carcinoma in situ'], { code: 'NILM', label: 'Normal', color: CYTOLOGY_COLORS['NILM'], group: 'normal' },
['carcinoma', 'Carcinoma epidermoide invasor'], { code: 'ASC-US', label: 'ASC-US', color: CYTOLOGY_COLORS['ASC-US'], group: 'abnormal' },
]); { code: 'LSIL', label: 'LIEBG', color: CYTOLOGY_COLORS['LSIL'], group: 'abnormal' },
const ABNORMAL = { label: 'Anormal', color: ROSE, codes: RESULTS.slice(1).map((c) => c.code) }; { code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
const GRADES = of(BIOPSY, [ { code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
['normal', 'Normal'], { code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
['LSIL', 'LIEBG (CIN 1)'], {
['CIN2', 'CIN 2'], code: 'carcinoma',
['HSIL', 'LIEAG (CIN 2 y 3)'], label: 'Carcinoma epidermoide invasor',
['CIN3', 'CIN 3'], color: BIOPSY_COLORS['carcinoma'],
['CIS', 'Carcinoma in situ'], group: 'abnormal',
['carcinoma', 'Carcinoma invasor'], },
]); ],
const GENOTYPES = of(HPV, [ };
['negative', 'Negativo'],
['positive_16', 'VPH 16'],
['positive_18', 'VPH 18'],
['positive_16_18', 'VPH 16 y 18'],
['positive_other', 'Positivo sin genotipo'],
]);
/** HPV categories not drawn: their reports stay in the total and the percentages. */
const UNDRAWN = { codes: ['positive_incomplete', 'inconsistent', 'no_result'], unit: 'reportes' };
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], group: 'low' },
{ code: 'CIN2', label: 'CIN 2', color: BIOPSY_COLORS['CIN2'], group: 'high' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: BIOPSY_COLORS['HSIL'], group: 'high' },
{ code: 'CIN3', label: 'CIN 3', color: BIOPSY_COLORS['CIN3'], group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
{
code: 'carcinoma',
label: 'Carcinoma invasor',
color: BIOPSY_COLORS['carcinoma'],
group: 'high',
},
],
faded: ['normal', 'LSIL'],
};
/** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [
{ code: 'negative', label: 'Negativo', color: HPV_COLORS['negative'] },
{ code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
{ code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
{ code: 'positive_other', label: 'Positivo sin genotipo', color: HPV_COLORS['positive_other'] },
];
/** The screening route's bars: a median, and the marks of its quartiles. */
const TINT = { bar: DURATION, mark: QUARTILE };
/** The screening rounds, in the order the cards draw them. */
const ROUNDS = ['initial', 'subsequent', 'no_data']; const ROUNDS = ['initial', 'subsequent', 'no_data'];
const BY_ROUND = 'Por detección inicial y anterior'; const ROUND_CAPTION =
const BY_AGE = 'Por grupo de edad'; 'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección inicial (primera vez en la vida), ' +
'con detección anterior (registrada, o ya con colposcopía o tratamiento) o «Sin dato». ' +
'Un grupo sin pacientes se muestra en cero; sin porcentaje.';
/** The views the cytology and HPV-by-genotype cards share (one selector for both). */
const GENERAL = 'General'; const GENERAL = 'General';
const BY_AGE = 'Por grupo de edad';
const BY_ROUND = 'Por detección inicial y anterior';
const AGE_GROUPS = ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'];
/** HPV categories the cards do not draw (their reports stay in the total and the percentages). */
const HPV_HIDDEN = {
codes: ['positive_incomplete', 'inconsistent', 'no_result'],
unit: 'reportes',
};
/** A results card's general reading and its readings by age group and by round (one /** One measure's breakdowns by group, each as stacked bars of the categories of `catalog`. */
* selector for both cards). */ const groupViews = (
function results(measure: string, catalog: Category[], unit: string, more: object): Mode[] { measure: string,
const caption = catalog: { code: string; label: string; color: string }[],
measure === 'CACU_VPH_GENOTIPO' unit: string,
? 'Porcentaje de reportes de VPH del grupo por genotipo.' more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string }; aggregate?: typeof ABNORMAL } = {},
: 'Porcentaje de pacientes del grupo por resultado citológico.'; ): Mode[] =>
const groups = [ [
{ { label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS },
label: BY_AGE,
stratum: 'age_group',
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
},
{ label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true }, { label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
]; ].map((v) => ({
return [ kind: 'grouped' as const,
{ measure,
kind: 'counts', catalog,
label: GENERAL, unit,
measure, caption: measure === 'CACU_VPH_GENOTIPO'
catalog, ? 'Porcentaje de reportes de VPH del grupo por genotipo.'
unit: unit === 'pacientes' ? 'Pacientes' : 'Reportes', : 'Porcentaje de pacientes del grupo por resultado citológico.',
percentLabel: ...v,
unit === 'pacientes' ? 'Porcentaje de pacientes' : 'Porcentaje de reportes de VPH', ...more,
...more, }));
},
...groups.map((g) => ({
kind: 'grouped' as const,
measure,
catalog,
unit,
caption,
ofAll: true,
...g,
...more,
})),
];
}
/** A confirmation rate's card: the whole, and by each of its stratifiers. */ /** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, percentLabel: string): ReadingsCard => ({ const ppv = (
measure: string,
title: string,
note: string,
percentLabel: string,
...more: Mode[]
): ReadingsCard => ({
kind: 'readings', kind: 'readings',
title, title,
headline: measure, headline: measure,
footnote: true, footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`, note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [ modes: [
{ kind: 'ratio', label: 'Total', measure, color: CONFIRMED, percentLabel }, { kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT, percentLabel },
{ {
kind: 'shares', kind: 'shares',
label: 'Citología previa', label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.', caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure, measure,
stratum: 'cytology', stratum: 'cytology',
colors: PRIOR_CYTOLOGY, colors: PPV_CYTOLOGY_COLORS,
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'], order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
percentLabel: 'Porcentaje de pacientes con esta citología previa', percentLabel: 'Porcentaje de pacientes con esta citología previa',
}, },
@@ -114,7 +143,7 @@ const ppv = (measure: string, title: string, note: string, percentLabel: string)
caption: 'Los grupos se traslapan.', caption: 'Los grupos se traslapan.',
measure, measure,
stratum: 'hpv', stratum: 'hpv',
colors: HPV, colors: HPV_COLORS,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'], order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
percentLabel: 'Porcentaje de pacientes de cada grupo de VPH previo', percentLabel: 'Porcentaje de pacientes de cada grupo de VPH previo',
}, },
@@ -123,25 +152,22 @@ const ppv = (measure: string, title: string, note: string, percentLabel: string)
label: 'Nivel de histología', label: 'Nivel de histología',
measure, measure,
stratum: 'level', stratum: 'level',
colors: LEVEL, colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'], order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
percentLabel: 'Porcentaje de pacientes de cada nivel de histología', percentLabel: 'Porcentaje de pacientes de cada nivel de histología',
}, },
{ {
kind: 'shares', kind: 'shares',
label: BY_ROUND, label: 'Por detección inicial y anterior',
caption: caption: ROUND_CAPTION,
'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección ' +
'inicial (primera vez en la vida), con detección anterior (registrada, o ya con ' +
'colposcopía o tratamiento) o «Sin dato». Un grupo sin pacientes se muestra en cero; ' +
'sin porcentaje.',
measure, measure,
stratum: 'round', stratum: 'round',
colors: ROUND, colors: ROUND_COLORS,
order: ROUNDS, order: ROUNDS,
complete: true, complete: true,
percentLabel: 'Porcentaje de pacientes de cada ronda', percentLabel: 'Porcentaje de pacientes de cada ronda',
}, },
...more,
], ],
}); });
@@ -149,16 +175,8 @@ const CACU_DAYS = {
value: '{median} días (mediana)', value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.', note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
}; };
const days = (label: string, ...steps: [string, string][]): Mode => ({
kind: 'days',
label,
tint: TINT,
steps: steps.map(([label, measure]) => ({ label, measure })),
});
export const CACU: Page = { export const CACU: Page = {
anchor: 'CACU_EU7', anchor: 'CACU_EU7',
clinicalFirst: true,
kpis: [ kpis: [
{ {
measure: 'CACU_EU7', measure: 'CACU_EU7',
@@ -193,34 +211,54 @@ export const CACU: Page = {
title: 'Tiempos de tamizaje', title: 'Tiempos de tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.', note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [ modes: [
days(
'Acumulado desde la toma',
['Resultado de citología', 'CACU_EU_TIEMPO_REPORTE'],
['Resultado de colposcopía', 'CACU_DIAS_TOMA_COLPOSCOPIA'],
['Resultado de biopsia', 'CACU_DIAS_TOMA_BIOPSIA'],
['Diagnóstico tras biopsia', 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA'],
),
{ {
...days( kind: 'days',
'Por ventana de tiempo', tint: TINT,
['Toma a resultado de citología', 'CACU_EU_TIEMPO_REPORTE'], label: 'Acumulado desde la toma',
['Resultado a colposcopía', 'CACU_DIAS_RESULTADO_COLPOSCOPIA'], steps: [
['Colposcopía a biopsia', 'CACU_DIAS_COLPOSCOPIA_BIOPSIA'], { label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
['Biopsia a diagnóstico', 'CACU_DIAS_BIOPSIA_DIAGNOSTICO'], { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
), { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{
label: 'Diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
},
{
kind: 'days',
tint: TINT,
label: 'Por ventana de tiempo',
staggered: true, staggered: true,
caption: caption:
'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus ' + 'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus propias pacientes: las medianas no se suman.',
'propias pacientes: las medianas no se suman.', steps: [
} as Mode, {
days('Diagnóstico precolposcópico', [ label: 'Toma a resultado de citología',
'Toma a primer diagnóstico', measure: 'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO', },
]), { label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
days('Diagnóstico tras biopsia', [ { label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
'Toma a diagnóstico tras biopsia', { label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA', ],
]), },
{
kind: 'days',
tint: TINT,
label: 'Diagnóstico precolposcópico',
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',
},
],
},
], ],
}, },
], ],
@@ -236,14 +274,39 @@ export const CACU: Page = {
follows: true, follows: true,
title: 'Distribución de resultados citológicos', title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.', note: 'Pacientes, por su última muestra válida del periodo.',
modes: results('CACU_EU7', RESULTS, 'pacientes', { aggregate: ABNORMAL }), modes: [
{
kind: 'counts',
label: GENERAL,
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
aggregate: ABNORMAL,
unit: 'Pacientes',
percentLabel: 'Porcentaje de pacientes',
},
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes', { aggregate: ABNORMAL, ofAll: true }),
],
}, },
{ {
kind: 'readings', kind: 'readings',
follows: true, follows: true,
title: 'Resultados de VPH por genotipo', title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.', note: 'Reportes, por fecha de toma.',
modes: results('CACU_VPH_GENOTIPO', GENOTYPES, 'reportes', { hidden: UNDRAWN }), modes: [
{
kind: 'counts',
label: GENERAL,
measure: 'CACU_VPH_GENOTIPO',
catalog: HPV,
unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de VPH',
hidden: HPV_HIDDEN,
},
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
ofAll: true,
hidden: HPV_HIDDEN,
}),
],
}, },
{ {
kind: 'readings', kind: 'readings',
@@ -252,9 +315,9 @@ export const CACU: Page = {
modes: [ modes: [
{ {
kind: 'counts', kind: 'counts',
label: GENERAL, label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS', measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: GRADES, catalog: BIOPSY.categories,
unit: 'Reportes', unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de biopsia', percentLabel: 'Porcentaje de reportes de biopsia',
}, },
-228
View File
@@ -1,228 +0,0 @@
import type { Catalog, Page } from './pages';
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
groups: [],
categories: [
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
],
};
/** What a patient without a typed biopsy shows. */
const NO_TYPE = [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
];
/** CaMa's page: the timeliness cards and their route, then the clinical indicators. */
export const CAMA: Page = {
anchor: 'CAMA_BIRADS456_PACIENTE',
kpis: [
{
measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
},
{
measure: 'CAMA_EU38A',
title: 'Tiempo 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',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
title: 'Tiempo de interpretación radiológica a resultado de biopsia',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CAMA_DAYS,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempo de tamizaje a diagnóstico y tratamiento',
modes: [
{
kind: 'days',
label: 'Por pasos',
rowsLabel: 'Paso',
staggered: true,
scale: true,
tint: { bar: '#42A77E', mark: '#17324D' },
caption:
'Esquema: cada barra es la mediana de su paso y empieza donde termina el paso del ' +
'que parte. Los pasos pueden corresponder a poblaciones diferentes, por lo que las ' +
'medianas no se suman. Las marcas indican el primer y tercer cuartil.',
steps: [
{ label: 'Toma de mastografía a interpretación radiológica', measure: 'CAMA_EU38A' },
{
label: 'Interpretación radiológica a diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
},
{
label: 'Diagnóstico tras biopsia a tratamiento',
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
},
// from the interpretation, as the diagnosis
{
label: 'Interpretación radiológica a resultado de biopsia',
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
after: 0,
},
],
},
{
kind: 'days',
label: 'Acumulado desde la toma',
rowsLabel: 'Etapa',
scale: true,
tint: { bar: '#42A77E', mark: '#17324D' },
caption:
'Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se ' +
'calcula por separado. Las marcas indican el primer y tercer cuartil.',
steps: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
},
],
},
],
},
],
clinical: [
{
kind: 'figures',
figures: [
{
kind: 'share-donut',
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
catalog: BIRADS,
center: 'mastografías',
},
{
kind: 'share-donut',
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_PACIENTE',
catalog: BIRADS,
center: 'pacientes',
},
],
},
{
kind: 'readings',
title: 'Tipo histológico por categoría BI-RADS',
note:
'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave ' +
'reportada, por fecha del examen. Los tipos siguen la clasificación CIE-O-3; «Sin dato» ' +
'incluye tipos ausentes o ' +
'con vínculo ambiguo. El porcentaje maligno conserva la clasificación de la biopsia y ' +
'su denominador de pacientes con clasificación conocida.',
modes: [
{
kind: 'outcomes',
label: 'Por categoría BI-RADS',
heading: 'Resultados por paciente',
caption: '«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.',
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
results: NO_TYPE,
malignant: ['in_situ', 'invasive'],
malignancy: 'CAMA_HISTOPATOLOGIA_BIRADS',
},
{
kind: 'counts',
label: 'Todas las categorías',
heading: 'Resultados por paciente',
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
catalog: [],
unit: 'Pacientes',
percent: true,
percentLabel: 'Porcentaje de pacientes',
},
],
},
{
kind: 'choice',
title: 'Confirmación histopatológica',
card: true,
choices: [
{
label: 'Tipos histológicos',
section: {
kind: 'readings',
title: 'Tipos histológicos',
note:
'Biopsias por fecha de reporte, agrupadas por tipo histológico (CIE-O-3). «Sin dato» ' +
'incluye los ' +
'tipos ausentes y los que no pueden vincularse de forma inequívoca. La tasa de ' +
'detección conserva su cálculo de carcinomas entre biopsias con clasificación ' +
'conocida; su denominador puede ser distinto.',
modes: [
{
kind: 'counts',
label: 'Tipos histológicos',
heading: 'Tipo histológico',
measure: 'CAMA_TIPO_HISTOLOGICO',
catalog: [],
unit: 'Biopsias',
percent: true,
percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
},
{
label: 'Mastografías con biopsia',
section: {
kind: 'readings',
title: 'Mastografías con biopsia',
headline: 'CAMA_CONFIRMACION_BIRADS45',
unit: 'mastografías',
note:
'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: ' +
'cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de ' +
'la biopsia.',
modes: [
{
kind: 'split',
label: 'Con y sin biopsia',
measure: 'CAMA_CONFIRMACION_BIRADS45',
yes: 'Con reporte de biopsia',
no: 'Sin reporte de biopsia',
colors: ['#A8C243', '#C9CDD2'],
unit: 'Mastografías',
percentLabel: 'Porcentaje de mastografías',
},
],
},
},
],
},
],
};
+442 -11
View File
@@ -1,14 +1,12 @@
import type { Mode } from './bars'; import type { Mode } from './bars';
import { CACU } from './pages-cacu'; import { CACU } from './pages-cacu';
import { CAMA } from './pages-cama'; import type { RouteStep } from './durations';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui): /** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures. * the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */ * Measures are named by their code (`Measure.name`). */
export interface Page { export interface Page {
kpis: Kpi[]; kpis: Kpi[];
/** the clinical indicators before the timeliness ones (CaCu) */
clinicalFirst?: boolean;
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */ /** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
opportunity?: Section[]; opportunity?: Section[];
clinical: Section[]; clinical: Section[];
@@ -28,27 +26,33 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** the headline said under the figure, not above it */ /** say the headline under the figure instead of above it */
footnote?: boolean; footnote?: boolean;
/** what the headline proportion counts, in the plural (default: pacientes) */ /** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string; unit?: string;
note?: string; note?: string;
modes: Mode[]; modes: Mode[];
/** in `columns` with `views`, the mode its section's selector picks */ /** in a `columns` section with `views`: takes the mode whose label the section's selector chose */
follows?: boolean; follows?: boolean;
} }
export type Section = export type Section =
| ReadingsCard | ReadingsCard
/** Cards side by side, the last one alone when odd; `views`: one selector (its first view /** A screening route as one compact card: a bar per step with its median, observations and
* by default) for the cards that follow it */ * quartiles. `sample` reads each step from the sample (its own measure, never a sum of
* medians); `step` reads each from the previous step. A reading with no steps is not offered. */
| { kind: 'route'; title: string; sample: RouteStep[]; step: RouteStep[] }
/** Cards side by side; the last one alone when odd. */
| { | {
kind: 'columns'; kind: 'columns';
title: string; title: string;
sections: ReadingsCard[]; sections: ReadingsCard[];
/** one selector for the cards that `follow` it: the labels of their modes, the first by default */
views?: string[]; views?: string[];
viewsLabel?: string; viewsLabel?: string;
} }
/** One section at a time; `card`: the title, the toggle and the chosen card in one card */ /** One section at a time. */
/** `card`: the title, the tabs and the chosen reading in one card (the reading's own title is
* left out: its tab names it) */
| { | {
kind: 'choice'; kind: 'choice';
title: string; title: string;
@@ -61,15 +65,18 @@ export type Section =
/** none: the boxes stand alone (TEA) */ /** none: the boxes stand alone (TEA) */
title?: string; title?: string;
cards: { measure?: string; title: string }[]; cards: { measure?: string; title: string }[];
/** the measure's own title under each card's (CaMa) */
subtitles?: boolean;
} }
/** Each figure in its own card, titled, two to a row (TEA). */ /** Each figure in its own card, titled, two to a row (TEA). */
| { kind: 'grid'; figures: FigureSpec[] } | { kind: 'grid'; figures: FigureSpec[] }
/** TEA's period summary in words, its numbers from the measures. */ /** TEA's period summary in words, its numbers from the measures. */
| { kind: 'tea-summary' }; | { kind: 'tea-summary' }
| ({ kind: 'card' } & Kpi);
/** Figure titles may carry `{p}`, the applied period. */ /** Figure titles may carry `{p}`, the applied period. */
export type FigureSpec = export type FigureSpec =
| { | {
kind: 'share-donut'; kind: 'donut' | 'share-donut';
title: string; title: string;
measure: string; measure: string;
catalog: Catalog; catalog: Catalog;
@@ -83,6 +90,18 @@ export type FigureSpec =
measure: string; measure: string;
/** the numerator's and the rest's names (stack), or the axis (share) */ /** the numerator's and the rest's names (stack), or the axis (share) */
names: [string, string]; names: [string, string];
}
| {
kind: 'rates';
title: string;
measure: string;
stratum: string;
rows: Category[];
/** each row in its category's colour (else all rose) */
colored?: boolean;
/** the categories (of the measure) that count as a positive */
positive: string[];
axis: string;
}; };
export interface Category { export interface Category {
@@ -99,6 +118,41 @@ export interface Catalog {
} }
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269';
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
groups: [],
categories: [
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
],
};
/** A breast biopsy's grades, and what stands in their place when there is none. */
const BIOPSY_GRADES = [
{ code: 'benign', label: 'Benigno', color: '#A8C243' },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2' },
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2' },
];
/** What «Sin biopsia» says, whatever the contract's category is called. */
const NO_BIOPSY_MEANS =
'«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.';
const INSTITUTIONAL = '#A8C243';
const NEUTRAL = '#C9CDD2';
const NO_RESULT = [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
];
export const PAGES: Record<string, Page> = { export const PAGES: Record<string, Page> = {
tea: { tea: {
@@ -193,6 +247,383 @@ export const PAGES: Record<string, Page> = {
}, },
], ],
}, },
cama: CAMA, cama: {
anchor: 'CAMA_BIRADS456_PACIENTE',
// every single-number card, together at the start, in the order asked for
kpis: [
{
measure: 'CAMA_BIRADS456_PACIENTE',
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
},
{
measure: 'CAMA_EU38A',
title: 'Tiempo 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',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
title: 'Tiempo de interpretación radiológica a resultado de biopsia',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
...CAMA_DAYS,
},
{
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CAMA_DAYS,
},
],
opportunity: [
{
kind: 'route',
title: 'Tiempo de tamizaje a diagnóstico y tratamiento',
// 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)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
},
],
step: [
{ label: 'Toma de mastografía a interpretación radiológica', measure: 'CAMA_EU38A' },
{
label: 'Interpretación radiológica a diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
},
{
label: 'Diagnóstico tras biopsia a tratamiento',
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
},
{
label: 'Interpretación radiológica a resultado de biopsia',
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
// from the interpretation, as the diagnosis: not after it
after: 0,
},
],
},
],
clinical: [
{
kind: 'figures',
figures: [
{
kind: 'share-donut',
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
catalog: BIRADS,
center: 'mastografías',
},
{
kind: 'share-donut',
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
measure: 'CAMA_BIRADS456_PACIENTE',
catalog: BIRADS,
center: 'pacientes',
},
],
},
{
kind: 'readings',
title: 'Tipo histológico por categoría BI-RADS',
note: 'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave reportada, por fecha del examen. Los tipos siguen la clasificación CIE-O-3; «Sin dato» incluye tipos ausentes o con vínculo ambiguo. El porcentaje maligno conserva la clasificación de la biopsia y su denominador de pacientes con clasificación conocida.',
modes: [
{
kind: 'outcomes',
label: 'Por categoría BI-RADS',
heading: 'Resultados por paciente',
caption: NO_BIOPSY_MEANS,
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
results: NO_RESULT,
malignant: ['in_situ', 'invasive'],
dynamicResults: true,
malignancyMeasure: 'CAMA_HISTOPATOLOGIA_BIRADS',
},
{
kind: 'counts',
label: 'Todas las categorías',
heading: 'Resultados por paciente',
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
catalog: [],
unit: 'Pacientes',
percent: true,
percentLabel: 'Porcentaje de pacientes',
},
],
},
{
kind: 'choice',
title: 'Confirmación histopatológica',
card: true,
choices: [
{
label: 'Tipos histológicos',
section: {
kind: 'readings',
title: 'Tipos histológicos',
unit: 'biopsias',
note: 'Biopsias por fecha de reporte, agrupadas por tipo histológico (CIE-O-3). «Sin dato» incluye los tipos ausentes y los que no pueden vincularse de forma inequívoca. La tasa de detección conserva su cálculo de carcinomas entre biopsias con clasificación conocida; su denominador puede ser distinto.',
modes: [
{
kind: 'counts',
label: 'Tipos histológicos',
heading: 'Tipo histológico',
measure: 'CAMA_TIPO_HISTOLOGICO',
catalog: [],
unit: 'Biopsias',
percent: true,
percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
},
{
label: 'Mastografías con biopsia',
section: {
kind: 'readings',
title: 'Mastografías con biopsia',
headline: 'CAMA_CONFIRMACION_BIRADS45',
unit: 'mastografías',
note: 'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de la biopsia.',
modes: [
{
kind: 'split',
label: 'Con y sin biopsia',
measure: 'CAMA_CONFIRMACION_BIRADS45',
yes: 'Con reporte de biopsia',
no: 'Sin reporte de biopsia',
colors: [INSTITUTIONAL, NEUTRAL],
unit: 'Mastografías',
percentLabel: 'Porcentaje de mastografías',
},
],
},
},
],
},
],
},
cacu: CACU, cacu: CACU,
}; };
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
export interface HistoryPanel {
title: string;
measure: string;
kind: 'stack' | 'percent' | 'median';
/** stack: the categories, in the old order, with their names and colours */
series?: { code: string; label: string; color: string }[];
/** stack: the y axis */
axis?: string;
group?: string;
}
export interface History {
panels: HistoryPanel[];
/** the line's colour (percent and median) */
line: string;
/** how many of the latest months the tab opens with (none: from the first with data) */
months?: number;
}
const GREY = '#C9CDD2';
const stack = (
title: string,
measure: string,
axis: string,
series: [string, string, string][],
): HistoryPanel => ({
title,
measure,
kind: 'stack',
axis,
series: series.map(([code, label, color]) => ({ code, label, color })),
});
const BIRADS_SERIES: [string, string, string][] = [
['4A', 'BI-RADS 4A', '#C24269'],
['4B', 'BI-RADS 4B', '#9C42C2'],
['4C', 'BI-RADS 4C', '#5C42C2'],
['5', 'BI-RADS 5', '#C2429C'],
['6', 'BI-RADS 6', '#8E2F62'],
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
];
export const HISTORY: Record<string, History> = {
cacu: {
line: '#6A8000',
months: 5,
panels: [
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
['NILM', 'Normal', '#9DBFE3'],
['ASC-US', 'ASC-US', '#2F6DB3'],
['LSIL', 'LIEBG', '#9C42C2'],
['ASC-H', 'ASC-H', '#5C42C2'],
['HSIL', 'LIEAG', '#C2429C'],
['CIS', 'Carcinoma in situ', '#8E2F62'],
['no_data', 'Sin dato', GREY],
]),
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
stack(
'Resultado de biopsia tras citología de alto grado',
'CACU_CONFIRMACION_CITOLOGIA',
'Pacientes',
[
['normal', 'Normal', '#9DBFE3'],
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
['CIN2', 'CIN 2', '#E07A9C'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
['CIN3', 'CIN 3', '#A8325A'],
['CIS', 'Carcinoma in situ', '#9C42C2'],
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
['no_biopsy', 'Sin biopsia aún', GREY],
['no_data', 'Biopsia sin grado', GREY],
],
),
{
title: 'Días de la toma de la citología a su resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median',
},
{
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
{
title: 'Riesgo CIN2+ por banda',
measure: 'CACU_RIESGO_BANDA',
kind: 'stack',
axis: 'Pacientes',
},
],
},
cama: {
line: '#9C42C2',
panels: [
{ title: 'Tiempo de diagnóstico tras biopsia a tratamiento', measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO', kind: 'median' },
{
title: 'Días de la toma de la mastografía a su resultado',
measure: 'CAMA_EU38A',
kind: 'median',
},
{
title: 'Días del resultado de la mastografía al diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{ title: 'Tasa de detección histopatológica', measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', kind: 'percent' },
stack(
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_MASTOGRAFIA',
'Mastografías',
BIRADS_SERIES,
),
stack(
'Pacientes con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_PACIENTE',
'Pacientes',
BIRADS_SERIES,
),
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
['benign', 'Benigno', '#9DBFE3'],
['in_situ', 'Carcinoma in situ', '#C24269'],
['invasive', 'Carcinoma invasor', '#9C42C2'],
['no_biopsy', 'Sin biopsia reportada', GREY],
['no_data', 'Sin dato', GREY],
]),
{
title: 'Confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent',
},
],
},
tea: {
line: '#9C42C2',
panels: [
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a ADOS-2',
measure: 'M26_DIAS_MCHAT_ADOS2',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de ADOS-2 a diagnóstico',
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
kind: 'median',
},
{
group: 'Tiempos del tamizaje',
title: 'Días de M-CHAT a diagnóstico positivo',
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
kind: 'median',
},
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
['in_process', 'En proceso', '#B8433A'],
]),
{
title: 'Porcentaje de confirmación diagnóstica',
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
kind: 'percent',
},
{
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
kind: 'percent',
},
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
['mchat_only', 'Solo M-CHAT', '#B8433A'],
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
['eeg', 'Con EEG', '#A8C243'],
]),
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
['good', 'Bueno', '#A8C243'],
['bad', 'No aceptable', '#B8433A'],
['not_analyzed', 'Sin analizar', GREY],
]),
],
},
};
-69
View File
@@ -1,69 +0,0 @@
/** CaCu's colours, by category: a colour names a category (never a position in a report), so
* one category looks the same on every card; greys are what is absent or not classified. */
export const NEUTRAL = '#C9CDD2';
export const NEUTRAL_DARK = '#9AA3AB';
const STEEL = '#5F7F9A';
const STEEL_MID = '#8FA7BB';
const GREEN = '#408651';
const BLUE = '#2778B8';
const OCHRE = '#B19525';
const VIOLET = '#7955B1';
const PINK = '#E07A9C';
const RASPBERRY = '#CE4778';
const RUBY = '#BC4163';
const WINE = '#AA394D';
const PLUM = '#8D4C79';
export const CYTOLOGY: Record<string, string> = {
NILM: GREEN,
'ASC-US': BLUE,
LSIL: OCHRE,
'ASC-H': VIOLET,
HSIL: RASPBERRY,
CIS: WINE,
carcinoma: PLUM,
no_data: NEUTRAL,
};
export const BIOPSY: Record<string, string> = {
normal: GREEN,
LSIL: OCHRE,
CIN2: PINK,
HSIL: RASPBERRY,
CIN3: RUBY,
CIS: WINE,
carcinoma: PLUM,
no_data: NEUTRAL,
};
/** HPV by genotype; a prior HPV group takes its genotype's colour. */
export const HPV: Record<string, string> = {
negative: '#42A77E',
positive_16: '#DF8640',
positive_18: '#C29C42',
positive_16_18: '#C24269',
positive_other: '#A8C243',
positive: '#A8C243',
hpv_16: '#DF8640',
hpv_18: '#C29C42',
no_data: NEUTRAL,
};
export const ROUND: Record<string, string> = {
initial: STEEL,
subsequent: STEEL_MID,
no_data: NEUTRAL,
};
/** A PPV's groups: a cytology or histology level takes its category's colour. */
export const PRIOR_CYTOLOGY: Record<string, string> = {
ascus_plus: BLUE,
lsil_plus: OCHRE,
hsil_plus: RASPBERRY,
no_data: NEUTRAL,
};
export const LEVEL: Record<string, string> = {
cin1_plus: OCHRE,
cin2_plus: RASPBERRY,
carcinoma: PLUM,
};
export const CONFIRMED = '#6A8000';
/** A median's bar and its quartile marks. */
export const TINT = { bar: '#42A77E', mark: '#17324D' };
-132
View File
@@ -1,132 +0,0 @@
@if (!hideTitle()) {
<h3 class="title">{{ title() }}</h3>
}
@if (headline()) {
<p class="headline">{{ headline() }}</p>
}
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1 && !view()) {
<mat-button-toggle-group
[attr.aria-label]="title()"
[value]="mode().label"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.label) {
<mat-button-toggle [value]="m.label">{{ m.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
@if (mode().caption) {
<p class="state">{{ mode().caption }}</p>
}
@if (mode().heading) {
<h4 class="heading">{{ mode().heading }}</h4>
}
@if (loading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (missing(); as why) {
<p class="state" role="status">{{ why }}</p>
} @else if (groups(); as g) {
<div class="axis" aria-hidden="true">
<span></span>
<span class="ticks">
@for (t of [0, 25, 50, 75, 100]; track t) {
<span [style.left.%]="t">{{ t }} %</span>
}
</span>
<span></span>
</div>
@for (group of g.groups; track group.code) {
<section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label">
<h4>
{{ group.label }} <span class="n">{{ unit() }}: {{ group.total }}</span>
@if (group.hint) {
<span class="n">{{ group.hint }}</span>
}
</h4>
@for (row of group.rows; track row.label) {
<div class="row" [class.sub]="row.sub" [attr.data-category]="row.label">
<span class="name">{{ row.label }}</span>
<span class="track" aria-hidden="true">
<span
class="fill"
[style.width.%]="row.percent ?? 0"
[style.background]="row.color"
></span>
</span>
<span class="value">{{ row.text }}</span>
</div>
}
</section>
}
@if (g.note) {
<p class="state">{{ g.note }}</p>
}
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
<tr>
<th>{{ mode().rowsLabel ?? '' }}</th>
@for (h of t.head; track h) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<tr [class.sub]="row.sub">
<th scope="row">
{{ row.label }}
@if (row.hint) {
<span class="hint">{{ row.hint }}</span>
}
@if (row.none) {
<span class="hint">{{ row.none }}</span>
} @else {
<span class="track" aria-hidden="true">
@for (p of row.segments ?? []; track $index) {
<span
class="bar"
[style.width.%]="p.width"
[style.background]="p.color"
[attr.title]="p.title"
></span>
} @empty {
<span
class="bar"
[style.margin-left.%]="row.offset"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
}
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m" [style.background]="t.markColor"></span>
}
</span>
}
</th>
@for (c of row.cells; track $index) {
<td>{{ c }}</td>
}
</tr>
}
</tbody>
</table>
@if (t.note) {
<p class="state">{{ t.note }}</p>
}
@if (t.legend; as legend) {
<p class="legend">
@for (l of legend; track l.label) {
<span><i [style.background]="l.color"></i>{{ l.label }}</span>
}
</p>
}
} @else {
<p class="state">Sin datos en el periodo.</p>
}
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
-156
View File
@@ -1,156 +0,0 @@
:host {
--name-width: minmax(9rem, 16rem);
--value-width: 8.5rem;
display: block;
min-width: 0;
}
:host(.compact) {
overflow-x: auto;
.title {
font-size: 18px;
font-weight: 500;
}
.state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
table {
font-size: 13px;
}
thead th {
font-weight: 500;
}
}
.title {
margin: 0 0 8px;
}
.headline {
font-weight: 500;
}
.heading {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
mat-button-toggle-group {
flex-wrap: wrap;
margin: 4px 0;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
font-weight: 400;
padding: 4px 6px;
text-align: right;
white-space: nowrap;
}
thead th:first-child,
th[scope='row'] {
text-align: left;
white-space: normal;
width: 60%;
}
tr.sub th[scope='row'],
.row.sub .name {
padding-left: 1.25rem;
}
.hint {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
}
.track {
background: rgba(0, 0, 0, 0.06);
display: flex;
height: 8px;
position: relative;
}
.bar {
background: #a8c243;
display: block;
flex: none;
height: 100%;
}
.mark {
background: #333;
height: 12px;
position: absolute;
top: -2px;
width: 2px;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 16px;
i {
display: inline-block;
height: 10px;
margin-right: 6px;
width: 10px;
}
}
.axis,
.row {
column-gap: 8px;
display: grid;
grid-template-columns: var(--name-width) 1fr var(--value-width);
}
.axis {
font-size: 12px;
margin: 12px 0 2px;
}
.ticks {
height: 1.2em;
position: relative;
span {
position: absolute;
transform: translateX(-50%);
white-space: nowrap;
}
span:first-child {
transform: none;
}
span:last-child {
transform: translateX(-100%);
}
}
.group {
margin: 6px 0 14px;
h4 {
font-size: 0.95rem;
margin: 0 0 4px;
}
.n {
color: var(--color-text-secondary);
font-size: 0.8em;
font-weight: 400;
margin-left: 8px;
}
}
.row {
align-items: center;
font-size: 0.9rem;
min-height: 22px;
.track {
background:
linear-gradient(to right, #d8dde1 1px, transparent 1px) 25% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 50% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 75% 0 / 1px 100% no-repeat,
rgba(0, 0, 0, 0.06);
height: 10px;
}
.fill {
display: block;
height: 100%;
}
.value {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
}
+375 -28
View File
@@ -1,49 +1,396 @@
import { Component, computed, input, signal } from '@angular/core'; import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { bars, Mode, Read } from './bars'; import { Figure, Plot } from '../plot';
import { grouped, outcomes, shares, unavailable } from './groups'; import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars (or the /** A card read one mode at a time: its title, its headline, the toggle and the bars. */
* groups of bars). In a section with one selector for several cards, `view` picks the mode. */
@Component({ @Component({
selector: 'app-readings', selector: 'app-readings',
imports: [Loading, MatButtonToggleModule], host: { '[class.cama]': 'camaStyle()' },
host: { '[class.compact]': 'compact()' }, imports: [Loading, MatButtonToggleModule, Plot],
templateUrl: './readings.html', template: `
styleUrl: './readings.scss', @if (!hideTitle()) {
<h3 class="title">{{ title() }}</h3>
}
@if (headline()) {
<p class="headline">{{ headline() }}</p>
}
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1 && !view()) {
<mat-button-toggle-group
[attr.aria-label]="title()"
[value]="mode().label"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.label) {
<mat-button-toggle [value]="m.label">{{ m.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
@if (mode().heading) {
<h4 class="heading">{{ mode().heading }}</h4>
}
@if (mode().caption) {
<p class="state">{{ mode().caption }}</p>
}
@if (loading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (missing(); as why) {
<p class="state" role="status">{{ why }}</p>
} @else if (groups(); as g) {
<div class="axis" aria-hidden="true">
<span></span>
<span class="ticks">
<span style="left: 0">0 %</span><span style="left: 25%">25 %</span
><span style="left: 50%">50 %</span><span style="left: 75%">75 %</span
><span style="left: 100%">100 %</span>
</span>
<span></span>
</div>
@for (group of g.groups; track group.code) {
<section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label">
<h4>
{{ group.label }} <span class="n">{{ countUnit() }}: {{ group.total }}</span>
@if (group.hint) {
<span class="hint">{{ group.hint }}</span>
}
</h4>
@for (row of group.rows; track row.label) {
<div class="row" [class.sub]="row.sub" [attr.data-category]="row.label">
<span class="name">{{ row.label }}</span>
<span class="track" aria-hidden="true">
<span
class="fill"
[style.width.%]="row.percent ?? 0"
[style.background]="row.color"
></span>
</span>
<span class="value">{{ row.text }}</span>
</div>
}
</section>
}
@if (g.note) {
<p class="state">{{ g.note }}</p>
}
} @else if (figure(); as f) {
<app-plot [figure]="f" [height]="height()" />
@if (hidden(); as why) {
<p class="state">{{ why }}</p>
}
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
<tr>
<th></th>
@for (h of t.head; track h) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<tr [class.sub]="row.sub">
<th scope="row">
{{ row.label }}
@if (row.hint) {
<span class="hint">{{ row.hint }}</span>
}
@if (row.none) {
<span class="none">{{ row.none }}</span>
} @else {
<span class="track" [class.parts]="!!row.segments" aria-hidden="true">
@if (row.segments; as parts) {
@for (p of parts; track $index) {
<span
class="bar"
[style.width.%]="p.width"
[style.background]="p.color"
[attr.title]="p.title"
></span>
}
} @else {
<span
class="bar"
[style.margin-left.%]="row.offset"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
}
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m" [style.background]="t.markColor"></span>
}
</span>
}
</th>
@for (c of row.cells; track $index) {
<td>{{ c }}</td>
}
</tr>
}
</tbody>
</table>
@if (t.note) {
<p class="state">{{ t.note }}</p>
}
@if (t.legend; as legend) {
<p class="legend">
@for (l of legend; track l.label) {
<span><i [style.background]="l.color"></i>{{ l.label }}</span>
}
</p>
}
} @else {
<p class="state">Sin datos en el periodo.</p>
}
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`,
styles: `
tr.sub th,
.row.sub .name {
padding-left: 1.25rem;
}
:host {
display: block;
min-width: 0;
}
:host(.cama) {
overflow-x: auto;
}
.title {
margin: 0 0 8px;
}
:host(.cama) .title {
font-size: 18px;
font-weight: 500;
}
.heading {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
.headline {
font-weight: 500;
}
:host(.cama) .headline {
margin: 8px 0;
}
:host(.cama) .state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
mat-button-toggle-group {
flex-wrap: wrap;
margin: 4px 0;
}
table {
border-collapse: collapse;
width: 100%;
}
:host(.cama) table {
font-size: 13px;
}
:host(.cama) thead th {
font-weight: 500;
}
th,
td {
font-weight: 400;
padding: 4px 6px;
text-align: right;
white-space: nowrap;
}
th[scope='row'] {
text-align: left;
white-space: normal;
width: 60%;
}
.axis {
column-gap: 8px;
display: grid;
font-size: 12px;
grid-template-columns: var(--name-width) 1fr var(--value-width);
margin: 12px 0 2px;
}
.ticks {
height: 1.2em;
position: relative;
}
.ticks span {
white-space: nowrap;
position: absolute;
transform: translateX(-50%);
}
.ticks span:first-child {
transform: none;
}
.ticks span:last-child {
transform: translateX(-100%);
}
.group {
margin: 6px 0 14px;
}
.group h4 {
font-size: 0.95rem;
margin: 0 0 4px;
}
.group .n,
.group .hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
font-size: 0.8em;
font-weight: 400;
margin-left: 8px;
}
.row {
align-items: center;
column-gap: 8px;
display: grid;
font-size: 0.9rem;
grid-template-columns: var(--name-width) 1fr var(--value-width);
min-height: 22px;
}
.row .track {
background:
linear-gradient(to right, #d8dde1 1px, transparent 1px) 25% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 50% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 75% 0 / 1px 100% no-repeat,
rgba(0, 0, 0, 0.06);
display: block;
height: 10px;
}
.row .fill {
display: block;
height: 100%;
}
.row .value {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
:host {
--name-width: 8.5rem;
--value-width: 8.5rem;
}
@media (max-width: 600px) {
:host {
--name-width: 0px;
--value-width: 0px;
}
.axis {
grid-template-columns: 1fr;
}
.axis > span:not(.ticks) {
display: none;
}
.row {
grid-template-areas: 'name value' 'track track';
grid-template-columns: 1fr auto;
padding-bottom: 4px;
}
.row .name {
grid-area: name;
}
.row .value {
grid-area: value;
}
.row .track {
grid-area: track;
}
}
.hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
display: block;
font-size: 0.8em;
}
.track {
background: rgba(0, 0, 0, 0.06);
display: block;
height: 8px;
position: relative;
}
.bar {
background: #a8c243;
display: block;
height: 100%;
}
.parts {
display: flex;
}
.none {
color: rgba(0, 0, 0, 0.6);
display: block;
font-size: 12px;
font-weight: 400;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 16px;
margin: 8px 0 0;
}
.legend i {
display: inline-block;
height: 10px;
margin-right: 6px;
width: 10px;
}
.mark {
background: #333;
height: 12px;
position: absolute;
top: -2px;
width: 2px;
}
`,
}) })
export class Readings { export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly hideTitle = input(false);
/** smaller type, for cards of tables with many columns */
readonly compact = input(false);
readonly headline = input(''); readonly headline = input('');
/** the headline said under the figure instead */
readonly foot = input('');
readonly note = input(''); readonly note = input('');
/** a line under the figure */
readonly foot = input('');
/** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false);
readonly camaStyle = input(false);
readonly modes = input.required<Mode[]>(); readonly modes = input.required<Mode[]>();
/** The label of the mode a section's selector chose, for the cards that follow it. */
readonly view = input<string>(); readonly view = input<string>();
readonly loading = input(false); readonly loading = input(false);
readonly read = input.required<Read>(); /** A measure's reading in the applied period, and the figure of a mode that has one. */
readonly read = input.required<(measure: string) => Reading | undefined>();
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal(''); protected readonly chosen = signal('');
protected readonly mode = computed(() => { protected readonly countUnit = computed(() => {
const label = this.view() ?? this.chosen(); const mode = this.mode();
return this.modes().find((m) => m.label === label) ?? this.modes()[0]; const unit = mode.kind === 'grouped' ? mode.unit : 'pacientes';
return unit[0].toUpperCase() + unit.slice(1);
}); });
protected readonly missing = computed(() => unavailable(this.mode(), this.read())); protected readonly mode = computed(
protected readonly groups = computed(() => grouped(this.mode(), this.read())); () => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
protected readonly table = computed(
() =>
outcomes(this.mode(), this.read()) ??
shares(this.mode(), this.read()) ??
bars(this.mode(), this.read()),
); );
/** "Pacientes", "Reportes": what a group's records are called, capitalised. */ protected readonly groups = computed(() => grouped(this.mode(), this.read()));
protected readonly unit = computed(() => { protected readonly table = computed(() => bars(this.mode(), this.read()));
/** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => {
const m = this.mode(); const m = this.mode();
const unit = m.kind === 'grouped' ? m.unit : ''; if (m.kind !== 'figure' || m.figure !== 'scenarios') return 300;
return unit.charAt(0).toUpperCase() + unit.slice(1); const groups = (this.figure()?.data[0] as { y?: unknown[] } | undefined)?.y?.length ?? 3;
return Math.max(360, 190 + 44 * groups); // a slim bar per group, and room for legend and axis
}); });
/** What the card says about the categories it does not draw. */
protected readonly hidden = computed(() => hiddenNote(this.mode(), this.read()));
/** Patients in the period but no classification published: say it, do not draw nothing. */
protected readonly missing = computed(() => unavailable(this.mode(), this.read()));
protected readonly figure = computed(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
);
} }
+186
View File
@@ -0,0 +1,186 @@
import { Component, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading';
import { chained, DurationRow, durationMax } from './durations';
/** A screening route as one compact card: a bar per step with its median, its observations
* and its quartiles, read step by step or cumulatively from the sample. A step that is not
* published, or has no measurements in the period, keeps its row and says so. */
@Component({
selector: 'app-route-card',
imports: [Loading, MatButtonToggleModule, MatCardModule],
template: `
<mat-card appearance="outlined">
<mat-card-content>
<div class="head">
<h3>{{ title() }}</h3>
@if (sample().length && step().length) {
<mat-button-toggle-group
aria-label="Lectura de los tiempos"
[value]="mode()"
(change)="mode.set($event.value)"
>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (loading()) {
<app-loading what="los tiempos" [figure]="true" />
} @else {
@let rows = mode() === 'sample' ? sample() : chain(step());
@let max = scale(rows);
<p class="state">
@if (mode() === 'sample') {
Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se
calcula por separado.
} @else {
Esquema: cada barra es la mediana de su paso y empieza donde termina el paso del que
parte. Los pasos pueden corresponder a poblaciones diferentes, por lo que las
medianas no se suman.
}
Las marcas indican el primer y tercer cuartil.
@if (max) {
Escala: 0 a {{ max }} días.
}
</p>
<table [attr.aria-label]="title()">
<thead>
<tr>
<th>{{ mode() === 'sample' ? 'Etapa' : 'Paso' }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr [attr.data-status]="row.status">
<th scope="row">
{{ row.label }}
@if (row.status === 'value') {
<span class="track" aria-hidden="true">
<span
class="bar"
[style.margin-left.%]="max ? (100 * (row.start ?? 0)) / max : 0"
[style.width.%]="max ? (100 * row.median!) / max : 0"
></span>
@if (row.low !== undefined && row.high !== undefined) {
<span
class="mark"
[style.left.%]="max ? (100 * ((row.start ?? 0) + row.low)) / max : 0"
></span>
<span
class="mark"
[style.left.%]="max ? (100 * ((row.start ?? 0) + row.high)) / max : 0"
></span>
}
</span>
} @else {
<span class="none">
{{
row.status === 'empty'
? 'Sin mediciones en el periodo'
: 'Indicador no publicado'
}}
</span>
}
</th>
<td>{{ row.status === 'value' ? row.median + ' días' : '—' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{
row.low === undefined || row.high === undefined
? '—'
: row.low + '–' + row.high
}}
</td>
</tr>
}
</tbody>
</table>
}
</mat-card-content>
</mat-card>
`,
styles: `
:host {
display: block;
margin-top: 24px;
}
.head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
h3 {
font-size: 18px;
font-weight: 500;
margin: 0;
}
.state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
table {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
th {
font-weight: 500;
text-align: left;
}
th[scope='row'] {
padding: 5px 0;
}
td,
thead th:not(:first-child) {
font-variant-numeric: tabular-nums;
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
position: relative;
}
.bar {
background: #42a77e;
display: block;
height: 100%;
}
.mark {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.none {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
`,
})
export class RouteCard {
readonly title = input.required<string>();
/** The rows from the sample, and the rows step by step. */
readonly sample = input.required<DurationRow[]>();
readonly step = input.required<DurationRow[]>();
readonly loading = input(false);
protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax;
protected readonly chain = chained;
}
+93 -53
View File
@@ -1,9 +1,10 @@
import { NgTemplateOutlet } from '@angular/common'; import { Component, computed, input, signal } from '@angular/core';
import { Component, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import type { Measure } from 'fhir/r4'; import type { Measure } from 'fhir/r4';
import { detail, formatScore, Reading, scoring } from './measures'; import { Mode } from './bars';
import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { ReadingsCard, Section } from './pages'; import type { ReadingsCard, Section } from './pages';
import { Readings } from './readings'; import { Readings } from './readings';
@@ -15,29 +16,56 @@ export interface Source {
} }
type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>; type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
/** A card of readings, several side by side (optionally read through one selector), or one of /** A card of readings, several side by side, or one of several at a time. */
* several at a time (as sections, or as one card). */
@Component({ @Component({
selector: 'app-section', selector: 'app-section',
imports: [MatButtonToggleModule, MatCardModule, NgTemplateOutlet, Readings], imports: [MatButtonToggleModule, MatCardModule, Readings],
template: ` template: `
@let s = section(); @let s = section();
@if (s.kind === 'readings') { @if (s.kind === 'readings') {
<mat-card appearance="outlined"> <mat-card appearance="outlined">
<mat-card-content> <mat-card-content>
<ng-container *ngTemplateOutlet="card; context: { $implicit: s }" /> <app-readings
[title]="s.title"
[camaStyle]="hasCamaHeading(s)"
[headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''"
[modes]="s.modes"
[view]="view()"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} @else if (s.kind === 'choice' && s.card) { } @else if (s.kind === 'choice' && s.card) {
@let open = chosen() || s.choices[0].label; @let open = chosen() || s.choices[0].label;
<mat-card appearance="outlined"> <mat-card appearance="outlined" class="choice-card">
<mat-card-content> <mat-card-content>
<h3 class="title">{{ s.title }}</h3> <h3 class="title">{{ s.title }}</h3>
<ng-container *ngTemplateOutlet="toggle; context: { $implicit: s, open }" /> <mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) { @for (c of s.choices; track c.label) {
@if (c.label === open) { @if (c.label === open) {
<ng-container <app-readings
*ngTemplateOutlet="card; context: { $implicit: c.section, bare: true }" [title]="c.section.title"
[hideTitle]="true"
[camaStyle]="true"
[headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''"
[modes]="c.section.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/> />
} }
} }
@@ -46,11 +74,11 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
} @else { } @else {
<h2>{{ s.title }}</h2> <h2>{{ s.title }}</h2>
@if (s.kind === 'columns') { @if (s.kind === 'columns') {
@let view = picked() || s.views?.[0];
@if (s.views) { @if (s.views) {
<mat-button-toggle-group <mat-button-toggle-group
class="views"
[attr.aria-label]="s.viewsLabel ?? s.title" [attr.aria-label]="s.viewsLabel ?? s.title"
[value]="view" [value]="picked() || s.views[0]"
(change)="picked.set($event.value)" (change)="picked.set($event.value)"
> >
@for (v of s.views; track v) { @for (v of s.views; track v) {
@@ -60,12 +88,24 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
} }
<div class="columns"> <div class="columns">
@for (inner of s.sections; track $index) { @for (inner of s.sections; track $index) {
<app-section [section]="inner" [of]="of()" [view]="inner.follows ? view : undefined" /> <app-section
[section]="inner"
[of]="of()"
[view]="inner.follows ? picked() || s.views?.[0] : undefined"
/>
} }
</div> </div>
} @else { } @else {
@let open = chosen() || s.choices[0].label; @let open = chosen() || s.choices[0].label;
<ng-container *ngTemplateOutlet="toggle; context: { $implicit: s, open }" /> <mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) { @for (c of s.choices; track c.label) {
@if (c.label === open) { @if (c.label === open) {
<app-section [section]="c.section" [of]="of()" /> <app-section [section]="c.section" [of]="of()" />
@@ -73,32 +113,6 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
} }
} }
} }
<ng-template #toggle let-s let-open="open">
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
</ng-template>
<ng-template #card let-c let-bare="bare">
<app-readings
[title]="c.title"
[hideTitle]="!!bare"
[compact]="!!bare || compact(c)"
[headline]="c.footnote ? '' : headline(c)"
[foot]="c.footnote ? headline(c).replace(' · ', ', ').replace('. IC', ', IC') : ''"
[note]="c.note ?? ''"
[modes]="c.modes"
[view]="view()"
[loading]="of().loading"
[read]="of().reading"
/>
</ng-template>
`, `,
styles: ` styles: `
:host { :host {
@@ -106,14 +120,17 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
margin-top: 24px; margin-top: 24px;
min-width: 0; min-width: 0;
} }
.views {
flex-wrap: wrap;
margin: 4px 0 8px;
}
.title { .title {
font-size: 18px; font-size: 18px;
font-weight: 500; font-weight: 500;
margin: 0 0 8px; margin: 0 0 8px;
} }
mat-button-toggle-group { .choice-card app-readings {
flex-wrap: wrap; margin-top: 8px;
margin: 4px 0 8px;
} }
.columns { .columns {
display: grid; display: grid;
@@ -128,22 +145,45 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
export class ReadingsSection { export class ReadingsSection {
readonly section = input.required<Shown>(); readonly section = input.required<Shown>();
readonly of = input.required<Source>(); readonly of = input.required<Source>();
/** The mode a card following its section's selector takes (its label). */ /** The mode a card of a `columns` section takes from the section's selector (its label). */
readonly view = input<string>(); readonly view = input<string>();
/** The view a columns section's selector has chosen. */
protected readonly picked = signal(''); protected readonly picked = signal('');
protected readonly chosen = signal(''); protected readonly chosen = signal('');
/** A card whose modes say what their rows count reads in smaller type. */ protected hasCamaHeading(s: ReadingsCard): boolean {
protected compact(c: ReadingsCard): boolean { return s.modes.some((mode) => !!mode.heading);
return c.modes.some((m) => !!m.heading);
} }
/** A card's headline: its measure's score and its counts, in its own unit. */ /** A reading card's headline: its measure's score and its counts, in its own units. */
protected headline(c: ReadingsCard): string { protected headlineOf(s: ReadingsCard): string {
const measure = c.headline && this.of().measure(c.headline); const code = s.headline;
const r = c.headline && this.of().reading(c.headline); const measure = code && this.of().measure(code);
const r = code && this.of().reading(code);
if (!measure || !r) return ''; if (!measure || !r) return '';
const words = detail(measure, r, c.unit); const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
} }
/** The headline of a card that says it under its figure, as one line separated by commas. */
protected footOf(s: ReadingsCard): string {
return s.footnote
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
: '';
}
protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure);
const measure = this.of().measure(mode.measure);
if (!measure || !r?.populations['initial-population']) return undefined;
if (mode.figure === 'donut') return donut(measure, r, 'category', mode.colors);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(
r,
{ groups: [], categories },
mode.stratum ?? 'follow_up_status',
name,
mode.order,
{ fill: mode.complete, ofAll: mode.ofAll },
);
});
} }
+14 -43
View File
@@ -3,8 +3,7 @@ import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app'; import { DOMAINS } from '../app';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import { code, label } from '../fhir'; import { code, label } from '../fhir';
import { STRATA } from './labels'; import { periodTypes, STRATA } from './measures';
import { periodTypes } from './measures';
const SCORING: Record<string, string> = { const SCORING: Record<string, string> = {
proportion: 'Proporción', proportion: 'Proporción',
@@ -16,29 +15,6 @@ const IMPROVEMENT: Record<string, string> = {
decrease: 'Mejor si baja', decrease: 'Mejor si baja',
}; };
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' }; const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** Where the NCI reference risks come from. */
const NCI = [
[
'https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/',
'Egemen y colaboradores: estimaciones que sustentan las guías (2020).',
],
[
'https://doi.org/10.1097/LGT.0000000000000528',
'Cheung y colaboradores: métodos de estimación (2020).',
],
[
'https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/',
'Perkins y colaboradores: guías de manejo ASCCP 2019.',
],
[
'https://data.lhncbc.nlm.nih.gov/public/cervixca/AdditionalTables.zip',
'LHNCBC: libros de tablas adicionales.',
],
[
'https://web.archive.org/web/20240710095705/https://lhncbc.nlm.nih.gov/LHC-research/LHC-projects/image-processing/cervixca.html',
'LHNCBC: página archivada de las tablas, 10 de julio de 2024.',
],
].map(([url, citation]) => ({ url, citation }));
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each /** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
* indicator opening to what it is (how it scores, which way is better, its periods and * indicator opening to what it is (how it scores, which way is better, its periods and
@@ -58,19 +34,17 @@ const NCI = [
<h4>Riesgos de referencia NCI</h4> <h4>Riesgos de referencia NCI</h4>
<p> <p>
Los riesgos de referencia corresponden a la cohorte Kaiser Permanente Northern Los riesgos de referencia corresponden a la cohorte Kaiser Permanente Northern
California (2003–2017, pacientes de 25 a 65 años). Las guías ASCCP deciden la conducta California (2003–2017, pacientes de 25 a 65 años). Las guías ASCCP deciden la
con el riesgo de CIN3+. Los riesgos publicados de CIN2+ y cáncer son resultados conducta con el riesgo de CIN3+. Los riesgos publicados de CIN2+ y cáncer son
complementarios; no son directamente comparables con las estimaciones institucionales resultados complementarios; no son directamente comparables con las estimaciones
porque no están validados para la población de esta plataforma. institucionales porque no están validados para la población de esta plataforma.
</p> </p>
<ul> <ul>
@for (source of nci; track source.url) { <li><a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/" target="_blank" rel="noopener noreferrer">Egemen y colaboradores: estimaciones que sustentan las guías (2020).</a></li>
<li> <li><a href="https://doi.org/10.1097/LGT.0000000000000528" target="_blank" rel="noopener noreferrer">Cheung y colaboradores: métodos de estimación (2020).</a></li>
<a [href]="source.url" target="_blank" rel="noopener noreferrer">{{ <li><a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/" target="_blank" rel="noopener noreferrer">Perkins y colaboradores: guías de manejo ASCCP 2019.</a></li>
source.citation <li><a href="https://data.lhncbc.nlm.nih.gov/public/cervixca/AdditionalTables.zip" target="_blank" rel="noopener noreferrer">LHNCBC: libros de tablas adicionales.</a></li>
}}</a> <li><a href="https://web.archive.org/web/20240710095705/https://lhncbc.nlm.nih.gov/LHC-research/LHC-projects/image-processing/cervixca.html" target="_blank" rel="noopener noreferrer">LHNCBC: página archivada de las tablas, 10 de julio de 2024.</a></li>
</li>
}
</ul> </ul>
} }
@if (available().length) { @if (available().length) {
@@ -92,14 +66,12 @@ const NCI = [
@if (m.relatedArtifact?.length) { @if (m.relatedArtifact?.length) {
<h4>Referencias</h4> <h4>Referencias</h4>
<ul> <ul>
@for (source of m.relatedArtifact; track $index) { @for (reference of m.relatedArtifact; track $index) {
<li> <li>
@if (source.url) { @if (reference.url) {
<a [href]="source.url" target="_blank" rel="noopener noreferrer">{{ <a [href]="reference.url" target="_blank" rel="noopener noreferrer">{{ reference.citation || reference.display || reference.url }}</a>
source.citation || source.display || source.url
}}</a>
} @else { } @else {
{{ source.citation || source.display }} {{ reference.citation || reference.display }}
} }
</li> </li>
} }
@@ -173,7 +145,6 @@ const NCI = [
`, `,
}) })
export class TabDefiniciones { export class TabDefiniciones {
protected readonly nci = NCI;
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly scoring = SCORING; protected readonly scoring = SCORING;
+109 -48
View File
@@ -40,60 +40,94 @@
} }
@if (page(); as pg) { @if (page(); as pg) {
@if (applied(); as period) { @if (applied(); as period) {
@if (pg.clinicalFirst) { @if (domain() === 'cama') {
<ng-container *ngTemplateOutlet="clinicalView; context: { $implicit: pg, period: period }" /> <section class="card opportunity" aria-labelledby="opportunity-title">
} <div class="section-head">
<section class="card opportunity" aria-labelledby="opportunity-title"> <h2 id="opportunity-title">Indicadores de oportunidad</h2>
<div class="section-head"> <span class="period">Periodo {{ period }}</span>
<h2 id="opportunity-title">Indicadores de oportunidad</h2> </div>
<span class="period">Periodo {{ period }}</span> <div class="kpis" style="--kpi-cols-md: 3; --kpi-cols-lg: 3">
</div> @for (k of pg.kpis; track k.title) {
<div <ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
class="kpis" }
[style.--kpi-cols-md]="kpiColumns(pg.kpis.length)[0]" </div>
[style.--kpi-cols-lg]="kpiColumns(pg.kpis.length)[1]" @for (section of pg.opportunity ?? []; track $index) {
> <ng-container
@for (k of pg.kpis; track k.title) { *ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null"> />
<mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3>
@if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" />
} @else {
<div class="kpi-value" [class.pending]="!k.measure">
@let v = kpiParts(kpiValue(k));
{{ v[0] }}
@if (v[1]) {
<span class="kpi-qualifier">{{ v[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div>
}
</mat-card-content>
</mat-card>
} }
</div> </section>
@for (section of pg.opportunity ?? []; track $index) { <section class="card clinical-page" aria-labelledby="clinical-title">
<ng-container <h2 id="clinical-title">Indicadores clínicos</h2>
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }" @for (section of pg.clinical; track $index) {
/> <ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
} @else {
@if (domain() === 'cacu') {
<section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
} }
</section> <section class="card opportunity" aria-labelledby="opportunity-title">
<div class="section-head">
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span>
</div>
<div
class="kpis"
[style.--kpi-cols-md]="pg.kpis.length < 3 ? pg.kpis.length : 3"
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
>
@for (k of pg.kpis; track k.title) {
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
}
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
@if (!pg.clinicalFirst) { @if (domain() !== 'cacu') {
<ng-container *ngTemplateOutlet="clinicalView; context: { $implicit: pg, period: period }" /> <section class="card clinical-page" aria-labelledby="clinical-title">
<h2 id="clinical-title">Indicadores clínicos</h2>
@for (section of pg.clinical; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
}
} }
} }
<ng-template #clinicalView let-pg let-period="period"> <ng-template #kpiView let-k>
<section class="card clinical-page" aria-labelledby="clinical-title"> <mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<h2 id="clinical-title">Indicadores clínicos</h2> <mat-card-content>
@for (section of pg.clinical; track $index) { <h3 class="kpi-title">{{ k.title }}</h3>
<ng-container @if (reports.isLoading() && k.measure) {
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }" <app-loading [what]="k.title.toLowerCase()" />
/> } @else {
} <div class="kpi-value" [class.pending]="!k.measure">
</section> @let v = kpiParts(kpiValue(k));
{{ v[0] }}
@if (v[1]) {
<span class="kpi-qualifier">{{ v[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div>
}
</mat-card-content>
</mat-card>
</ng-template> </ng-template>
<ng-template #sectionView let-section let-period="period"> <ng-template #sectionView let-section let-period="period">
@@ -103,6 +137,14 @@
@case ('choice') { @case ('choice') {
<app-section [section]="section" [of]="of()" /> <app-section [section]="section" [of]="of()" />
} }
@case ('route') {
<app-route-card
[title]="section.title"
[sample]="stepRows(section, 'sample')"
[step]="stepRows(section, 'step')"
[loading]="reports.isLoading()"
/>
}
@case ('tea-summary') { @case ('tea-summary') {
@if (teaSummary(); as t) { @if (teaSummary(); as t) {
<mat-card appearance="outlined" class="summary"> <mat-card appearance="outlined" class="summary">
@@ -170,6 +212,10 @@
<div class="empty-figure">Sin datos publicados</div> <div class="empty-figure">Sin datos publicados</div>
} @else { } @else {
<p class="state">Filtro general aplicado: {{ period }}</p> <p class="state">Filtro general aplicado: {{ period }}</p>
@if (section.subtitles) {
<h2 class="box-subtitle">{{ measureTitle(b.measure) }}</h2>
<p class="state">Figura: Caja de cuartiles</p>
}
@if (reports.isLoading()) { @if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" /> <app-loading what="la figura" [figure]="true" />
} @else if (boxOf(b.measure); as fig) { } @else if (boxOf(b.measure); as fig) {
@@ -183,6 +229,21 @@
} }
</div> </div>
} }
@case ('card') {
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
<mat-card-content>
<h3 class="kpi-title">{{ section.title }}</h3>
<div class="kpi-value">
@let w = kpiParts(kpiValue(section));
{{ w[0] }}
@if (w[1]) {
<span class="kpi-qualifier">{{ w[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(section) }}</div>
</mat-card-content>
</mat-card>
}
@default { @default {
<mat-card appearance="outlined" class="figure-card"> <mat-card appearance="outlined" class="figure-card">
<mat-card-content> <mat-card-content>
+10
View File
@@ -221,6 +221,12 @@ h2.box-title {
margin: 0 0 4px; margin: 0 0 4px;
} }
h2.box-subtitle {
font-size: 16px;
font-weight: 500;
margin: 8px 0 0;
}
.empty-figure { .empty-figure {
align-items: center; align-items: center;
border: 1px solid var(--color-border); border: 1px solid var(--color-border);
@@ -240,6 +246,10 @@ h2.box-title {
font-weight: 500; font-weight: 500;
} }
.kpi.closing {
margin-top: 24px;
}
.summary { .summary {
margin-bottom: 24px; margin-bottom: 24px;
+22 -4
View File
@@ -8,6 +8,7 @@ import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4'; import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { DurationRow, durationRows } from './durations';
import { LAYOUTS } from './layout'; import { LAYOUTS } from './layout';
import { import {
ageShare, ageShare,
@@ -15,6 +16,8 @@ import {
boxFigure, boxFigure,
countBars, countBars,
fill, fill,
nestedDonut,
rateDots,
scenarioBars, scenarioBars,
shareDonut, shareDonut,
} from './figures'; } from './figures';
@@ -24,16 +27,18 @@ import {
donut, donut,
formatScore, formatScore,
medians, medians,
name,
periodLabel, periodLabel,
periods, periods,
PeriodType, PeriodType,
reading, reading,
Reading, Reading,
scoring, scoring,
STRATA,
strataBars, strataBars,
} from './measures'; } from './measures';
import { name, STRATA } from './labels';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { RouteCard } from './route-card';
import { ReadingsSection, Source } from './section'; import { ReadingsSection, Source } from './section';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per /** The period's indicators: the timeliness KPIs, the screening route, and a card per
@@ -50,6 +55,7 @@ import { ReadingsSection, Source } from './section';
MatSelectModule, MatSelectModule,
Plot, Plot,
ReadingsSection, ReadingsSection,
RouteCard,
], ],
templateUrl: './tab-indicadores.html', templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss', styleUrl: './tab-indicadores.scss',
@@ -191,6 +197,15 @@ export class TabIndicadores {
} }
protected readonly name = name; protected readonly name = name;
protected stepRows(section: Section, mode: 'sample' | 'step'): DurationRow[] {
if (section.kind !== 'route') return [];
return durationRows(
section[mode],
(code) => this.rd(code),
(code) => this.byName().has(code),
);
}
/** A measure's reading in the applied period, by code. */ /** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined { protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code); return this.loaded()?.get(code);
@@ -259,9 +274,8 @@ export class TabIndicadores {
unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'), unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'),
}; };
}); });
/** The cards' columns at medium and large widths: all in one row up to five, else in two. */ protected measureTitle(code: string | undefined): string {
protected kpiColumns(n: number): [number, number] { return (code && this.byName().get(code)?.title) || '';
return [Math.min(n, 3), n <= 5 ? n : Math.ceil(n / 2)];
} }
/** What a section of readings is drawn from. */ /** What a section of readings is drawn from. */
protected readonly of = computed<Source>(() => { protected readonly of = computed<Source>(() => {
@@ -276,6 +290,8 @@ export class TabIndicadores {
const r = this.rd(spec.measure); const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined; if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
switch (spec.kind) { switch (spec.kind) {
case 'donut':
return nestedDonut(r, spec.catalog, spec.center);
case 'share-donut': case 'share-donut':
return shareDonut(r, spec.catalog, spec.center); return shareDonut(r, spec.catalog, spec.center);
case 'counts': case 'counts':
@@ -286,6 +302,8 @@ export class TabIndicadores {
return ageShare(r, spec.names[0]); return ageShare(r, spec.names[0]);
case 'scenario-bars': case 'scenario-bars':
return scenarioBars(r, spec.catalog, spec.stratum, name); return scenarioBars(r, spec.catalog, spec.stratum, name);
case 'rates':
return rateDots(r, spec);
} }
} }
} }
+2 -2
View File
@@ -125,7 +125,7 @@
<th>Paciente</th> <th>Paciente</th>
<th>Grupo de edad</th> <th>Grupo de edad</th>
<th>Estado del caso</th> <th>Estado del caso</th>
<th>Paso</th> <th>Último EEG</th>
<th class="num">Puntaje M-CHAT</th> <th class="num">Puntaje M-CHAT</th>
<th class="num">CSS ADOS-2</th> <th class="num">CSS ADOS-2</th>
<th>Estatus de EEG</th> <th>Estatus de EEG</th>
@@ -141,7 +141,7 @@
</td> </td>
<td>{{ r.ageGroup ? ageLabel(r.ageGroup) : 'Sin dato' }}</td> <td>{{ r.ageGroup ? ageLabel(r.ageGroup) : 'Sin dato' }}</td>
<td>{{ cases[r.case] ?? r.case }}</td> <td>{{ cases[r.case] ?? r.case }}</td>
<td>{{ label(r.step) }}</td> <td>{{ r.lastEeg ?? '—' }}</td>
<td class="num">{{ r.mchat ?? '—' }}</td> <td class="num">{{ r.mchat ?? '—' }}</td>
<td class="num">{{ r.css ?? '—' }}</td> <td class="num">{{ r.css ?? '—' }}</td>
<td>{{ eegStatuses[r.eegStatus] ?? r.eegStatus }}</td> <td>{{ eegStatuses[r.eegStatus] ?? r.eegStatus }}</td>
+6 -8
View File
@@ -11,7 +11,7 @@ import type { Patient } from 'fhir/r4';
import { EXT, Fhir, resources } from '../fhir'; import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { ageLabel } from './figures'; import { ageLabel } from './figures';
import { name } from './labels'; import { name } from './measures';
import { matchesSearch, PatientSearch } from './patient-search'; import { matchesSearch, PatientSearch } from './patient-search';
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */ /** One child on TEA's list, as the list shows her (core.tea.follow_up). */
@@ -21,10 +21,9 @@ export interface TeaRow {
ageGroup: string; ageGroup: string;
case: string; case: string;
status: string; status: string;
/** the last step she reached by the cut-off (tea-step) */
step: string;
eegStatus: string; eegStatus: string;
alterations: string[]; alterations: string[];
lastEeg?: string;
mchat?: number; mchat?: number;
css?: number; css?: number;
} }
@@ -39,10 +38,10 @@ export function teaRow(p: Patient): TeaRow {
ageGroup: has(p, 'tea-age-group')[0]?.valueString ?? '', ageGroup: has(p, 'tea-age-group')[0]?.valueString ?? '',
case: coded('tea-case'), case: coded('tea-case'),
status: coded('follow-up-status'), status: coded('follow-up-status'),
step: coded('tea-step'), eegStatus: coded('tea-eeg-status'),
eegStatus: coded('tea-eeg-result'),
alterations: has(p, 'tea-eeg-alteration').map((e) => e.valueCoding?.code ?? ''), alterations: has(p, 'tea-eeg-alteration').map((e) => e.valueCoding?.code ?? ''),
mchat: has(p, 'mchat-score')[0]?.valueDecimal, lastEeg: has(p, 'tea-last-eeg')[0]?.valueDate,
mchat: has(p, 'mchat-score')[0]?.valueInteger,
css: has(p, 'ados2-css')[0]?.valueInteger, css: has(p, 'ados2-css')[0]?.valueInteger,
}; };
} }
@@ -63,14 +62,13 @@ const EEG_STATUS: Record<string, string> = {
normal: 'Normal', normal: 'Normal',
abnormal: 'Anormal', abnormal: 'Anormal',
no_valid_eeg: 'Sin EEG válido', no_valid_eeg: 'Sin EEG válido',
not_scored: 'Sin analizar',
}; };
const CASE: Record<string, string> = { const CASE: Record<string, string> = {
confirmed: 'Diagnóstico confirmado', confirmed: 'Diagnóstico confirmado',
in_process: 'En proceso', in_process: 'En proceso',
not_confirmed: 'Sin TEA', not_confirmed: 'Sin TEA',
}; };
/** An EEG metric outside its age curve (`spindles`), or with its side (`spindles:above`). */ /** `theta_power:above` → "theta_power (aumentado)". */
export const alteration = (a: string) => { export const alteration = (a: string) => {
const [metric, side] = a.split(':'); const [metric, side] = a.split(':');
const shown = (METRIC_NAMES[metric] ?? metric).replace(/ \(.*\)$/, ''); const shown = (METRIC_NAMES[metric] ?? metric).replace(/ \(.*\)$/, '');
+1 -1
View File
@@ -142,7 +142,7 @@
</td> </td>
<td> <td>
{{ row.age ?? 'No disponible' }} {{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup }}</small> <small>Grupo: {{ name(row.ageGroup) }}</small>
</td> </td>
<td>{{ name(row.status) }}</td> <td>{{ name(row.status) }}</td>
<td> <td>
+21 -17
View File
@@ -16,13 +16,13 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { saveExcel, savePdf } from '../export';
import { Stages } from '../paciente/stages'; import { Stages } from '../paciente/stages';
import { saveFollowUp } from './follow-up-export';
import { cytologyResult, followUpSheet } from './follow-up-sheet'; import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up'; import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search'; import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { name } from './labels'; import { name } from './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']; const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
@@ -140,24 +140,28 @@ export class TabRiesgos {
/** The whole list, not the page shown, as a file. */ /** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> { protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true); this.saving.set(true);
this.saveError.set(''); this.saveError.set('');
try { try {
const cutoff = this.applied(); await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) => {
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 }; const cutoffYear = Number(query.cutoff.slice(0, 4));
const pages = await this.fhir.all(this.domain(), 'Patient', asked); // bornFor encodes the minimum with le and the maximum with gt at one year earlier.
const start = windowStart(cutoff, this.window()); const lower = query.birthdates.find((value) => value.startsWith('le'));
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon())); const upper = query.birthdates.find((value) => value.startsWith('gt'));
const sheet = followUpSheet(all, [ const minimum = lower ? `${cutoffYear - Number(lower.slice(2, 6))}` : 'Sin límite';
['Ventana consultada', `${start} al ${cutoff}`], const maximum = upper ? `${cutoffYear - Number(upper.slice(2, 6)) - 1}` : 'Sin límite';
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'], const all = pages.flatMap((p) => rows(p, query.start, query.cutoff, query.horizon));
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`], return followUpSheet(all, [
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`], ['Ventana consultada', query.window],
['Búsqueda', this.search() || 'Ninguna'], ['Estatus de seguimiento', query.status],
['Horizonte de la probabilidad (años)', `${this.horizon()}`], ['Edad mínima', minimum],
]); ['Edad máxima', maximum],
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu'); ['Búsqueda', query.search],
else await savePdf([sheet], 'seguimiento-cacu', true); ['Horizonte de la probabilidad (años)', `${query.horizon}`],
]);
});
} catch { } catch {
this.saveError.set('No se generó el archivo.'); this.saveError.set('No se generó el archivo.');
} finally { } finally {
+19 -19
View File
@@ -35,7 +35,26 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form> </form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) { @if (error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
@@ -115,23 +134,4 @@
<button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()"> <button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()">
Siguiente Siguiente
</button> </button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</div> </div>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
+20 -22
View File
@@ -7,12 +7,12 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { saveExcel, savePdf } from '../export'; import { saveFollowUp } from './follow-up-export';
import { camaRows, windowStart } from './follow-up';
import { camaFollowUpSheet } from './follow-up-sheet'; import { camaFollowUpSheet } from './follow-up-sheet';
import { camaRows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search'; import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { name, PRIORITY } from './labels'; import { name, PRIORITY } from './measures';
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy']; const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
@@ -48,9 +48,9 @@ export class TabSeguimiento {
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
protected readonly name = name; protected readonly name = name;
protected readonly priority = (code: string) => PRIORITY[code] ?? code; protected readonly priority = (code: string) => PRIORITY[code] ?? code;
protected readonly saving = signal(false); protected readonly saving = signal(false);
protected readonly saveError = signal(''); protected readonly saveError = signal('');
/** The list as it is asked for, whatever the page. */ /** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({ private readonly query = computed(() => ({
'follow-up-window': this.window(), 'follow-up-window': this.window(),
@@ -60,7 +60,6 @@ export class TabSeguimiento {
_revinclude: ['DiagnosticReport:subject'], _revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result', '_include:iterate': 'DiagnosticReport:result',
})); }));
private readonly first = resource({ private readonly first = resource({
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }), params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
loader: ({ params: { domain, query, size } }) => { loader: ({ params: { domain, query, size } }) => {
@@ -94,25 +93,28 @@ export class TabSeguimiento {
protected readonly pageCount = computed(() => protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())), Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
); );
protected retry(): void {
this.first.reload();
}
/** The whole list, not the page shown, as a file. */ /** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> { protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true); this.saving.set(true);
this.saveError.set(''); this.saveError.set('');
try { try {
const cutoff = this.applied(); await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) =>
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 }; camaFollowUpSheet(
const pages = await this.fhir.all(this.domain(), 'Patient', asked); pages.flatMap((p) => camaRows(p, query.cutoff)),
const sheet = camaFollowUpSheet( [
pages.flatMap((p) => camaRows(p, cutoff)), ['Ventana consultada', query.window],
[ ['Estatus de seguimiento', query.status],
['Ventana consultada', `${windowStart(cutoff, this.window())} al ${cutoff}`], ['Búsqueda', query.search],
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'], ],
['Búsqueda', this.search() || 'Ninguna'], this.priority,
], ),
this.priority,
); );
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cama');
else await savePdf([sheet], 'seguimiento-cama', true);
} catch { } catch {
this.saveError.set('No se generó el archivo.'); this.saveError.set('No se generó el archivo.');
} finally { } finally {
@@ -120,10 +122,6 @@ export class TabSeguimiento {
} }
} }
protected retry(): void {
this.first.reload();
}
protected has(relation: 'next' | 'previous'): boolean { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
@@ -0,0 +1,51 @@
import { TestBed } from '@angular/core/testing';
import type { Measure } from 'fhir/r4';
import { Fhir } from '../fhir';
import { HISTORY } from './pages';
import { TabTrazabilidad } from './tab-trazabilidad';
describe('Trazabilidad: periodo seleccionado', () => {
for (const domain of ['cama', 'cacu']) {
it(`applies a monthly and semester period to the ${domain} queries`, async () => {
const requests: Record<string, string>[] = [];
await TestBed.configureTestingModule({
imports: [TabTrazabilidad],
providers: [
{
provide: Fhir,
useValue: {
all: async (_domain: string, _resource: string, params: Record<string, string>) => {
requests.push(params);
return [{ resourceType: 'Bundle', type: 'searchset', entry: [] }];
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(TabTrazabilidad);
fixture.componentRef.setInput('domain', domain);
fixture.componentRef.setInput('measures', [
{ resourceType: 'Measure', id: 'test', name: HISTORY[domain].panels[0].measure },
] as Measure[]);
fixture.detectChanges();
await fixture.whenStable();
const component = fixture.componentInstance as any;
component.chosen.set('2025-03');
fixture.detectChanges();
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2025-03');
expect(requests.at(-1)?.['as-of']).toBeUndefined();
component.setType('semester');
fixture.detectChanges();
await fixture.whenStable();
component.chosen.set('2024-S1');
fixture.detectChanges();
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2024-S1');
});
}
});
+11 -11
View File
@@ -7,8 +7,8 @@ import { Fhir, resources } from '../fhir';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { historyFigure } from './figures'; import { historyFigure } from './figures';
import { periodLabel, periods, periodStart, PeriodType, reading } from './measures'; import { historyPeriods, periodLabel, periods, PeriodType, reading } from './measures';
import { HISTORY, HistoryPanel } from './history'; import { HISTORY, HistoryPanel } from './pages';
interface Drawn { interface Drawn {
panel: HistoryPanel; panel: HistoryPanel;
@@ -33,7 +33,7 @@ interface Drawn {
<mat-button-toggle value="month">Mensual</mat-button-toggle> <mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle> <mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group> </mat-button-toggle-group>
@if (domain() !== 'tea') { @if (domain() === 'cama' || domain() === 'cacu') {
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodo seleccionado</mat-label> <mat-label>Periodo seleccionado</mat-label>
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)"> <mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
@@ -42,7 +42,7 @@ interface Drawn {
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<button mat-flat-button (click)="upTo.set(chosen())" [disabled]="chosen() === upTo()"> <button mat-flat-button (click)="applied.set(chosen())" [disabled]="chosen() === applied()">
Aplicar Aplicar
</button> </button>
} }
@@ -87,8 +87,8 @@ interface Drawn {
margin-bottom: 16px; margin-bottom: 16px;
} }
.filters { .filters {
align-items: center;
display: flex; display: flex;
align-items: center;
flex-wrap: wrap; flex-wrap: wrap;
gap: 16px; gap: 16px;
} }
@@ -117,14 +117,14 @@ export class TabTrazabilidad {
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('month'); protected readonly type = signal<PeriodType>('month');
protected readonly options = computed(() => periods(this.type())); protected readonly options = computed(() => periods(this.type()));
/** The period the history ends in (CaCu, CaMa): the chosen one, once applied. */
protected readonly chosen = signal(periods('month')[0]); protected readonly chosen = signal(periods('month')[0]);
protected readonly upTo = signal(periods('month')[0]); protected readonly applied = signal(periods('month')[0]);
protected setType(type: PeriodType): void { protected setType(type: PeriodType): void {
this.type.set(type); this.type.set(type);
this.chosen.set(this.options()[0]); const latest = this.options()[0];
this.upTo.set(this.options()[0]); this.chosen.set(latest);
this.applied.set(latest);
} }
protected readonly series = resource({ protected readonly series = resource({
@@ -132,12 +132,12 @@ export class TabTrazabilidad {
domain: this.domain(), domain: this.domain(),
type: this.type(), type: this.type(),
measures: this.measures(), measures: this.measures(),
upTo: this.upTo(), period: this.applied(),
}), }),
loader: async ({ params }) => { loader: async ({ params }) => {
const history = HISTORY[params.domain]; const history = HISTORY[params.domain];
if (!history) return []; if (!history) return [];
const asked = periods(params.type, 6, periodStart(params.upTo)).reverse(); const asked = historyPeriods(params.type, params.period);
return Promise.all( return Promise.all(
history.panels.map(async (panel) => { history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure); const measure = params.measures.find((m) => m.name === panel.measure);
-85
View File
@@ -1,85 +0,0 @@
import { Api } from '../api/api';
import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain';
import { scenarioFigure } from '../gobernanza/figures';
import type { ScenarioFactors } from './factores';
import type { Model } from './record';
import { combinationOf, noCurveText, sortUndrawn, survivalFigure } from './survival';
import { figureChoices } from './curve-chooser';
type Report = Record<string, any> | null | undefined;
const count = (n: number) => n.toLocaleString('es-MX');
/** A model version's report, by name. */
function report(api: Api, domain: string, model: Model, which: string): Promise<Report> {
return api.invoke(readReport$Json, {
domain: domain as Domain,
name: model.model.split('.')[1],
version: model.version,
report: which,
}) as Promise<Report>;
}
/** The names of the methods the figures draw, each once. */
const methods = (figures: { figure: { data: { name?: string }[] } }[]) =>
[
...new Set(figures.flatMap((f) => f.figure.data.map((t) => t.name)).filter((n) => !!n)),
] as string[];
/** "Análisis de supervivencia" or "de recurrencia": the curves of her clinical scenarios from the
* report of the model version that scored her, and the risk factors of those scenarios. CaCu says
* apart a scenario the report lists as short of deaths from one it does not mention. */
export async function analysis(api: Api, domain: string, m: Model) {
const mine = (all: any[] = []) => all.filter((e) => m.scenarios.includes(e.escenario));
if (m.model.endsWith('.recurrence')) {
const r = (await report(api, domain, m, 'interpretability'))?.['recurrencia'] ?? {};
const technical = await report(api, domain, m, 'technical_validation');
const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen'];
const figures = mine(r['escenarios']).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${count(e.n)}, recaídas = ${count(e.recaidas)})`,
e,
r['horizons_months'],
'Supervivencia libre de recaída',
),
);
const none = { unavailable: [], insufficient: [], missing: [], methods: [] };
return {
...none,
factors: mine(summary?.['filas']) as ScenarioFactors[],
scenarios: m.scenarios,
figures,
};
}
const found = await report(api, domain, m, 'interpretability');
const drawn = mine(found?.['escenarios']);
const figures = drawn.map((e) =>
scenarioFigure(
`${e.escenario} (n = ${count(e.n)}, fallecidos = ${count(e.fallecidos)})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
);
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
const cacu = domain === 'cacu';
return {
factors: mine(found?.['factores_escenarios']) as ScenarioFactors[],
scenarios: m.scenarios,
figures,
unavailable: cacu ? [] : undrawn,
...(cacu ? sortUndrawn(found, undrawn) : { insufficient: [], missing: [] }),
methods: methods(figures),
};
}
export type Analysis = Awaited<ReturnType<typeof analysis>>;
/** CaCu: the Kaplan-Meier of the patients who share all her values, from the survival report of
* the version that scored her; or why there is none. */
export async function combination(api: Api, m: Model & { inputs: Record<string, unknown> }) {
const found = await report(api, 'cacu', m, 'interpretability');
const mine = combinationOf(found, m.inputs);
return mine?.km
? { n: mine.n, deaths: mine.fallecidos, curves: figureChoices(survivalFigure(mine)) }
: { missing: noCurveText(found, mine) };
}
-62
View File
@@ -1,62 +0,0 @@
import { Component, input } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { ANTECEDENTS } from './record-groups';
/** CaCu: what each cytology's form declares of her (the one she was opened at first), by day.
* Statements of the form, not confirmed diagnoses. */
@Component({
selector: 'app-antecedents',
imports: [MatCardModule],
template: `
<mat-card appearance="outlined" data-section="antecedentes">
<mat-card-header>
<mat-card-title>Antecedentes y evaluación ginecológica</mat-card-title>
</mat-card-header>
<mat-card-content>
<p class="muted note">
Datos declarados en el formulario de la citología: no son diagnósticos confirmados. Cada
dato pertenece al formulario de la toma que se indica.
</p>
<h3>Citología cervical · toma {{ forms()[0].date }}</h3>
<dl class="facts">
@for (a of antecedents; track a.field) {
<div>
<dt>{{ a.title }}</dt>
<dd>{{ forms()[0].values[a.field] ?? 'No documentado' }}</dd>
</div>
}
</dl>
@if (forms().length > 1) {
<details class="findings">
<summary>Formularios anteriores ({{ forms().length - 1 }})</summary>
<table class="plain">
<thead>
<tr>
<th>Toma</th>
@for (a of antecedents; track a.field) {
<th>{{ a.title }}</th>
}
</tr>
</thead>
<tbody>
@for (o of forms().slice(1); track o.date) {
<tr>
<td class="nowrap">{{ o.date }}</td>
@for (a of antecedents; track a.field) {
<td>{{ o.values[a.field] ?? 'No documentado' }}</td>
}
</tr>
}
</tbody>
</table>
</details>
}
</mat-card-content>
</mat-card>
`,
styleUrl: './paciente.scss',
})
export class Antecedents {
readonly forms = input.required<{ date: string; values: Record<string, string> }[]>();
protected readonly antecedents = ANTECEDENTS;
}
@@ -0,0 +1,57 @@
import { camaRecordSheets } from './cama-record-sheets';
const sheets = (over: Partial<Parameters<typeof camaRecordSheets>> = []) =>
camaRecordSheets(
(over[0] as any) ?? [['Nombre', 'Ana'], ['CURP', undefined]],
(over[1] as any) ?? [['Categoría BI-RADS de la última mastografía', '4B'], ['Resultado histopatológico', undefined]],
(over[2] as any) ?? [{ date: '2025-01-02', kind: 'Procedimiento', text: 'Mastectomía' }],
(over[3] as any) ?? [{ date: '2025-01-01', kind: 'Mastografía', reported: undefined, results: ['BI-RADS: 4B'], findings: [] }],
(over[4] as any) ?? [],
(over[5] as any) ?? [],
);
const by = (s: ReturnType<typeof sheets>, title: string) => s.find((x) => x.title.startsWith(title))!;
// Each test fails if the PDF made up a value, kept a section of CaCu or dropped what CaMa publishes.
describe('the CaMa record as a PDF', () => {
it('has only CaMa sections and says a missing value as such', () => {
const s = sheets();
expect(s.map((x) => x.title)).toEqual([
'Datos de la paciente',
'Última mastografía y resultado histopatológico',
'Historial médico',
'Pruebas y resultados',
'Riesgos y recomendaciones publicados',
]);
expect(s.some((x) => /citolog|VPH|NCI|ASCCP|Etapas/i.test(x.title + x.head.join()))).toBe(false);
expect(by(s, 'Datos').rows).toEqual([['Nombre', 'Ana'], ['CURP', 'No disponible']]);
expect(by(s, 'Última').rows[1]).toEqual(['Resultado histopatológico', 'No disponible']);
expect(by(s, 'Pruebas').rows[0].slice(0, 3)).toEqual(['2025-01-01', 'Mastografía', 'Pendiente']);
});
it('without published estimates it says there are none, with no probability', () => {
expect(by(sheets(), 'Riesgos').rows).toEqual([
['Sin estimaciones publicadas', 'No disponible', 'No disponible', 'No disponible', 'No disponible'],
]);
});
it('publishes each estimate by horizon with its interval, and a zero is a value', () => {
const s = sheets([
undefined, undefined, undefined, undefined,
[{ text: 'Supervivencia v2', index: '2026-01-01', predictions: [{ years: 0, p: 0, low: 0, high: 0.01 }, { years: 5, p: 0.8 }] }],
] as any);
expect(by(s, 'Riesgos').rows).toEqual([
['Supervivencia v2', '2026-01-01', 'Al índice', '0.00 %', '0.00 % a 1.00 %'],
['Supervivencia v2', '2026-01-01', '5 años', '80.00 %', 'No disponible'],
]);
});
it('lists the scenario curves, the ones without a curve and the group nature of the estimates', () => {
const s = sheets([
undefined, undefined, undefined, undefined, [],
[{ title: 'Supervivencia', scenarios: ['A', 'B'], figures: ['A (n = 9, fallecidos = 6)'], undrawn: ['B'] }],
] as any);
const sheet = by(s, 'Supervivencia y recurrencia');
expect(sheet.title).toContain('no predicciones individuales');
expect(sheet.rows).toEqual([
['Supervivencia', 'A (n = 9, fallecidos = 6)', 'Curva publicada'],
['Supervivencia', 'B', 'No disponible: datos insuficientes'],
]);
});
});
+106
View File
@@ -0,0 +1,106 @@
import type { Sheet } from '../export';
const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
interface Event {
date: string;
kind: string;
text: string;
}
interface Test {
date: string;
kind: string;
reported?: string;
results: string[];
findings: string[];
}
/** A published estimate (risk, survival or recurrence) of one model, by horizon. */
interface Estimate {
text: string;
index: string;
predictions: { years: number; p: number; low?: number; high?: number }[];
}
/** The curves of a patient's clinical scenarios, as the page lists them. */
interface Analysis {
title: string;
scenarios: string[];
/** the figures' titles (scenario, members and events) */
figures: string[];
/** her scenarios the report draws no curve for */
undrawn: string[];
}
const horizon = (years: number) =>
years === 0 ? 'Al índice' : `${years} ${years === 1 ? 'año' : 'años'}`;
/** A CaMa patient's record as the tables of her PDF, in the page's order. Only what CaMa publishes:
* a value that is absent says so and no estimate is made up. */
export function camaRecordSheets(
facts: [string, string | undefined][],
studies: [string, string | undefined][],
history: Event[],
tests: Test[],
estimates: Estimate[],
analyses: Analysis[],
): Sheet[] {
const risks = estimates.flatMap((m) =>
m.predictions.map((p) => [
m.text,
m.index || NONE,
horizon(p.years),
percent(p.p),
p.low === undefined || p.high === undefined ? NONE : `${percent(p.low)} a ${percent(p.high)}`,
]),
);
const curves = analyses.flatMap((a) => [
...a.figures.map((f) => [a.title, f, 'Curva publicada']),
...a.undrawn.map((s) => [a.title, s, 'No disponible: datos insuficientes']),
...(a.figures.length || a.undrawn.length
? []
: [[a.title, a.scenarios.join('; ') || NONE, NONE]]),
]);
return [
{
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Última mastografía y resultado histopatológico',
head: ['Dato', 'Valor'],
rows: studies.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos'],
rows: tests.map((t) => [
t.date,
t.kind,
t.reported ?? 'Pendiente',
t.results.join(' · '),
t.findings.join(' · '),
]),
},
{
title: 'Riesgos y recomendaciones publicados',
head: ['Estimación', 'Fecha índice', 'Horizonte', 'Probabilidad', 'IC 95 %'],
rows: risks.length ? risks : [['Sin estimaciones publicadas', NONE, NONE, NONE, NONE]],
},
...(curves.length
? [
{
title:
'Supervivencia y recurrencia por escenario clínico (estimaciones del grupo, no predicciones individuales)',
head: ['Análisis', 'Escenario', 'Estado'],
rows: curves,
},
]
: []),
];
}
-99
View File
@@ -1,99 +0,0 @@
import type { DiagnosticReport, Patient } from 'fhir/r4';
import { code, ext, Fhir } from '../fhir';
import { ageGroup, CAMA_AGE_GROUPS, CamaRow, camaRows } from '../indicadores/follow-up';
import { name, PRIORITY } from '../indicadores/labels';
import { PatientRecord, results, shown } from './record';
interface Listed {
window: number;
/** the cut-off the list applied */
cutoff: string;
row?: CamaRow;
}
/** Her row on CaMa's follow-up list, at the window and cut-off she was opened from. */
export async function listedRow(
fhir: Fhir,
{ id, window, cutoff }: { id: string; window: number; cutoff?: string },
): Promise<Listed> {
const page = await fhir.search('cama', 'Patient', {
_id: id,
'follow-up-window': window,
'follow-up-cutoff': cutoff,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
const self = page.link?.find((l) => l.relation === 'self')?.url;
const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
return { window, cutoff: applied, row: camaRows(page, applied)[0] };
}
/** What the old record's card said of her: her row on the list (on it or not), her own latest
* mammogram and biopsy. */
export function camaSummary(d: PatientRecord, found: Listed) {
const latest = (study: string) =>
d.reports
.filter((r) => code(r.code) === study)
.sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''))
.at(-1);
const value = (r: DiagnosticReport | undefined, field: string) => {
const o = r && results(d, r).find((x) => code(x.code) === field);
return o ? shown(o) : undefined;
};
const mammogram = latest('mammography');
const biopsy = latest('breast_biopsy');
const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff);
const r = found.row;
return {
...found,
ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS),
scenario: treated ? 'Post-tratamiento' : 'En observación',
status: r ? name(r.status) : undefined,
priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined,
birads: value(mammogram, 'mammography.birads'),
mammogram: mammogram?.effectiveDateTime?.slice(0, 10),
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
histology: value(biopsy, 'breast_biopsy.histology'),
biopsy: biopsy
? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime)
: undefined,
};
}
type Summary = ReturnType<typeof camaSummary> | undefined;
type Facts = [string, string | undefined][];
const sex = (p?: Patient) =>
p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined;
/** Her data as the PDF lists them. */
export function camaFacts(
who: { name?: string; curp?: string; numbers: string[] },
p: Patient | undefined,
c: Summary,
): Facts {
return [
['Nombre', who.name],
['CURP', who.curp],
['Expedientes', who.numbers.join(', ')],
['Fecha de nacimiento', p?.birthDate],
['Sexo', sex(p)],
['Grupo de edad', c?.ageGroup],
['Escenario clínico', c?.scenario],
['Fecha de corte', c?.cutoff],
[
'Estatus de seguimiento',
c && (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`),
],
['Prioridad', c?.priority],
['Días de mastografía a diagnóstico', c?.days?.toString()],
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as Facts) : []),
];
}
/** Her latest mammogram and biopsy as the PDF lists them. */
export const camaStudies = (c: Summary): Facts => [
['Categoría BI-RADS de la última mastografía', c?.birads],
['Fecha de la última mastografía', c?.mammogram],
['Resultado histopatológico', c?.histology],
['Fecha de reporte de la biopsia', c?.biopsy],
];
+10
View File
@@ -0,0 +1,10 @@
import { figureChoices } from './curve-chooser';
describe('figureChoices', () => {
it('keeps each band with its line, one choice per curve', () => {
const data = [{ showlegend: false }, { name: 'Kaplan-Meier' }, { name: 'Weibull' }];
const { choices, draw } = figureChoices({ data: data as never });
expect(choices.map((c) => c.name)).toEqual(['Kaplan-Meier', 'Weibull']);
expect(draw(new Set(['Kaplan-Meier'])).data.length).toBe(2);
});
});
+17 -15
View File
@@ -5,13 +5,12 @@ import { Figure, Plot } from '../plot';
export interface Choice { export interface Choice {
id: string; id: string;
name: string; name: string;
/** drawn until the user says otherwise */ /** drawn before the user touches it */
on: boolean; on: boolean;
} }
export type Draw = (ids: Set<string>) => Figure;
/** A figure's named curves as choices, all on; a trace with no legend of its own (a band) goes /** A figure's curves as choices, all on: a band has no name of its own and goes with the line
* with the named one after it. */ * after it. */
export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw } { export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw } {
const groups = new Map<string, Figure['data']>(); const groups = new Map<string, Figure['data']>();
let pending: Figure['data'] = []; let pending: Figure['data'] = [];
@@ -29,20 +28,22 @@ export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw }
}; };
} }
/** Curves to compare on one plot, each chosen or not, with what the chosen ones assume. */ export type Draw = (ids: Set<string>) => Figure;
/** Curves chosen or not, to compare them on one plot: the record's risk and survival curves. */
@Component({ @Component({
selector: 'app-curve-chooser', selector: 'app-curve-chooser',
imports: [MatCheckboxModule, Plot], imports: [MatCheckboxModule, Plot],
template: ` template: `
<div class="choices"> <div class="choices">
@for (c of choices(); track c.id) { @for (c of choices(); track c.id) {
<mat-checkbox [checked]="chosen().has(c.id)" (change)="toggle(c.id)">{{ <mat-checkbox [checked]="chosen().has(c.id)" (change)="toggle(c.id)">
c.name {{ c.name }}
}}</mat-checkbox> </mat-checkbox>
} }
</div> </div>
@if (chosen().size) { @if (chosen().size) {
@for (note of said(); track note) { @for (note of notes()(chosen()); track note) {
<p class="muted">{{ note }}</p> <p class="muted">{{ note }}</p>
} }
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" /> <app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
@@ -63,22 +64,23 @@ export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw }
export class CurveChooser { export class CurveChooser {
readonly choices = input.required<Choice[]>(); readonly choices = input.required<Choice[]>();
readonly draw = input.required<Draw>(); readonly draw = input.required<Draw>();
/** what the chosen curves assume, said under the choices */
readonly notes = input<(ids: Set<string>) => string[]>(() => []); readonly notes = input<(ids: Set<string>) => string[]>(() => []);
/** the choices the user turned from their default */ /** what the user toggled away from its default */
private readonly flipped = signal(new Set<string>()); private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed( protected readonly chosen = computed(
() => () =>
new Set( new Set(
this.choices() this.choices()
.filter((c) => c.on !== this.flipped().has(c.id)) .filter((c) => c.on !== this.toggled().has(c.id))
.map((c) => c.id), .map((c) => c.id),
), ),
); );
protected readonly figure = computed(() => this.draw()(this.chosen())); protected readonly figure = computed(() => this.draw()(this.chosen()));
protected readonly said = computed(() => this.notes()(this.chosen()));
protected toggle(id: string) { protected toggle(id: string) {
const next = new Set(this.flipped()); const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id); if (!next.delete(id)) next.add(id);
this.flipped.set(next); this.toggled.set(next);
} }
} }
+116 -59
View File
@@ -1,73 +1,130 @@
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters } from 'fhir/r4';
import { currency, eligibilityFailure, eligibilityView, ineligibility } from './eligibility'; import { eligibilityFailure, eligibilityView } from './eligibility';
const visit = (scenario: string, day: string, eligible: boolean, ...criteria: string[]) => ({ const part = (name: string, extra: object) => ({ name, ...extra }) as any;
name: 'candidate', const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
part: [ const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
{ name: 'scenario', valueCoding: { code: scenario } }, const candidate = (
{ name: 'index-date', valueDate: day }, scenario: string,
{ name: 'eligible', valueBoolean: eligible }, date: string,
...criteria.map((code) => ({ name: 'criterion', valueCoding: { code } })), eligible: boolean,
], criteria: string[] = [],
}); sample?: string,
const answer = (...candidates: ParametersParameter[]): Parameters => ({ display?: string,
resourceType: 'Parameters', ) =>
parameter: [{ name: 'status', valueCode: 'evaluated' }, ...candidates], 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;
describe('eligibility', () => { // Each test fails if the section merged visits, dropped a reason or read silence as eligibility.
it('keeps each visit with its own decision, latest first, its reasons as the screens say them', () => { describe('the eligibility answer as the section shows it', () => {
const state = eligibilityView( it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => {
const view = eligibilityView(
answer( answer(
visit('pre_colposcopy', '2025-01-10', true), 'evaluated',
visit('pre_colposcopy', '2026-02-01', false, 'hysterectomy', 'brand_new'), 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'),
), ),
); );
expect(state).toEqual({ if (view.kind !== 'evaluated') throw new Error(view.kind);
kind: 'evaluated', expect(view.cutoff).toBe('2026-12-02');
visits: [ expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([
{ ['post_colposcopy', 'Postcolposcopia', 2],
scenario: 'pre_colposcopy', ['surveillance', 'Vigilancia', 2],
indexDate: '2026-02-01', ]);
eligible: false, const post = view.groups[0].visits; // newest visit first
reasons: ['Histerectomía previa al índice', 'brand_new'], expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([
}, ['2022-02-02', true, []],
{ scenario: 'pre_colposcopy', indexDate: '2025-01-10', eligible: true, reasons: [] }, ['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('never reads a malformed answer, or a failure, as a decision', () => { it('without candidates it says so, which is not eligibility', () => {
expect(eligibilityView(answer({ name: 'candidate', part: [] })).kind).toBe('unavailable'); expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' });
expect(
eligibilityView({
resourceType: 'Parameters',
parameter: [{ name: 'status', valueCode: 'no_candidate' }],
}).kind,
).toBe('none');
const failed = (status: number) => eligibilityFailure(new HttpErrorResponse({ status }));
expect([409, 404, 500].map((s) => failed(s).kind)).toEqual(['gold', 'unavailable', 'error']);
}); });
it('says why she has no estimate from the latest visit of her scenario by the day', () => { it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => {
const state = eligibilityView( 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( answer(
visit('surveillance', '2025-03-01', false, 'under_18'), 'evaluated',
visit('pre_colposcopy', '2026-05-01', true), candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'),
candidate('other_scenario', '2025-01-02', false, ['another_rule']),
), ),
); );
expect(ineligibility(state, 'pre_colposcopy', '2026-06-01')).toBeUndefined(); if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(ineligibility(state, 'pre_colposcopy', '2026-01-01')).toBe( expect(view.groups.map((g) => [g.code, g.text])).toEqual([
'No disponible por: Edad menor de 18 años al índice.', ['new_scenario', 'Escenario nuevo'],
); ['other_scenario', 'other_scenario'],
expect(ineligibility(state, 'post_treatment', '2026-06-01')).toBe( ]);
'No disponible por: paciente ya tratada.', expect(view.groups[1].visits[0].reasons).toEqual([
); { code: 'another_rule', text: 'another_rule' },
}); ]);
it('says the cytology the estimate speaks of, and a later one it does not', () => { });
const risk = [{ model: 'cacu.cin2_pre_colposcopy', index: '2026-01-10T00:00:00' }]; });
expect(currency(risk, ['2026-01-10']).note).toBe('Estimación de la citología del 2026-01-10.');
expect(currency(risk, ['2026-03-01']).note).toContain('posterior, del 2026-03-01'); describe('what a failed call is', () => {
const post = [{ model: 'cacu.cin2_post_colposcopy', index: '2026-01-10' }]; const failure = (status: number, error: unknown = null) =>
expect(currency(post, ['2026-03-01']).excluded).toContain('primera visita poscolposcopía'); 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' });
}); });
}); });
+223 -83
View File
@@ -1,8 +1,19 @@
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { Component, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The exclusion criteria `$eligibility` names, as the screens say them. */ /** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */
const CRITERIA: Record<string, string> = { 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', hysterectomy: 'Histerectomía previa al índice',
under_18: 'Edad menor de 18 años al índice', under_18: 'Edad menor de 18 años al índice',
prior_outcome: 'Resultado CIN2+ previo al índice', prior_outcome: 'Resultado CIN2+ previo al índice',
@@ -21,94 +32,223 @@ const CRITERIA: Record<string, string> = {
not_evaluated: 'Escenario que la plataforma no evalúa por ahora', not_evaluated: 'Escenario que la plataforma no evalúa por ahora',
}; };
/** One indexed visit of a scenario: the backend's decision and its reasons, as they are. */ export interface Reason {
export interface Visit { /** the API's code, untouched */
scenario: string; code: string;
indexDate: string; text: string;
eligible: boolean;
reasons: string[];
} }
/** What `$eligibility` answered; "eligible" is never inferred, only read. */ 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 = export type EligibilityState =
| { kind: 'loading' | 'error' | 'unavailable' | 'none' } | { kind: 'loading' }
| { kind: 'error' }
| { kind: 'unavailable' }
| { kind: 'gold'; text?: string } | { kind: 'gold'; text?: string }
| { kind: 'evaluated'; visits: Visit[] }; | { kind: 'none'; cutoff?: string }
| { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] };
type Part = ParametersParameter; type Part = ParametersParameter;
const parts = (of: Part[] | undefined, name: string) => (of ?? []).filter((p) => p.name === name); const value = (p?: Part): unknown =>
const first = (of: Part[] | undefined, name: string) => parts(of, name)[0]; 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's visits, latest first. An answer outside the contract is "unavailable". */ /** 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 { export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
const top = answer?.resourceType === 'Parameters' ? answer.parameter : undefined; const top = answer?.parameter;
if (!Array.isArray(top)) return { kind: 'unavailable' }; if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' };
const status = first(top, 'status')?.valueCode; const status = value(named(top, 'status')[0]);
const candidates = parts(top, 'candidate'); const cutoff = value(named(top, 'cutoff')[0]) as string | undefined;
if (status === 'no_candidate' && !candidates.length) return { kind: 'none' }; const candidates = named(top, 'candidate');
if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff };
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' }; if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
const visits: Visit[] = []; const groups = new Map<string, ScenarioGroup>();
for (const { part } of candidates) { for (const c of candidates) {
const scenario = first(part, 'scenario')?.valueCoding?.code; const scenario = coding(named(c.part, 'scenario')[0]);
const indexDate = first(part, 'index-date')?.valueDate; const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined;
const eligible = first(part, 'eligible')?.valueBoolean; const eligible = value(named(c.part, 'eligible')[0]);
if (!scenario || !indexDate || eligible === undefined) return { kind: 'unavailable' }; if (!scenario?.code || !indexDate || typeof eligible !== 'boolean')
const reasons = parts(part, 'criterion') return { kind: 'unavailable' };
.map((r) => r.valueCoding) const group = groups.get(scenario.code) ?? {
.filter((k) => !!k?.code) code: scenario.code,
.map((k) => CRITERIA[k!.code!] ?? k!.display ?? k!.code!); text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code,
visits.push({ scenario, indexDate, eligible, reasons }); visits: [],
}
return {
kind: 'evaluated',
visits: visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate)),
};
}
/** A failed answer: the gold to rebuild (409), no such operation for her (404, 422), or the call
* itself (anything else). */
export function eligibilityFailure(error: unknown): EligibilityState {
if (!(error instanceof HttpErrorResponse)) return { kind: 'error' };
if (error.status === 409) return { kind: 'gold', text: error.error?.issue?.[0]?.diagnostics };
return error.status === 404 || error.status === 422 ? { kind: 'unavailable' } : { kind: 'error' };
}
/** The scenarios that speak for a follow-up status, the first with a visit by the day wins. */
const SPEAKS_FOR: Record<string, string[]> = {
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
post_colposcopy: ['post_colposcopy'],
};
/** Why she has no risk estimate in her scenario by `day`; nothing when she is eligible or no visit
* of it is known. A treated patient has none, whatever was indexed. */
export function ineligibility(state: EligibilityState, status: string, day: string) {
if (status === 'post_treatment') return 'No disponible por: paciente ya tratada.';
if (state.kind !== 'evaluated') return undefined;
for (const scenario of SPEAKS_FOR[status] ?? []) {
const latest = state.visits.find((v) => v.scenario === scenario && v.indexDate <= day);
if (latest)
return latest.eligible ? undefined : `No disponible por: ${latest.reasons.join('; ')}.`;
}
return undefined;
}
/** Which cytology her estimates speak of, against her latest by the cut-off: after the first
* post-colposcopy visit nothing is evaluated; otherwise a later cytology is only said. */
export function currency(estimates: { model: string; index: string }[], cytologies: string[]) {
const sample = estimates
.map((e) => e.index.slice(0, 10))
.sort()
.at(-1);
if (!sample) return {};
const latest = cytologies
.map((d) => d.slice(0, 10))
.sort()
.at(-1);
const said = `Estimación de la citología del ${sample}.`;
if (!latest || latest <= sample) return { sample, note: said };
if (estimates.some((e) => e.model.includes('post_colposcopy')))
return {
sample,
excluded: `No disponible por: hay una citología posterior a la primera visita poscolposcopía (${latest}) y solo se evalúa esa primera visita.`,
}; };
return { sample, note: `${said} Hay una citología posterior, del ${latest}, que no se evalúa.` }; 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;
}
} }
+37
View File
@@ -0,0 +1,37 @@
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();
});
it('says of a treated patient only that she was already treated', () => {
const text = 'No disponible por: paciente ya tratada.';
expect(ineligibility(state, 'post_treatment', '2025-06-01')).toBe(text);
expect(ineligibility({ kind: 'error' }, 'post_treatment', '2025-06-01')).toBe(text);
});
});
+32
View File
@@ -0,0 +1,32 @@
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'],
};
/** 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 {
// a treated patient has no risk estimate, whatever visit was indexed
if (status === 'post_treatment') return 'No disponible por: paciente ya tratada.';
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;
}
+445 -38
View File
@@ -5,14 +5,21 @@
@if (error()) { @if (error()) {
<p class="muted" role="alert">No se encontró la paciente.</p> <p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) { } @else if (patient(); as p) {
<div class="head"> <div class="record-head">
<h1> <h1>
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code> {{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1> </h1>
@if (cama()) { @if (cama()) {
<ng-container *ngTemplateOutlet="export" /> <div class="head-actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
} }
</div> </div>
@if (cama() && saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<dl class="summary"> <dl class="summary">
<div> <div>
<dt>CURP</dt> <dt>CURP</dt>
@@ -116,8 +123,15 @@
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content> <mat-card-content>
@if (stages(); as s) { @if (stages(); as s) {
<ng-container *ngTemplateOutlet="export" /> <div class="export-actions">
<p class="muted note"> <button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<p class="muted route-note">
Los pasos muestran el tamizaje actual, en curso: el de la citología que se consulta. Los pasos muestran el tamizaje actual, en curso: el de la citología que se consulta.
</p> </p>
<div data-section="etapas"> <div data-section="etapas">
@@ -197,24 +211,321 @@
</mat-card> </mat-card>
@if (forms().length) { @if (forms().length) {
<app-antecedents class="wide" [forms]="forms()" /> <mat-card appearance="outlined" class="wide" data-section="antecedentes">
} <mat-card-header
@if (excluded() || groups().length || domain() !== 'cacu' || riskModels().length) { ><mat-card-title
<app-risk-card >Antecedentes y evaluación ginecológica</mat-card-title
class="wide" ></mat-card-header
[domain]="domain()" >
[id]="id()" <mat-card-content>
[cutoff]="corte()" <p class="muted route-note">
[sample]="currency().sample ?? citologia()" Datos declarados en el formulario de la citología: no son diagnósticos confirmados.
[models]="riskModels()" Cada dato pertenece al formulario de la toma que se indica.
[groups]="groups()" </p>
[excluded]="excluded()" @let f = forms()[0];
[note]="currency().note" <h3>Citología cervical · toma {{ f.date }}</h3>
/> <dl class="facts">
@for (a of antecedents; track a.field) {
<div>
<dt>{{ a.title }}</dt>
<dd>{{ f.values[a.field] ?? 'No documentado' }}</dd>
</div>
}
</dl>
@if (forms().length > 1) {
<details class="findings">
<summary>Formularios anteriores ({{ forms().length - 1 }})</summary>
<table class="plain">
<thead>
<tr>
<th>Toma</th>
@for (a of antecedents; track a.field) {
<th>{{ a.title }}</th>
}
</tr>
</thead>
<tbody>
@for (o of forms().slice(1); track o.date) {
<tr>
<td class="nowrap">{{ o.date }}</td>
@for (a of antecedents; track a.field) {
<td>{{ o.values[a.field] ?? 'No documentado' }}</td>
}
</tr>
}
</tbody>
</table>
</details>
}
</mat-card-content>
</mat-card>
} }
@if (excluded() || groups().length || domain() !== 'cacu' || riskModels().length) {
<mat-card appearance="outlined" class="wide" data-section="riesgos">
@if (excluded(); as reason) {
<mat-card-header>
<mat-card-title>Sin estimación de riesgo: criterio de exclusión</mat-card-title>
</mat-card-header>
}
<mat-card-content>
@if (excluded(); as reason) {
<p role="status" data-state="excluded">{{ reason }}</p>
} @else {
<app-risk-scales [groups]="groups()" />
@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>
</details>
}
@if (riskModels().length || hasCurves()) {
<details class="curves" open data-section="curvas">
<summary>Curvas de probabilidad con su intervalo</summary>
@if (hasCurves()) {
<app-risk-series [series]="riskSeries.value()!" />
} @else {
<app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
}
</details>
}
@if (!riskModels().length) {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
}
</mat-card-content>
</mat-card>
}
@if (domain() === 'tea') { @if (domain() === 'tea') {
<app-tea-record class="wide" [id]="id()" [observations]="observations()" /> <mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
<mat-card-content>
@if (ados2(); as a) {
<h3>Puntajes por reactivo · {{ a.date }}</h3>
<app-plot [figure]="a.figure" [height]="a.height" />
<p class="totals">
@for (t of a.totals; track t.label) {
<span
>{{ t.label }}: <strong>{{ t.value }}</strong></span
>
}
</p>
} @else {
<p class="muted">Sin evaluación ADOS-2.</p>
}
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" class="wide" data-section="eeg">
<mat-card-header><mat-card-title>EEG</mat-card-title></mat-card-header>
<mat-card-content>
@if (eeg.isLoading()) {
<app-loading what="el EEG" />
} @else if (eeg.value()?.study; as st) {
<h3>Calidad del EEG</h3>
<p>
Estudio del {{ st.study_date }}:
<strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong>
@if (st.level) {
({{ levelNames[st.level] ?? st.level }})
}
</p>
<h3>Alteraciones del EEG</h3>
@if (!st.valid) {
<p class="muted">EEG no aceptable: no se compara con la norma por edad.</p>
} @else if (!scored()) {
<p class="muted">Sin curva por edad en producción para este EEG.</p>
} @else if (alterations().length) {
<table class="plain">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>Norma por edad (P5–P95)</th>
<th>Mediana</th>
<th>Desviación (z)</th>
<th>Detalle</th>
</tr>
</thead>
<tbody>
@for (m of alterations(); track m.code) {
<tr [class.chosen]="zoned()?.code === m.code">
<td>
<button
mat-button
type="button"
class="metric"
[attr.aria-expanded]="zoned()?.code === m.code"
(click)="zone.set(zoned()?.code === m.code ? undefined : m.code)"
>
{{ metricNames[m.code] ?? m.code }}
</button>
</td>
<td>{{ m.value | number: '1.0-3' }}</td>
<td>{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}</td>
<td>{{ m.median | number: '1.0-3' }}</td>
<td>{{ m.z | number: '1.1-2' }}</td>
<td>{{ m.outside! > 0 ? 'Aumentado' : 'Disminuido' }}</td>
</tr>
}
</tbody>
</table>
<p class="muted">Elija una alteración para ver sus zonas más afectadas.</p>
@if (zoned(); as z) {
<section class="zones" aria-label="Zonas más afectadas">
<h3>Zonas más afectadas</h3>
<p class="muted">
{{ metricNames[z.code] ?? z.code }} ·
{{
zonesScored()
? 'desviación de cada zona frente a su norma por edad'
: 'valor de cada zona (sin norma por edad por zona)'
}}
</p>
@if (z.electrodes.length) {
<app-plot [figure]="head()" [height]="280" />
}
@if (z.zones.length) {
<ol class="regions" aria-label="Zonas ordenadas por desviación">
@for (r of zoneOrder(); track r.site) {
<li [class.marked]="(r.z ?? 0) >= 2 || (r.z ?? 0) <= -2">
<span>{{ zoneNames[r.site] ?? r.site }}</span>
<span>{{
r.z !== null && r.z !== undefined
? 'z = ' + (r.z | number: '1.1-2')
: (r.value | number: '1.0-3')
}}</span>
</li>
}
</ol>
} @else if (!z.electrodes.length) {
<p class="muted">Esta métrica no se mide por zona.</p>
}
</section>
}
} @else {
<p>Sin alteraciones: todas sus métricas están dentro de la norma por edad.</p>
}
@if (st.valid && scored()) {
<section
class="relation"
aria-label="Relación de las alteraciones del EEG con el ADOS-2"
>
<h3>Relación con el ADOS-2</h3>
@if (!eeg.value()?.analysis?.relation?.length) {
<p class="muted">Sin modelo de asociación en producción para este EEG.</p>
} @else if (!related().length) {
<p>
Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara
con el ADOS-2 en la cohorte.
</p>
} @else {
<p class="muted">
Modelo de asociación ajustado en la cohorte ({{ related()[0].n }} niños, por
edad y módulo del ADOS-2): qué tanto se asocia cada alteración del EEG por
zona con un aspecto del ADOS-2. No es un diagnóstico ni indica qué causa qué.
</p>
<table class="plain">
<thead>
<tr>
<th>Zona del EEG</th>
<th>Aspecto del ADOS-2</th>
<th>Asociación en la cohorte</th>
<th>Probabilidad para este paciente</th>
<th>Resultado en su ADOS-2</th>
</tr>
</thead>
<tbody>
@for (f of related(); track f.biomarker + f.zone + f.outcome_code) {
<tr>
<td>
<strong>{{ biomarkerNames[f.biomarker] ?? f.biomarker }}</strong>
<small
>{{ zoneNames[f.zone] ?? f.zone }} · z =
{{ f.z | number: '1.1-2' }}</small
>
</td>
<td>
{{ outcomeNames[f.outcome_code] ?? f.outcome_code }}
<small>{{ f.kind === 'item' ? 'Reactivo' : 'Dominio' }}</small>
</td>
<td>
OR {{ f.odds_ratio | number: '1.2-2' }}
<small
>IC 95 % {{ f.ci_low | number: '1.2-2' }}–{{
f.ci_high | number: '1.2-2'
}}
· q {{ qText(f.q) }}</small
>
<small>{{
f.odds_ratio >= 1
? 'A mayor z, mayor probabilidad'
: 'A menor z, mayor probabilidad'
}}</small>
</td>
<td>
<strong>{{ f.probability * 100 | number: '1.0-0' }} %</strong>
<small
>{{ f.event }} · con z = 0:
{{ f.reference_probability * 100 | number: '1.0-0' }} %</small
>
</td>
<td>
{{ observed(f) }}
@if (matches(f); as m) {
<small>{{ m }}</small>
}
</td>
</tr>
}
</tbody>
</table>
<p class="muted">
OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga
alterado; menor que 1, al revés. Solo se muestran las zonas alteradas del
paciente (|z| ≥ 2) con una asociación clara en la cohorte (q &lt; 0.05).
Versión del modelo: {{ related()[0].model }}.
</p>
}
</section>
}
} @else {
<p class="muted">Sin EEG analizado.</p>
}
</mat-card-content>
</mat-card>
} }
@if (recurrenceModel(); as rm) { @if (recurrenceModel(); as rm) {
@@ -264,28 +575,124 @@
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} }
@if (survivalModels().length) { @if (models().some((m) => m.model.endsWith('.survival'))) {
<app-survival-card <mat-card appearance="outlined" class="wide" data-section="supervivencia">
class="wide" <mat-card-header>
[domain]="domain()" <mat-card-title>{{
[models]="survivalModels()" domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
[analysis]="survival.value()" }}</mat-card-title>
[loading]="survival.isLoading()" </mat-card-header>
[failed]="!!survival.error()" <mat-card-content>
/> @if (domain() !== 'cacu') {
<h3>Análisis de supervivencia</h3>
}
@if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
@for (g of survivalScales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
v.risk!.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
</tbody>
</table>
</details>
}
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.curves) {
<p class="muted">
Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 %
Greenwood; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p>
<app-curve-chooser [choices]="c.curves.choices" [draw]="c.curves.draw" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<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" />
}
@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">No disponible: datos insuficientes.</p>
}
</mat-card-content>
</mat-card>
} }
</div> </div>
} @else if (loading()) { } @else if (loading()) {
<app-loading what="el expediente" /> <app-loading what="el expediente" />
} }
<ng-template #export>
<div class="actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
</ng-template>
</section> </section>
+74 -17
View File
@@ -54,6 +54,44 @@ mat-card-content {
} }
} }
.totals {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.zones {
margin-top: 12px;
}
.regions {
list-style: none;
margin: 8px 0 0;
padding: 0;
max-width: 420px;
li {
display: flex;
justify-content: space-between;
padding: 4px 8px;
border-bottom: 1px solid var(--mat-sys-outline-variant);
}
li.marked {
font-weight: 600;
color: var(--mat-sys-error);
}
}
tr.chosen td {
background: var(--mat-sys-surface-container);
}
.relation {
margin-top: 16px;
td small {
display: block;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
}
h1 .id { h1 .id {
font-size: 14px; font-size: 14px;
font-weight: 400; font-weight: 400;
@@ -61,30 +99,17 @@ h1 .id {
vertical-align: middle; vertical-align: middle;
} }
/* The name and, in CaMa, the record's export on one line; narrow screens put it under the name. */ .export-actions {
.head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
justify-content: space-between;
h1 {
min-width: 0;
overflow-wrap: anywhere;
}
.actions {
margin-bottom: 0;
}
}
.actions {
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
margin-bottom: var(--space-3); margin-bottom: var(--space-3);
} }
.note {
.route-note {
font-size: 12px; font-size: 12px;
margin: var(--space-2) 0 var(--space-3); margin: var(--space-2) 0 var(--space-3);
} }
.findings { .findings {
margin-top: 4px; margin-top: 4px;
summary { summary {
@@ -97,3 +122,35 @@ h1 .id {
padding-left: 18px; padding-left: 18px;
} }
} }
.curves {
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 12px;
padding: 8px 12px;
summary {
cursor: pointer;
font-weight: 500;
}
}
.curve-text {
margin: 8px 0;
padding-left: 18px;
}
/* The name and, in CaMa, the export of the record on the same line; narrow screens put the button under the name. */
.record-head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
justify-content: space-between;
}
.record-head h1 {
min-width: 0;
overflow-wrap: anywhere;
}
.head-actions {
flex: none;
}
+640 -190
View File
@@ -1,4 +1,4 @@
import { DecimalPipe, NgTemplateOutlet } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
@@ -8,51 +8,114 @@ import type {
Condition, Condition,
DiagnosticReport, DiagnosticReport,
Observation, Observation,
Parameters,
Patient, Patient,
Procedure, Procedure,
RiskAssessment, RiskAssessment,
} from 'fhir/r4'; } from 'fhir/r4';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility'; import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
import { code, ext, Fhir, resources } from '../fhir'; 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';
import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { savePdf } from '../export'; import { savePdf } from '../export';
import { ageAt, CURP } from '../indicadores/follow-up'; import { camaRecordSheets } from './cama-record-sheets';
import { name } from '../indicadores/labels'; import { recordSheets } from './record-sheets';
import { Loading } from '../loading'; import { HttpClient } from '@angular/common/http';
import { Plot } from '../plot'; import type { Parameters as FhirParameters } from 'fhir/r4';
import { analysis } from './analysis'; import { firstValueFrom } from 'rxjs';
import { Antecedents } from './antecedents'; import { ApiConfiguration } from '../api/api-configuration';
import { camaSummary, camaFacts, camaStudies, listedRow } from './cama-record'; import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
import { currency, eligibilityFailure, eligibilityView, ineligibility } from './eligibility'; import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
import { Factores } from './factores'; import { ineligibility } from './ineligibility';
import { forms, history, models, PatientRecord, tests } from './record'; import { parseSeries, RiskSeries, Series } from './risk-series';
import { camaRecordSheets, recordSheets } from './record-sheets'; import { curveFigure } from './risk-curve';
import { RiskCard } from './risk-card'; import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { riskGroups, riskScales, survivalGroups } from './risk-scales'; import { combinationOf, noCurveText, survivalFigure } from './survival-combination';
import { route, Stages } from './stages'; import { route, Stages } from './stages';
import { SurvivalCard } from './survival-card'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { TeaRecord } from './tea-record'; import { LABELS, name, PRIORITY } from '../indicadores/measures';
import {
BIOMARKER_NAMES,
byDeviation,
headMap,
METRIC_NAMES,
OUTCOME_NAMES,
ZONE_NAMES,
LEVEL_NAMES,
} from '../eeg-labels';
import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores';
import { CurveChooser, figureChoices } from './curve-chooser';
/** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string {
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
if (o.valueCodeableConcept) {
// The screens' own name for the code (BI-RADS 4C), else the server's display.
const c = code(o.valueCodeableConcept) ?? '';
return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept);
}
if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim();
return o.valueString ?? o.valueDateTime ?? '';
}
/** A report's Observations as facts of its study's form (record-groups). */
function facts(observations: Observation[]): Fact[] {
return observations.map((o) => ({
...split(code(o.code) ?? ''),
title: label(o.code),
value: shown(o),
}));
}
/** 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))];
}
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
/** One patient: her history, her tests and results, the form's antecedents, her risk with its
* curves and her survival, as the FHIR API publishes them. */
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [ imports: [
Antecedents,
DecimalPipe,
Factores, Factores,
CurveChooser,
Loading, Loading,
DecimalPipe,
MatButtonModule, MatButtonModule,
MatCardModule, MatCardModule,
MatIconModule, MatIconModule,
NgTemplateOutlet,
Plot,
RiskCard,
RouterLink, RouterLink,
Plot,
RiskScales,
RiskSeries,
Stages, Stages,
SurvivalCard,
TeaRecord,
], ],
templateUrl: './paciente.html', templateUrl: './paciente.html',
styleUrl: './paciente.scss', styleUrl: './paciente.scss',
@@ -60,6 +123,8 @@ import { TeaRecord } from './tea-record';
export class Paciente { export class Paciente {
private readonly fhir = inject(Fhir); private readonly fhir = inject(Fhir);
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly id = input.required<string>(); readonly id = input.required<string>();
/** The follow-up list she was opened from: its window (months) and cut-off. */ /** The follow-up list she was opened from: its window (months) and cut-off. */
@@ -70,164 +135,173 @@ export class Paciente {
private readonly data = resource({ private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }), params: () => ({ domain: this.domain(), id: this.id() }),
loader: async ({ params: { domain, id } }): Promise<PatientRecord> => { loader: async ({ params: { domain, id } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 }; const subject = { subject: `Patient/${id}`, _count: 200 };
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([ const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
this.fhir.read<Patient>(domain, 'Patient', id), this.fhir.read<Patient>(domain, 'Patient', id),
...['Condition', 'Procedure', 'DiagnosticReport', 'Observation', 'RiskAssessment'].map( this.fhir.all(domain, 'Condition', subject),
(type) => this.fhir.all(domain, type, subject), this.fhir.all(domain, 'Procedure', subject),
), this.fhir.all(domain, 'DiagnosticReport', subject),
this.fhir.all(domain, 'Observation', subject),
this.fhir.all(domain, 'RiskAssessment', subject),
]); ]);
return { return {
patient: patient as Patient, patient,
conditions: resources<Condition>(conditions as never, 'Condition'), conditions: resources<Condition>(conditions, 'Condition'),
procedures: resources<Procedure>(procedures as never, 'Procedure'), procedures: resources<Procedure>(procedures, 'Procedure'),
reports: resources<DiagnosticReport>(reports as never, 'DiagnosticReport').reverse(), reports: resources<DiagnosticReport>(reports, 'DiagnosticReport').reverse(),
observations: new Map( observations: new Map(
resources<Observation>(observations as never, 'Observation').map((o) => [o.id, o]), resources<Observation>(observations, 'Observation').map((o) => [o.id, o]),
), ),
risks: resources<RiskAssessment>(risks as never, 'RiskAssessment'), risks: resources<RiskAssessment>(risks, 'RiskAssessment'),
}; };
}, },
}); });
protected readonly patient = computed(() => this.data.value()?.patient); protected readonly patient = computed(() => this.data.value()?.patient);
protected readonly error = computed(() => this.data.error()); protected readonly error = computed(() => this.data.error());
protected readonly loading = computed(() => this.data.isLoading()); protected readonly loading = computed(() => this.data.isLoading());
protected readonly observations = computed(() => [ protected readonly history = computed(() => {
...(this.data.value()?.observations.values() ?? []), const d = this.data.value();
]); if (!d) return [];
protected readonly history = computed(() => return [
this.data.hasValue() ? history(this.data.value()) : [], ...d.conditions.map((c) => ({
); date: c.recordedDate ?? '',
protected readonly tests = computed(() => (this.data.hasValue() ? tests(this.data.value()) : [])); kind: 'Diagnóstico',
text: label(c.code),
// the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid)
code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code,
})),
...d.procedures.map((p) => ({
date: p.performedDateTime ?? '',
kind: 'Procedimiento',
text: label(p.code),
code: undefined,
})),
].sort((a, b) => b.date.localeCompare(a.date));
});
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv')); protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff())); protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
private readonly cacu = computed(() => this.domain() === 'cacu'); /** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
private readonly cytologies = computed(() => * hysterectomy of her record is still held against her when the backend does not report it,
(this.data.value()?.reports ?? []).filter((r) => code(r.code) === 'cervical_cytology'), * 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 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
? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined;
});
/** CaCu: why the backend withholds some of her estimates at the cut-off, if it does. */
protected readonly withheld = computed(() => {
const patient = this.patient();
return patient ? ext(patient, 'risk-withheld')?.valueString : undefined;
});
/** The one criterion she does not meet: nothing else of her risk is then shown. */
protected readonly excluded = computed(() => this.withheld() ?? this.riskExclusion());
/** Whether any published series has a point to draw. */
protected readonly hasCurves = computed(
() => this.riskSeries.value()?.some((s) => s.points.length > 0) ?? false,
); );
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */ /** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
protected readonly stages = computed(() => { protected readonly stages = computed(() => {
const opened = this.cytologies().find((r) => r.effectiveDateTime === this.citologia()); const cytologies = (this.data.value()?.reports ?? []).filter(
return this.cacu() ? route(opened ?? this.cytologies()[0], this.cutoff()) : undefined; (r) => code(r.code) === 'cervical_cytology',
);
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
}); });
/** CaCu: what each cytology's form declares, the one she was opened at first. */ /** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly forms = computed(() => protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
this.cacu() && this.data.hasValue() ? forms(this.data.value(), this.citologia()) : [], protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
); );
/** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
/** CaCu: the decisions `$eligibility` publishes for her indexed visits. */ * survival only there is nothing to draw here: its scales are in the survival section. */
private readonly eligibility = resource({ protected readonly groups = computed(() =>
params: () => (this.cacu() ? { id: this.id(), cutoff: this.corte() } : undefined), this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
loader: async ({ params }) => { ? riskGroups(this.riskModels())
: [],
);
protected readonly survivalScales = computed(() =>
this.domain() === 'cacu'
? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
: [],
);
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
* the model version that scored her. */
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
},
loader: async ({ params: { version, inputs } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: 'cacu' as Domain,
name: 'survival',
version,
report: 'interpretability',
});
const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km
? { n: found.n, fallecidos: found.fallecidos, curves: figureChoices(survivalFigure(found)) }
: { missing: noCurveText(report as Record<string, unknown>, found) };
},
});
/** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({
params: () =>
this.domain() === 'cacu'
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
: undefined,
loader: async ({ params }): Promise<Series[] | undefined> => {
try {
const answer = await firstValueFrom(
this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
{
params: Object.fromEntries(
Object.entries({
cutoff: params.cutoff,
sample: params.sample?.slice(0, 10),
}).filter((e): e is [string, string] => !!e[1]),
),
},
),
);
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 { try {
const answer = await this.api.invoke(cacuEligibility, { const answer = await this.api.invoke(cacuEligibility, {
domain: 'cacu', domain: 'cacu' as Domain,
...params, id: params.id,
} as never); cutoff: params.cutoff,
return eligibilityView(answer as Parameters); });
return eligibilityView(answer as FhirParameters);
} catch (error) { } catch (error) {
return eligibilityFailure(error); return eligibilityFailure(error);
} }
}, },
}); });
/** CaCu: why she has no risk estimate: the backend's reason, else a hysterectomy her record protected readonly eligibility = computed<EligibilityState>(() =>
* holds by the index (evidence loaded without the day it became available). */ this.eligibilityData.isLoading()
protected readonly riskExclusion = computed(() => { ? { kind: 'loading' }
const p = this.patient(); : (this.eligibilityData.value() ?? { kind: 'loading' }),
if (!this.cacu() || !p) return undefined;
const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const status = ext(p, 'follow-up-status')?.valueCoding?.code ?? '';
const state = this.eligibility.value() ?? { kind: 'loading' as const };
const recorded = ext(p, 'first-hysterectomy-recorded')?.valueDate;
return (
ineligibility(state, status, index) ??
(recorded && recorded <= index
? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined)
);
});
/** Each model's latest estimate of her; none when she is excluded. */
protected readonly models = computed(() =>
this.riskExclusion() ? [] : models(this.data.value()?.risks ?? []),
); );
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly survivalModels = computed(() =>
this.models().filter((m) => m.model.endsWith('.survival')),
);
/** CaCu: the cytology her estimates speak of, against her latest by the cut-off. */
protected readonly currency = computed(() =>
this.cacu()
? currency(
this.riskModels(),
this.cytologies()
.map((r) => r.effectiveDateTime ?? '')
.filter((d) => d && d.slice(0, 10) <= this.cutoff()),
)
: {},
);
/** The one reason nothing of her risk is shown: the backend withholding it, her exclusion, or a
* later cytology after her first post-colposcopy visit. */
protected readonly excluded = computed(
() =>
(this.patient() && ext(this.patient(), 'risk-withheld')?.valueString) ??
this.riskExclusion() ??
this.currency().excluded,
);
/** CaCu: both horizons of every risk model, or both unavailable (with survival only, nothing). */
protected readonly groups = computed(() =>
this.cacu() && (this.riskModels().length || !survivalGroups(this.survivalModels()).length)
? riskGroups(this.riskModels())
: [],
);
/** "Análisis de supervivencia" and "de recurrencia" of her clinical scenarios. */
protected readonly survival = this.analysis('survival');
protected readonly recurrence = this.analysis('recurrence');
protected readonly recurrenceModel = computed(() =>
this.models().find((m) => m.model.endsWith('.recurrence') && m.version),
);
private analysis(kind: 'survival' | 'recurrence') {
return resource({
params: () => {
const domain = this.domain();
const m = this.models().find((x) => x.model === `${domain}.${kind}` && x.scenarios.length);
return m?.version && !(kind === 'survival' && domain === 'cacu')
? { domain, m }
: undefined;
},
loader: ({ params: { domain, m } }) => analysis(this.api, domain, m),
});
}
protected readonly identity = computed(() => {
const p = this.patient();
return {
name: p?.name?.[0]?.text,
curp: p?.identifier?.find((i) => i.system === CURP)?.value,
// each record number once (several sources may carry the same one)
numbers: [
...new Set((p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value)),
].filter((n): n is string => !!n),
};
});
/** CaMa: her row on the follow-up list, as opened (else the widest window). */
private readonly listed = resource({
params: () =>
this.domain() === 'cama'
? { id: this.id(), window: Number(this.ventana()) || 12, cutoff: this.corte() || undefined }
: undefined,
loader: ({ params }) => listedRow(this.fhir, params),
});
protected readonly cama = computed(() => {
const found = this.listed.value();
return found && this.data.hasValue() ? camaSummary(this.data.value(), found) : undefined;
});
protected readonly status = computed(() => {
const p = this.patient();
return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : '';
});
protected readonly saving = signal(false); protected readonly saving = signal(false);
protected readonly saveError = signal(''); protected readonly saveError = signal('');
/** Her record as a PDF (CaCu's or CaMa's). */ /** Her record as a PDF (CaCu's or CaMa's). */
@@ -235,60 +309,436 @@ export class Paciente {
this.saving.set(true); this.saving.set(true);
this.saveError.set(''); this.saveError.set('');
try { try {
if (this.domain() === 'cama') await this.saveCama(); if (this.domain() === 'cama') {
else await this.saveCacu(); await this.saveCama();
return;
}
const { name: who, curp, numbers } = this.identity();
const facts: [string, string | undefined][] = [
['Nombre', who],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', this.patient()?.birthDate],
['Edad', this.age()?.toString()],
['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()],
];
if (this.riskExclusion()) facts.push(['Evaluación de probabilidad', this.riskExclusion()]);
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.forms(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
} catch { } catch {
this.saveError.set('No se generó el archivo.'); this.saveError.set('No se generó el archivo.');
} finally { } finally {
this.saving.set(false); this.saving.set(false);
} }
} }
private async saveCacu(): Promise<void> { /** CaMa: her record as a PDF, with what CaMa publishes of her. */
private async saveCama(): Promise<void> {
const c = this.cama();
const { name: who, curp, numbers } = this.identity(); const { name: who, curp, numbers } = this.identity();
const p = this.patient();
const facts: [string, string | undefined][] = [ const facts: [string, string | undefined][] = [
['Nombre', who], ['Nombre', who],
['CURP', curp], ['CURP', curp],
['Expedientes', numbers.join(', ')], ['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', this.patient()?.birthDate], ['Fecha de nacimiento', p?.birthDate],
['Edad', this.age()?.toString()], ['Sexo', p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined],
['Estatus de seguimiento', this.status()], ['Grupo de edad', c?.ageGroup],
['Fecha de corte', this.cutoff()], ['Escenario clínico', c?.scenario],
['Fecha de corte', c?.cutoff],
[
'Estatus de seguimiento',
c ? (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`) : undefined,
],
['Prioridad', c?.priority],
['Días de mastografía a diagnóstico', c?.days?.toString()],
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as [string, string][]) : []),
]; ];
if (this.riskExclusion()) facts.push(['Evaluación de probabilidad', this.riskExclusion()]); const studies: [string, string | undefined][] = [
const scales = riskScales(this.riskModels()); ['Categoría BI-RADS de la última mastografía', c?.birads],
const sheets = recordSheets( ['Fecha de la última mastografía', c?.mammogram],
facts, ['Resultado histopatológico', c?.histology],
this.stages() ?? [], ['Fecha de reporte de la biopsia', c?.biopsy],
this.history(), ];
this.tests(), const analysis = (title: string, r: typeof this.survival) => {
scales, // a report that failed to load is no analysis: its absence is said, the file is still made
this.forms(),
);
await savePdf(sheets, 'expediente-cacu');
}
private async saveCama(): Promise<void> {
// an analysis that failed to load is none: its absence is said, the file is still made
const read = (title: string, r: typeof this.survival) => {
const v = r.hasValue() ? r.value() : undefined; const v = r.hasValue() ? r.value() : undefined;
return v return v
? [ ? [{ title, scenarios: v.scenarios, figures: v.figures.map((f) => f.title), undrawn: v.unavailable }]
{
title,
scenarios: v.scenarios,
figures: v.figures.map((f) => f.title),
undrawn: v.unavailable,
},
]
: []; : [];
}; };
const sheets = camaRecordSheets( const sheets = camaRecordSheets(
camaFacts(this.identity(), this.patient(), this.cama()), facts,
camaStudies(this.cama()), studies,
this.history(), this.history(),
this.tests(), this.tests(),
this.models(), this.models(),
[...read('Supervivencia', this.survival), ...read('Recurrencia', this.recurrence)], [...analysis('Supervivencia', this.survival), ...analysis('Recurrencia', this.recurrence)],
); );
await savePdf(sheets, 'expediente-cama'); await savePdf(sheets, 'expediente-cama');
} }
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
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 { hpv, rest } = hpvApart(facts(results));
const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
status: r.status,
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
* opened at first, each with its day. They are statements of the form, not confirmed diagnoses. */
protected readonly forms = computed(() => {
const d = this.data.value();
if (!d || this.domain() !== 'cacu') return [];
const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology');
const first = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return [first, ...cytologies.filter((r) => r !== first)]
.filter((r) => !!r)
.map((r) => {
const found = group(
facts(
(r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[],
),
).antecedents;
return {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
values: found,
};
})
.filter((f) => ANTECEDENTS.some((a) => f.values[a.field]));
});
protected readonly antecedents = ANTECEDENTS;
/** One model's latest risk assessment per model. */
protected readonly models = computed(() => {
if (this.riskExclusion()) return [];
const latest = new Map<string, RiskAssessment>();
for (const r of this.data.value()?.risks ?? []) {
const key = code(r.method) ?? '';
if (
!latest.has(key) ||
(latest.get(key)!.occurrenceDateTime ?? '') < (r.occurrenceDateTime ?? '')
)
latest.set(key, r);
}
return [...latest.values()].map((r) => ({
model: code(r.method) ?? '',
text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '',
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico')
.map((e) => e.valueString ?? ''),
predictions: (r.prediction ?? []).map((p) => ({
years: p.whenRange?.high?.value ?? 0,
p: p.probabilityDecimal ?? 0,
low: ext(p, 'ic-bajo')?.valueDecimal,
high: ext(p, 'ic-alto')?.valueDecimal,
})),
}));
});
/** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical
* scenarios, from the report of the model version that scored her. */
protected readonly survival = this.analysis('survival');
protected readonly recurrence = this.analysis('recurrence');
protected readonly recurrenceModel = computed(() =>
this.models().find((m) => m.model.endsWith('.recurrence') && m.version),
);
private analysis(name: 'survival' | 'recurrence') {
return resource({
params: () => {
const m = this.models().find(
(x) => x.model === `${this.domain()}.${name}` && x.scenarios.length && x.version,
);
return m ? { m, domain: this.domain() } : undefined;
},
loader: async ({ params: { m, domain } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: domain as Domain,
name,
version: m.version,
report: 'interpretability',
});
const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
if (name === 'recurrence') {
const r = (report?.['recurrencia'] ?? {}) as any;
// The risk factors of her scenarios, by horizon (the development tables).
const technical = (await this.api.invoke(readReport$Json, {
domain: domain as Domain,
name,
version: m.version,
report: 'technical_validation',
})) as any;
const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen'];
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')})`,
e,
r['horizons_months'],
'Supervivencia libre de recaída',
),
),
};
}
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,
// her scenarios the report draws no curve for
unavailable: domain === 'cacu' ? [] : undrawn,
insufficient,
missing,
methods: methods(figures),
};
},
});
}
/** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's
* `ados2.*` fields), item by item, and its totals. */
protected readonly ados2 = computed(() => {
const d = this.data.value();
if (!d) return undefined;
const field = (o: Observation) => (code(o.code) ?? '').replace(/^ados2\./, '');
const scored = [...d.observations.values()].filter(
(o) => (code(o.code) ?? '').startsWith('ados2.') && o.valueQuantity?.value !== undefined,
);
const latest = scored
.map((o) => o.effectiveDateTime ?? '')
.sort()
.at(-1);
if (latest === undefined) return undefined;
const results = scored.filter((o) => (o.effectiveDateTime ?? '') === latest);
const totals = ['social_affect_total', 'restricted_repetitive_total', 'overall_total'];
const items = results.filter((o) => !totals.includes(field(o)));
const figure: Figure = {
data: [
{
type: 'bar',
orientation: 'h',
y: items.map((o) => label(o.code)),
x: items.map((o) => o.valueQuantity!.value!),
marker: { color: PALETTE[0] },
hovertemplate: '%{y}: %{x}<extra></extra>',
},
],
layout: {
showlegend: false,
margin: { t: 10, r: 16, b: 40, l: 16 },
xaxis: { title: { text: 'Puntaje (0 a 3)' }, range: [0, 3], dtick: 1 },
yaxis: { autorange: 'reversed', automargin: true, type: 'category' },
},
};
return {
date: latest.slice(0, 10),
figure,
height: 60 + items.length * 22,
totals: results
.filter((o) => totals.includes(field(o)))
.map((o) => ({ label: label(o.code), value: o.valueQuantity!.value! })),
};
});
/** TEA: her EEG as analysed (the latest), its quality and its metrics against the age
* curves: those outside the band are its alterations. */
protected readonly eeg = resource({
params: () => (this.domain() === 'tea' ? this.id() : undefined),
loader: async ({ params: person }) => {
const mine = (await this.api.invoke(eegStudies))
.filter((s) => s.person_id === person && s.analysed)
.sort((a, b) => b.study_date.localeCompare(a.study_date));
if (!mine.length) return { study: undefined, analysis: undefined };
return {
study: mine[0],
analysis: await this.api.invoke(eegStudy, { eeg_id: mine[0].id }),
};
},
});
protected readonly alterations = computed(() =>
(this.eeg.value()?.analysis?.metrics ?? []).filter((m) => m.outside),
);
protected readonly scored = computed(() =>
(this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined),
);
protected readonly shown = signal<string | undefined>(undefined);
protected readonly metricNames = METRIC_NAMES;
protected readonly zoneNames = ZONE_NAMES;
/** "Zonas más afectadas": the alteration chosen, its zones and electrodes. */
protected readonly zone = signal<string | undefined>(undefined);
protected readonly zoned = computed(() => {
const m = this.alterations().find((a) => a.code === this.zone());
return m ? { code: m.code, zones: m.zones ?? [], electrodes: m.electrodes ?? [] } : undefined;
});
protected readonly zonesScored = computed(() =>
[...(this.zoned()?.zones ?? []), ...(this.zoned()?.electrodes ?? [])].some(
(s) => s.z !== null && s.z !== undefined,
),
);
protected readonly biomarkerNames = BIOMARKER_NAMES;
protected readonly outcomeNames = OUTCOME_NAMES;
/** "Relación con el ADOS-2": her altered zones (|z| ≥ 2) with a clear association in the
* cohort (q < 0.05), clearest first, as the old summary showed them. */
protected readonly related = computed(() =>
(this.eeg.value()?.analysis?.relation ?? [])
.filter((f) => Math.abs(f.z) >= 2 && f.q !== null && f.q !== undefined && f.q < 0.05)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1)),
);
protected qText(q?: number | null): string {
return q === null || q === undefined ? '—' : q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`;
}
protected observed(f: Relation): string {
if (f.observed === null || f.observed === undefined) return 'Sin dato';
if (f.kind === 'item')
return f.observed >= 1 ? `Alterado (${f.observed})` : 'Sin anormalidad (0)';
return `CSS ${f.observed}`;
}
/** Whether what she shows is what the model leans to (above or below one half). */
protected matches(f: Relation): string | undefined {
if (f.observed === null || f.observed === undefined) return undefined;
const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8;
return present === f.probability >= 0.5
? 'Coincide con la asociación de la cohorte'
: 'No coincide con la asociación de la cohorte';
}
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.riskModels(), this.top()));
private top(): number {
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(() => {
const p = this.patient();
return {
name: p?.name?.[0]?.text,
curp: p?.identifier?.find((i) => i.system === CURP)?.value,
// each record number once (several sources may carry the same one)
numbers: [
...new Set(
(p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''),
),
].filter(Boolean),
};
});
/** CaMa: her row on the follow-up list (window and cut-off as opened, else the widest
* window up to the last day with data), as the list shows it: the old record's card. */
private readonly listed = resource({
params: () =>
this.domain() === 'cama'
? {
domain: this.domain(),
id: this.id(),
window: Number(this.ventana()) || 12,
cutoff: this.corte() || undefined,
}
: undefined,
loader: async ({ params: { domain, id, window, cutoff } }) => {
const page = await this.fhir.search(domain, 'Patient', {
_id: id,
'follow-up-window': window,
'follow-up-cutoff': cutoff,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
const self = page.link?.find((l) => l.relation === 'self')?.url;
const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
return { window, cutoff: applied, row: camaRows(page, applied)[0] };
},
});
protected readonly cama = computed(() => {
const found = this.listed.value();
const d = this.data.value();
if (!found || !d) return undefined;
// Her own latest mammogram and biopsy, on the list or not.
const latest = (study: string) =>
d.reports
.filter((r) => code(r.code) === study)
.sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''))
.at(-1);
const value = (r: DiagnosticReport | undefined, field: string) => {
const o = (r?.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.find((x) => code(x?.code) === field);
return o ? shown(o) : undefined;
};
const mammogram = latest('mammography');
const biopsy = latest('breast_biopsy');
const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff);
const r = found.row;
return {
...found,
ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS),
scenario: treated ? 'Post-tratamiento' : 'En observación',
status: r ? name(r.status) : undefined,
priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined,
birads: value(mammogram, 'mammography.birads'),
mammogram: mammogram?.effectiveDateTime?.slice(0, 10),
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
histology: value(biopsy, 'breast_biopsy.histology'),
biopsy: biopsy
? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime)
: undefined,
};
});
protected readonly status = computed(() => {
const p = this.patient();
return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : '';
});
} }
+77
View File
@@ -0,0 +1,77 @@
import { ANTECEDENTS, group, split } from './record-groups';
const fact = (study: string, field: string, title: string, value: string) => ({
study,
field,
title,
value,
});
describe('the record of a cytology by what its facts are', () => {
it('splits a catalog code into its study and its field', () => {
expect(split('cervical_cytology.hpv_16')).toEqual({
study: 'cervical_cytology',
field: 'hpv_16',
});
expect(split('plain')).toEqual({ study: '', field: 'plain' });
});
it('keeps the form antecedents apart from the results and the findings', () => {
const found = group([
fact(
'cervical_cytology',
'screening_history',
'Detección de cáncer de cérvix',
'Primera vez en la vida',
),
fact(
'cervical_cytology',
'gynecologic_condition',
'Condición ginecoobstétrica a la detección',
'DIU in situ',
),
fact('cervical_cytology', 'presenting_symptom', 'Actualmente presenta', 'Flujo'),
fact('cervical_cytology', 'cervix_appearance', 'A la exploración se observa', 'Cuello sano'),
fact('cervical_cytology', 'adequacy', 'Calidad de la muestra', 'Satisfactoria'),
fact(
'cervical_cytology',
'result',
'Resultado (Bethesda)',
'Negativo para lesión intraepitelial o malignidad',
),
fact('cervical_cytology', 'hpv', 'VPH de alto riesgo', 'negativo'),
fact('cervical_cytology', 'findings', 'Hallazgos adicionales', 'Inflamación.'),
fact('cervical_cytology', 'finding_inflammation', 'Hallazgo: inflamación', 'positivo'),
]);
expect(Object.keys(found.antecedents)).toEqual(ANTECEDENTS.map((a) => a.field));
expect(found.antecedents['gynecologic_condition']).toBe('DIU in situ');
expect(found.results).toEqual([
'Calidad de la muestra: Satisfactoria',
'Resultado (Bethesda): Negativo para lesión intraepitelial o malignidad',
'VPH de alto riesgo: negativo',
]);
expect(found.findings).toEqual(['Texto del informe: Inflamación.', 'Inflamación']);
});
it('nothing is lost: every fact lands in exactly one place', () => {
const facts = [
fact('cervical_cytology', 'screening_history', 'a', '1'),
fact('cervical_cytology', 'result', 'b', '2'),
fact('cervical_cytology', 'finding_atrophy', 'Hallazgo: atrofia', 'positivo'),
fact('cervical_biopsy', 'histology', 'Histología', 'LIEAG'),
];
const found = group(facts);
expect(
Object.keys(found.antecedents).length + found.results.length + found.findings.length,
).toBe(facts.length);
});
it('a study that is not the cytology has no antecedents and no collapsed findings', () => {
const found = group([fact('cervical_biopsy', 'histology', 'Histología', 'LIEAG (CIN 2 y 3)')]);
expect(found.antecedents).toEqual({});
expect(found.findings).toEqual([]);
expect(found.results).toEqual(['Histología: LIEAG (CIN 2 y 3)']);
});
it('a stated finding keeps a value that is not simply "positivo"', () => {
expect(
group([fact('cervical_cytology', 'finding_none', 'Hallazgo: ninguno', 'negativo')]).findings,
).toEqual(['Ninguno: negativo']);
});
});
+28 -25
View File
@@ -1,5 +1,5 @@
/** A field of a study's form, as its Observation says it: `cervical_cytology.hpv` is the study /** One field of a study's form as the report's Observation carries it: the catalog's field
* `cervical_cytology` and the field `hpv`. */ * (`cervical_cytology.screening_history`), its title and its value as the screens say it. */
export interface Fact { export interface Fact {
study: string; study: string;
field: string; field: string;
@@ -7,47 +7,50 @@ export interface Fact {
value: string; value: string;
} }
/** What the cytology's form declares before and at the sample: statements of the form, not /** What the cytology's form declares of her before and at the sample: her screening history, the
* diagnoses. */ * gynecologic condition she reports, what she presents and what the exploration observed. These are
export const ANTECEDENTS = [ * statements of the form (not diagnoses), each with its form and day. */
export const ANTECEDENTS: { field: string; title: string }[] = [
{ field: 'screening_history', title: 'Detección de cáncer de cérvix' }, { field: 'screening_history', title: 'Detección de cáncer de cérvix' },
{ field: 'gynecologic_condition', title: 'Condición ginecoobstétrica a la detección' }, { field: 'gynecologic_condition', title: 'Condición ginecoobstétrica a la detección' },
{ field: 'presenting_symptom', title: 'Actualmente presenta' }, { field: 'presenting_symptom', title: 'Actualmente presenta' },
{ field: 'cervix_appearance', title: 'A la exploración se observa' }, { field: 'cervix_appearance', title: 'A la exploración se observa' },
]; ];
const DECLARED = new Set(ANTECEDENTS.map((a) => a.field));
const HPV = new Set(['hpv', 'hpv_16', 'hpv_18']);
/** A catalog code as its study and field. */ /** `cervical_cytology.hpv` as its study and its field. */
export function split(code: string): { study: string; field: string } { export function split(code: string): { study: string; field: string } {
const [study, ...field] = code.split('.'); const at = code.indexOf('.');
return field.length ? { study, field: field.join('.') } : { study: '', field: code }; return at < 0
? { study: '', field: code }
: { study: code.slice(0, at), field: code.slice(at + 1) };
} }
const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); /** A report's facts by what they are: the form's antecedents (by field), the results of the study
* itself, and the extra findings (collapsible): the cytologist's text and each stated finding. */
/** A report's facts sorted by what they are: the form's antecedents (by field), the study's own
* results, and the extra findings (the cytologist's text first, then each finding stated). */
export function group(facts: Fact[]) { export function group(facts: Fact[]) {
const antecedents: Record<string, string> = {}; const antecedents: Record<string, string> = {};
const results: string[] = []; const results: string[] = [];
const findings: string[] = []; const findings: string[] = [];
for (const f of facts) { for (const f of facts) {
const form = f.study === 'cervical_cytology'; const cytology = f.study === 'cervical_cytology';
if (form && DECLARED.has(f.field)) antecedents[f.field] = f.value; if (cytology && ANTECEDENTS.some((a) => a.field === f.field)) antecedents[f.field] = f.value;
else if (form && f.field === 'findings') findings.unshift(`Texto del informe: ${f.value}`); else if (cytology && f.field === 'findings') findings.unshift(`Texto del informe: ${f.value}`);
else if (form && f.field.startsWith('finding_')) { else if (cytology && f.field.startsWith('finding_')) {
const named = capital(f.title.replace(/^Hallazgo: /, '')); const named = f.title.replace(/^Hallazgo: /, '');
findings.push(f.value === 'positivo' ? named : `${named}: ${f.value}`); const text = named.charAt(0).toUpperCase() + named.slice(1);
findings.push(f.value === 'positivo' ? text : `${text}: ${f.value}`);
} else {
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
results.push(f.value.startsWith(f.title) ? f.value : `${f.title}: ${f.value}`);
} }
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
else results.push(f.value.startsWith(f.title) ? f.value : `${f.title}: ${f.value}`);
} }
return { antecedents, results, findings }; return { antecedents, results, findings };
} }
/** A cytology report's HPV results apart from the cytology's own: they are a study of their own. */ 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[]) { export function hpvApart(facts: Fact[]) {
const hpv = (f: Fact) => f.study === 'cervical_cytology' && HPV.has(f.field); const isHpv = (f: Fact) => f.study === 'cervical_cytology' && HPV_FIELDS.includes(f.field);
return { hpv: facts.filter(hpv), rest: facts.filter((f) => !hpv(f)) }; return { hpv: facts.filter(isHpv), rest: facts.filter((f) => !isHpv(f)) };
} }
+92
View File
@@ -0,0 +1,92 @@
import { recordSheets } from './record-sheets';
describe('the PDF of a record', () => {
const sheets = recordSheets(
[['Nombre', 'Ana']],
[
{
label: 'Toma de muestra',
day: '2026-01-10',
state: 'recorded',
sources: ['cytology-form'],
},
{
label: 'Colposcopía',
day: '2026-02-01',
state: 'inferred',
sources: ['clinical-note', 'biopsy-order'],
},
{
label: 'Reporte de biopsia',
state: 'pending',
requested: '2026-02-05',
sources: ['date-association'],
},
{ label: 'Diagnóstico', state: 'unknown' },
],
[{ date: '2026-03-01', kind: 'Diagnóstico', text: 'N87.9' }],
[
{
date: '2026-01-10',
kind: 'Citología cervical',
reported: '2026-01-20',
results: ['Resultado (Bethesda): LIEAG'],
findings: ['Texto del informe: Inflamación.', 'Inflamación'],
},
],
[
{
date: '2026-01-10',
values: { screening_history: 'Primera vez en la vida', cervix_appearance: 'Cuello sano' },
},
],
[],
);
const by = (title: string) => sheets.find((s) => s.title.startsWith(title))!;
it('keeps every section, in the page order', () => {
expect(sheets.map((s) => s.title.split(' (')[0])).toEqual([
'Datos de la paciente',
'Etapas del tamizaje',
'Historial médico',
'Antecedentes y evaluación ginecológica',
'Pruebas y resultados',
'Probabilidades',
]);
});
it('writes each stage with its state, its day or its request, and where it comes from', () => {
expect(by('Etapas').head).toEqual(['Etapa', 'Estado', 'Fecha', 'Procedencia']);
expect(by('Etapas').rows).toEqual([
['Toma de muestra', 'Registrada', '2026-01-10', 'Formulario de citología'],
['Colposcopía', 'Inferida por fechas', '2026-02-01', 'Nota clínica · Orden de biopsia'],
['Reporte de biopsia', 'Pendiente', 'Solicitada el 2026-02-05', 'Asociación por fechas'],
['Diagnóstico', 'Sin dato', '', ''],
]);
});
it('gives the declared antecedents their own sheet, said as declared, with what is not documented', () => {
const s = by('Antecedentes');
expect(s.title).toContain('no son diagnósticos confirmados');
expect(s.head).toEqual([
'Toma',
'Detección de cáncer de cérvix',
'Condición ginecoobstétrica a la detección',
'Actualmente presenta',
'A la exploración se observa',
]);
expect(s.rows).toEqual([
['2026-01-10', 'Primera vez en la vida', 'No documentado', 'No documentado', 'Cuello sano'],
]);
});
it('keeps the results and the extra findings of each test in their own columns', () => {
expect(by('Pruebas').head).toEqual(['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos']);
expect(by('Pruebas').rows).toEqual([
[
'2026-01-10',
'Citología cervical',
'2026-01-20',
'Resultado (Bethesda): LIEAG',
'Texto del informe: Inflamación. · Inflamación',
],
]);
});
});
+30 -94
View File
@@ -1,14 +1,11 @@
import type { Sheet } from '../export'; import type { Sheet } from '../export';
import type { RiskScale } from './risk-scales';
import { ANTECEDENTS } from './record-groups'; import { ANTECEDENTS } from './record-groups';
import type { Prediction, RiskScale } from './risk-scales';
import { SOURCES, Stage, STATES } from './stages'; import { SOURCES, Stage, STATES } from './stages';
const NONE = 'No disponible'; const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`; const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
const between = (p?: Prediction) =>
p?.low === undefined || p.high === undefined ? NONE : `${percent(p.low)} a ${percent(p.high)}`;
type Facts = [string, string | undefined][];
interface Event { interface Event {
date: string; date: string;
kind: string; kind: string;
@@ -26,55 +23,22 @@ interface Form {
date: string; date: string;
values: Record<string, string | undefined>; values: Record<string, string | undefined>;
} }
/** A published estimate (risk, survival or recurrence) by horizon. */
interface Estimate {
text: string;
index: string;
predictions: Prediction[];
}
/** The curves of her clinical scenarios as the page lists them. */
export interface Analysis {
title: string;
scenarios: string[];
/** the titles of the figures drawn */
figures: string[];
/** her scenarios the report draws no curve for */
undrawn: string[];
}
const table = (title: string, facts: Facts): Sheet => ({ /** A patient's record as the tables of her PDF, in the page's order. */
title,
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
});
const historySheet = (history: Event[]): Sheet => ({
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
});
const testsSheet = (tests: Test[]): Sheet => ({
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos'],
rows: tests.map((t) => [
t.date,
t.kind,
t.reported ?? 'Pendiente',
t.results.join(' · '),
t.findings.join(' · '),
]),
});
/** A CaCu patient's record as the tables of her PDF, in the page's order. */
export function recordSheets( export function recordSheets(
facts: Facts, facts: [string, string | undefined][],
stages: Stage[], stages: Stage[],
history: Event[], history: Event[],
tests: Test[], tests: Test[],
scales: RiskScale[],
forms: Form[], forms: Form[],
scales: RiskScale[],
): Sheet[] { ): Sheet[] {
return [ return [
table('Datos de la paciente', facts), {
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{ {
title: 'Etapas del tamizaje', title: 'Etapas del tamizaje',
head: ['Etapa', 'Estado', 'Fecha', 'Procedencia'], head: ['Etapa', 'Estado', 'Fecha', 'Procedencia'],
@@ -85,7 +49,11 @@ export function recordSheets(
(s.sources ?? []).map((c) => SOURCES[c]).join(' · '), (s.sources ?? []).map((c) => SOURCES[c]).join(' · '),
]), ]),
}, },
historySheet(history), {
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{ {
title: title:
'Antecedentes y evaluación ginecológica (declarados en el formulario de la citología; no son diagnósticos confirmados)', 'Antecedentes y evaluación ginecológica (declarados en el formulario de la citología; no son diagnósticos confirmados)',
@@ -95,57 +63,25 @@ export function recordSheets(
...ANTECEDENTS.map((a) => f.values[a.field] ?? 'No documentado'), ...ANTECEDENTS.map((a) => f.values[a.field] ?? 'No documentado'),
]), ]),
}, },
testsSheet(tests), {
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos'],
rows: tests.map((t) => [
t.date,
t.kind,
t.reported ?? 'Pendiente',
t.results.join(' · '),
t.findings.join(' · '),
]),
},
{ {
title: 'Probabilidades', title: 'Probabilidades',
head: ['Estimación', 'Probabilidad', 'IC 95 %'], head: ['Estimación', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [label, risk ? percent(risk.p) : NONE, between(risk)]), rows: scales.map(({ label, risk }) => [
label,
risk ? percent(risk.p) : NONE,
risk?.low === undefined ? NONE : `${percent(risk.low)} a ${percent(risk.high!)}`,
]),
}, },
]; ];
} }
const horizon = (years: number) =>
years === 0 ? 'Al índice' : `${years} ${years === 1 ? 'año' : 'años'}`;
/** A CaMa patient's record as the tables of her PDF: only what CaMa publishes, an absent value
* said as such and no estimate made up. */
export function camaRecordSheets(
facts: Facts,
studies: Facts,
history: Event[],
tests: Test[],
estimates: Estimate[],
analyses: Analysis[],
): Sheet[] {
const risks = estimates.flatMap((m) =>
m.predictions.map((p) => [m.text, m.index || NONE, horizon(p.years), percent(p.p), between(p)]),
);
const curves = analyses.flatMap((a) => [
...a.figures.map((f) => [a.title, f, 'Curva publicada']),
...a.undrawn.map((s) => [a.title, s, 'No disponible: datos insuficientes']),
...(a.figures.length || a.undrawn.length
? []
: [[a.title, a.scenarios.join('; ') || NONE, NONE]]),
]);
return [
table('Datos de la paciente', facts),
table('Última mastografía y resultado histopatológico', studies),
historySheet(history),
testsSheet(tests),
{
title: 'Riesgos y recomendaciones publicados',
head: ['Estimación', 'Fecha índice', 'Horizonte', 'Probabilidad', 'IC 95 %'],
rows: risks.length ? risks : [['Sin estimaciones publicadas', NONE, NONE, NONE, NONE]],
},
...(curves.length
? [
{
title:
'Supervivencia y recurrencia por escenario clínico (estimaciones del grupo, no predicciones individuales)',
head: ['Análisis', 'Escenario', 'Estado'],
rows: curves,
},
]
: []),
];
}
-147
View File
@@ -1,147 +0,0 @@
import type {
Condition,
DiagnosticReport,
Observation,
Patient,
Procedure,
RiskAssessment,
} from 'fhir/r4';
import { code, EXT, ext, label } from '../fhir';
import { LABELS, name } from '../indicadores/labels';
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
/** Her record as the FHIR API gives it. */
export interface PatientRecord {
patient: Patient;
conditions: Condition[];
procedures: Procedure[];
/** latest first */
reports: DiagnosticReport[];
observations: Map<string | undefined, Observation>;
risks: RiskAssessment[];
}
/** An Observation's value as the screens say it, whatever its type. */
export function shown(o: Observation): string {
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
if (o.valueCodeableConcept) {
// the screens' own name for the code (BI-RADS 4C), else the server's display
const c = code(o.valueCodeableConcept) ?? '';
return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept);
}
if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim();
return o.valueString ?? o.valueDateTime ?? '';
}
/** A report's Observations. */
export const results = (d: PatientRecord, r: DiagnosticReport) =>
(r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o): o is Observation => !!o);
/** Observations as facts of their study's form. */
const facts = (observations: Observation[]): Fact[] =>
observations.map((o) => ({
...split(code(o.code) ?? ''),
title: label(o.code),
value: shown(o),
}));
/** Her diagnoses and procedures, latest first. */
export function history(d: PatientRecord) {
return [
...d.conditions.map((c) => ({
date: c.recordedDate ?? '',
kind: 'Diagnóstico',
text: label(c.code),
// the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid)
code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code,
})),
...d.procedures.map((p) => ({
date: p.performedDateTime ?? '',
kind: 'Procedimiento',
text: label(p.code),
code: undefined,
})),
].sort((a, b) => b.date.localeCompare(a.date));
}
/** Her studies and their own results; the form's antecedents have their section, the extra
* findings are collapsed, and an HPV result is a study of its own row. */
export function tests(d: PatientRecord) {
return d.reports.flatMap((r) => {
const { hpv, rest } = hpvApart(facts(results(d, r)));
const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
status: r.status,
results: found.results,
findings: found.findings,
};
if (!hpv.length) return [row];
return [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }];
});
}
/** What each cytology's form declares (statements, not diagnoses), the one she was opened at
* first; forms that declare nothing are left out. */
export function forms(d: PatientRecord, opened?: string) {
const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology');
const first = cytologies.find((r) => r.effectiveDateTime === opened) ?? cytologies[0];
return [first, ...cytologies.filter((r) => r !== first)]
.filter((r) => !!r)
.map((r) => ({
date: r.effectiveDateTime ?? '',
values: group(facts(results(d, r))).antecedents,
}))
.filter((f) => ANTECEDENTS.some((a) => f.values[a.field]));
}
/** The JSON of a model's inputs as an object; anything else is none. */
function inputs(value?: string): Record<string, unknown> | undefined {
try {
const found: unknown = value && JSON.parse(value);
return found && typeof found === 'object' && !Array.isArray(found)
? (found as never)
: undefined;
} catch {
return undefined;
}
}
/** The day of an instant at the hospital (America/Monterrey). */
const localDay = (instant?: string) =>
instant && new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' });
/** Each model's latest assessment of her. */
export function models(risks: RiskAssessment[]) {
const latest = new Map<string, RiskAssessment>();
for (const r of risks) {
const key = code(r.method) ?? '';
const held = latest.get(key)?.occurrenceDateTime;
if (held === undefined || held < (r.occurrenceDateTime ?? '')) latest.set(key, r);
}
return [...latest.values()].map((r) => ({
model: code(r.method) ?? '',
text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '',
/** risk, mortality (survival) or other (recurrence) */
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: inputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico')
.map((e) => e.valueString ?? ''),
predictions: (r.prediction ?? []).map((p) => ({
years: p.whenRange?.high?.value ?? 0,
p: p.probabilityDecimal ?? 0,
low: ext(p, 'ic-bajo')?.valueDecimal,
high: ext(p, 'ic-alto')?.valueDecimal,
})),
}));
}
export type Model = ReturnType<typeof models>[number];
+260
View File
@@ -0,0 +1,260 @@
import type { Parameters } from 'fhir/r4';
import { groupReference, horizonLabel, outcomeText, referenceView } from './reference-risk';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const answer = (...parameter: object[]): Parameters =>
({ resourceType: 'Parameters', parameter }) as Parameters;
const resolved = (comparison: object[] = []) =>
answer(
part('status', { valueCode: 'resolved' }),
part('cutoff', { valueDate: '2026-11-30' }),
part('scenario', {
part: [
part('table', { valueCode: 'screening' }),
part('label', { valueString: 'Tamizaje' }),
part('key', {
part: [
part('name', { valueCode: 'history' }),
part('value', { valueString: 'Cotest-negative' }),
],
}),
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0 }),
...comparison,
],
}),
part('horizon', {
part: [part('years', { valueInteger: 5 }), part('published', { valueBoolean: false })],
}),
);
describe('the reference answer as the section shows it', () => {
it('names the horizons and never calls a year the immediate risk', () => {
expect(horizonLabel(0)).toBe('Inmediato (al índice)');
expect(horizonLabel(1)).toBe('1 año');
expect(horizonLabel(5)).toBe('5 años');
});
it('keeps a published zero as zero and a blank as absent', () => {
const view = referenceView(resolved());
expect(view.horizons.map((h) => [h.years, h.reference, h.published])).toEqual([
[0, 0, true],
[5, undefined, false],
]);
expect(view.scenario).toEqual({
label: 'Tamizaje',
keys: [{ name: 'Antecedente más reciente', value: 'Cotest-negative' }],
});
});
it('reads a comparison with its model, its figures and its reasons, and a difference only when one is given', () => {
const view = referenceView(
resolved([
part('comparison', {
part: [
part('model', { valueCode: 'cacu.cin2_pim' }),
part('title', { valueString: 'Riesgo LIEAG+' }),
part('institutional', { valueDecimal: 0.05 }),
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'outcome_differs' }),
],
}),
]),
);
const [c] = view.horizons[0].comparisons;
expect(c).toMatchObject({
model: 'cacu.cin2_pim',
institutional: 0.05,
status: 'not_comparable',
reasons: ['outcome_differs'],
});
expect(c.differencePp).toBeUndefined();
});
it('an unresolved answer has its state and reasons and no horizons', () => {
const view = referenceView(
answer(
part('status', { valueCode: 'history_not_demonstrable' }),
part('reason', { valueCode: 'no_earlier_test_registered' }),
),
);
expect(view).toMatchObject({
status: 'history_not_demonstrable',
reasons: ['no_earlier_test_registered'],
horizons: [],
used: [],
});
});
});
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']);
});
});
+615
View File
@@ -0,0 +1,615 @@
import { DecimalPipe } from '@angular/common';
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. */
export const STATUS_TEXT: Record<string, string> = {
resolved: 'Referencia disponible',
not_published: 'Probabilidad no publicada en las tablas',
missing_data: 'Falta un dato clínico',
history_not_demonstrable: 'Antecedente no demostrable',
not_applicable: 'Escenario no aplicable',
contradictory: 'Resultados contradictorios',
ambiguous: 'Escenario ambiguo',
scenario_not_implemented: 'Escenario aún no resuelto',
unverifiable_correspondence: 'Correspondencia no verificable',
no_published_row: 'Sin fila publicada para esta combinación',
};
/** Why a resolution or a comparison has no value. */
export const REASON_TEXT: Record<string, string> = {
no_cytology_reported_by_cutoff: 'No hay citología con resultado a la fecha de corte.',
sample_not_reported_by_cutoff: 'La citología pedida no tenía resultado a la fecha de corte.',
no_birth_date: 'Falta la fecha de nacimiento.',
age_outside_25_65: 'La edad está fuera del rango de las tablas (25 a 65 años).',
cytology_not_in_tables: 'El resultado citológico no está en las tablas.',
missing_hpv: 'La citología no tiene resultado de VPH.',
contradictory_hpv: 'El VPH es negativo pero se reporta un genotipo positivo.',
hpv_positive_row:
'Las tablas muestran «VPH positivo» junto a VPH 16 y VPH 18; no se verificó si esa fila es el total o los otros tipos, y no se asume.',
no_earlier_test_registered:
'La plataforma no tiene una prueba anterior con VPH; no demuestra que no haya antecedente.',
earlier_test_older_than_5_years: 'La prueba anterior es de hace más de 5 años.',
colposcopy_or_treatment_before:
'Hay una colposcopía, biopsia o tratamiento previo: es un escenario posterior a colposcopía o tratamiento, aún no resuelto.',
history_is_a_surveillance_scenario:
'El antecedente anormal corresponde a la tabla de vigilancia, aún no resuelta.',
registered_cin2_plus_before: 'Hay un CIN2+ registrado antes: las tablas lo excluyen.',
hysterectomy_declared: 'El formulario declara una histerectomía: las tablas la excluyen.',
procedure_after_without_named_referral:
'Hay una colposcopía o biopsia posterior, pero ningún registro la nombra como derivada de esta citología (una asociación por fechas no basta).',
several_biopsies_name_the_cytology: 'Varias biopsias nombran esta citología.',
not_a_referral_result_in_the_tables:
'La citología no es un resultado de derivación de las tablas.',
hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.',
cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.',
biopsy_without_histology: 'La biopsia no tiene histología.',
risk_blank_in_the_tables: 'Las tablas dejan esta probabilidad en blanco.',
no_row_for_the_combination: 'Las tablas no publican esa combinación.',
several_rows: 'Más de una fila podría corresponder.',
no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.',
outcome_differs: 'El desenlace del modelo no es el de la tabla (CIN3+).',
unknown_model: 'El desenlace del modelo no está registrado para comparar.',
horizon_not_published_by_model: 'El modelo no publica una predicción a este horizonte.',
index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.',
population_not_verified:
'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.',
no_reference: 'Las tablas no dan una probabilidad a este horizonte.',
};
const KEY_TEXT: Record<string, string> = {
history: 'Antecedente más reciente',
hpv: 'VPH actual',
cytology: 'Citología actual',
referral: 'Resultado de tamizaje que originó la colposcopía',
biopsy: 'Resultado de biopsia',
};
const USED_TEXT: Record<string, string> = {
'sample-date': 'toma',
'report-date': 'reporte',
'request-date': 'solicitud',
result: 'resultado',
hpv: 'VPH',
'hpv-16': 'VPH 16',
'hpv-18': 'VPH 18',
histology: 'histología',
};
const usedValue = (v: unknown) => (v === true ? 'positivo' : v === false ? 'negativo' : String(v));
export interface ComparisonView {
model?: string;
title?: string;
outcome?: string;
/** probabilities, 0 to 1 */
institutional?: number;
low?: number;
high?: number;
status: string;
/** percentage points, institutional minus reference */
differencePp?: number;
reasons: string[];
}
export interface HorizonView {
years: number;
label: string;
published: boolean;
/** probability, 0 to 1; none when the tables leave it blank */
reference?: number;
comparisons: ComparisonView[];
}
export interface ReferenceView {
status: string;
reasons: string[];
cutoff?: string;
scenario?: { label: string; keys: { name: string; value: string }[] };
index?: { sampleDate?: string; reportDate?: string; result?: string; age?: number };
evaluationDate?: string;
source?: { id?: string; file?: string; sha256?: string; outcome?: string; status?: string };
row?: { sheet?: string; number?: number; officialCheck?: string; matchedVia?: string };
used: { label: string; details: string }[];
assumptions: string[];
horizons: HorizonView[];
}
type Part = ParametersParameter;
const value = (p?: Part) =>
p?.valueCode ??
p?.valueString ??
p?.valueDate ??
p?.valueInteger ??
p?.valueDecimal ??
p?.valueBoolean ??
undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const one = (parts: Part[] | undefined, name: string) => value(named(parts, name)[0]);
/** The horizon's name; the colposcopy table's one year is a year, never "immediate". */
export function horizonLabel(years: number): string {
return years === 0 ? 'Inmediato (al índice)' : years === 1 ? '1 año' : `${years} años`;
}
/** The result of `$reference-risk` as the section shows it. A value absent from the answer stays
* absent: no zero is made of a blank, and no difference is made of a comparison that is not one. */
export function referenceView(answer: Parameters): ReferenceView {
const top = answer.parameter ?? [];
const scenario = named(top, 'scenario')[0];
const index = named(top, 'index')[0]?.part;
const row = named(top, 'row')[0]?.part;
const source = named(top, 'source')[0]?.part;
const view: ReferenceView = {
status: String(one(top, 'status') ?? 'missing_data'),
reasons: named(top, 'reason').map((r) => String(value(r))),
cutoff: one(top, 'cutoff') as string | undefined,
evaluationDate: one(top, 'evaluation-date') as string | undefined,
used: named(top, 'used').map((u) => ({
label: String(one(u.part, 'label') ?? ''),
details: (u.part ?? [])
.filter((p) => p.name !== 'label')
.map((p) => `${USED_TEXT[p.name ?? ''] ?? p.name}: ${usedValue(value(p))}`)
.join(' · '),
})),
assumptions: named(top, 'assumption').map((a) => String(value(a))),
horizons: named(top, 'horizon').map((h) => {
const years = Number(one(h.part, 'years'));
return {
years,
label: horizonLabel(years),
published: one(h.part, 'published') === true,
reference: one(h.part, 'reference') as number | undefined,
comparisons: named(h.part, 'comparison').map((c) => ({
model: one(c.part, 'model') as string | undefined,
title: one(c.part, 'title') as string | undefined,
outcome: one(c.part, 'outcome') as string | undefined,
institutional: one(c.part, 'institutional') as number | undefined,
low: one(c.part, 'institutional-low') as number | undefined,
high: one(c.part, 'institutional-high') as number | undefined,
status: String(one(c.part, 'status')),
differencePp: one(c.part, 'difference-pp') as number | undefined,
reasons: named(c.part, 'reason').map((r) => String(value(r))),
})),
};
}),
};
if (scenario?.part)
view.scenario = {
label: String(one(scenario.part, 'label') ?? ''),
keys: named(scenario.part, 'key').map((k) => ({
name: KEY_TEXT[String(one(k.part, 'name'))] ?? String(one(k.part, 'name')),
value: String(one(k.part, 'value')),
})),
};
if (index)
view.index = {
sampleDate: one(index, 'sample-date') as string | undefined,
reportDate: one(index, 'report-date') as string | undefined,
result: one(index, 'result') as string | undefined,
age: one(index, 'age') as number | undefined,
};
if (row)
view.row = {
sheet: one(row, 'sheet') as string | undefined,
number: one(row, 'number') as number | undefined,
officialCheck: one(row, 'official-check') as string | undefined,
matchedVia: one(row, 'matched-via') as string | undefined,
};
if (source)
view.source = {
id: one(source, 'id') as string | undefined,
file: one(source, 'file') as string | undefined,
sha256: one(source, 'sha256') as string | undefined,
outcome: one(source, 'outcome') as string | undefined,
status: one(source, 'status') as string | undefined,
};
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',
differs: 'no coincide con la tabla del NCI',
not_found_in_official: 'sin fila equivalente en la tabla del NCI consultada',
blank_in_both: 'en blanco en ambas',
no_official_file: 'sin tabla del NCI para cotejar',
};
/** Comparison with the NCI's reference risks (experimental): the reference by horizon beside the
* institutional models', the difference only where the two are the same estimate. */
@Component({
selector: 'app-reference-risk',
imports: [DecimalPipe],
template: `
@let v = view();
<section
class="reference"
data-section="referencia-nci"
aria-label="Comparación de probabilidades de referencia"
>
<h3>Comparación de probabilidades de referencia</h3>
<dl class="meta">
<div>
<dt>Estado</dt>
<dd [attr.data-status]="v.status">{{ statusText(v.status) }}</dd>
</div>
@if (v.scenario; as s) {
<div>
<dt>Escenario clínico</dt>
<dd>{{ s.label }}</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>
<dd>{{ day }}</dd>
</div>
}
@if (v.cutoff) {
<div>
<dt>Fecha de corte</dt>
<dd>{{ v.cutoff }}</dd>
</div>
}
@if (v.source; as src) {
<div>
<dt>Fuente y versión</dt>
<dd>Tablas NCI (libro {{ src.file }}, {{ src.id }}); no validadas</dd>
</div>
}
</dl>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivo">
@for (r of v.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (v.horizons.length) {
@let g = grouped();
<table class="plain" aria-label="Referencia NCI por horizonte">
<thead>
<tr>
<th>Horizonte</th>
<th>Referencia NCI</th>
</tr>
</thead>
<tbody>
@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 la probabilidad institucional menos la probabilidad NCI y solo se calcula si ambos
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
</p>
}
@if (v.used.length || v.assumptions.length || v.scenario || v.row) {
<details class="used">
<summary>Antecedentes utilizados</summary>
@if (v.scenario; as s) {
<ul>
@for (k of s.keys; track k.name) {
<li>{{ k.name }}: {{ k.value }}</li>
}
</ul>
}
@if (v.index; as i) {
<p>
Citología evaluada: toma {{ i.sampleDate }}, reporte {{ i.reportDate }}, resultado
{{ i.result }}
@if (i.age !== undefined) {
, edad {{ i.age }} años
}
.
</p>
}
<ul>
@for (u of v.used; track $index) {
<li>
<strong>{{ u.label }}</strong>: {{ u.details }}
</li>
}
</ul>
@if (v.row; as r) {
<p class="muted">
Fila de origen: «{{ r.sheet }}», fila {{ r.number }}
@if (r.matchedVia === 'table_group') {
(categoría agrupada definida por la propia tabla)
}
— {{ official(r.officialCheck) }}.
</p>
}
@for (a of v.assumptions; track a) {
<p class="muted">Sin verificar: {{ a }}</p>
}
</details>
}
</section>
`,
styles: `
.reference {
border: 1px dashed #9aa3ab;
border-radius: 6px;
margin: 16px 0;
padding: 12px 16px;
}
h3 {
margin: 0 0 8px;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
margin: 0 0 8px;
}
.meta dt {
color: var(--color-text-secondary);
font-size: 12px;
}
.meta dd {
font-weight: 500;
margin: 0;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th,
td {
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
.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;
padding-left: 18px;
}
.note {
font-size: 12px;
}
.used {
margin-top: 8px;
}
.used summary {
cursor: pointer;
}
@media (max-width: 700px) {
.reference {
padding: 8px 10px;
}
table,
thead,
tbody,
tr,
th,
td {
display: block;
}
thead {
display: none;
}
tr {
border-bottom: 1px solid #dce3e7;
padding: 6px 0;
}
td {
padding: 2px 0;
}
td::before {
color: var(--color-text-secondary);
content: attr(data-label);
display: block;
font-size: 12px;
}
}
`,
})
export class ReferenceRisk {
readonly view = input.required<ReferenceView>();
protected readonly grouped = computed(() => groupReference(this.view()));
protected outcomeText(outcome?: string) {
return outcomeText(outcome);
}
protected statusText(status: string) {
return STATUS_TEXT[status] ?? status;
}
protected reasonText(reason: string) {
return REASON_TEXT[reason] ?? reason;
}
protected official(check?: string) {
return OFFICIAL[check ?? ''] ?? 'sin cotejo';
}
}
-65
View File
@@ -1,65 +0,0 @@
<mat-card appearance="outlined" data-section="riesgos">
@if (excluded(); as reason) {
<mat-card-header>
<mat-card-title>Sin estimación de riesgo: criterio de exclusión</mat-card-title>
</mat-card-header>
<mat-card-content>
<p role="status" data-state="excluded">{{ reason }}</p>
</mat-card-content>
} @else {
<mat-card-content>
@if (note(); as said) {
<p class="muted note" data-state="toma">{{ said }}</p>
}
<app-risk-scales [groups]="groups()" />
@if (models().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 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.high !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high * 100 | number: '1.1-2' }} %
} @else {
—
}
</td>
</tr>
}
}
</tbody>
</table>
</details>
}
@if (models().length || drawn()) {
<details class="curves" open data-section="curvas">
<summary>Curvas de probabilidad con su intervalo</summary>
@if (drawn(); as series) {
<app-risk-series [series]="series" />
} @else {
<app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
}
</details>
}
@if (!models().length) {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
</mat-card-content>
}
</mat-card>
-79
View File
@@ -1,79 +0,0 @@
import { DecimalPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, resource } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import type { Parameters } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import { Plot } from '../plot';
import type { Model } from './record';
import { curveFigure } from './risk-curve';
import { RiskGroup, RiskScales } from './risk-scales';
import { parseSeries, RiskSeries } from './risk-series';
/** Her risk: why she has none, or the scales of each model, its values and its curves (CaCu: with
* the series `$risk-series` publishes, when the API has them on). */
@Component({
selector: 'app-risk-card',
imports: [DecimalPipe, MatCardModule, Plot, RiskScales, RiskSeries],
templateUrl: './risk-card.html',
styles: `
.note {
font-size: 12px;
margin: 8px 0 12px;
}
.curves {
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 12px;
padding: 8px 12px;
summary {
cursor: pointer;
font-weight: 500;
}
}
`,
})
export class RiskCard {
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
readonly domain = input.required<string>();
readonly id = input.required<string>();
readonly cutoff = input<string>();
/** the day of the cytology her estimates speak of */
readonly sample = input<string>();
/** the models whose estimate is a risk (not survival or recurrence) */
readonly models = input.required<Model[]>();
readonly groups = input.required<RiskGroup[]>();
/** why she has no estimate, when she has none */
readonly excluded = input<string>();
readonly note = input<string>();
/** CaCu, experimental: the series her record compares; none while the API has them off. */
protected readonly series = resource({
params: () =>
this.domain() === 'cacu'
? { id: this.id(), cutoff: this.cutoff(), sample: this.sample()?.slice(0, 10) }
: undefined,
loader: async ({ params: { id, ...asked } }) => {
const params = Object.fromEntries(Object.entries(asked).filter(([, v]) => !!v)) as never;
const url = `${this.root}/cacu/fhir/Patient/${id}/$risk-series`;
try {
return parseSeries(await firstValueFrom(this.http.get<Parameters>(url, { params })));
} catch {
return undefined;
}
},
});
protected readonly drawn = computed(() =>
this.series.hasValue() && this.series.value()?.some((s) => s.points.length)
? this.series.value()
: undefined,
);
protected readonly curve = computed(() =>
curveFigure(
this.models(),
Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))),
),
);
}
+100
View File
@@ -0,0 +1,100 @@
import { curveFigure, curveText } from './risk-curve';
const model = (text: string, predictions: object[], index = '2026-06-01') => ({
text,
index,
predictions: predictions as { years: number; p: number; low?: number; high?: number }[],
});
const traces = (models: ReturnType<typeof model>[]) => curveFigure(models, 0.4).data as any[];
describe('the institutional curves', () => {
it('draws one series per model, named as the model, at the horizons it publishes only', () => {
const found = traces([
model('Riesgo LIEAG+ v3', [
{ years: 1, p: 0.08 },
{ years: 3, p: 0.21 },
{ years: 5, p: 0.34 },
]),
model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]),
]);
const lines = found.filter((t) => !t.name?.startsWith('IC'));
expect(lines.map((t) => t.name)).toEqual(['Probabilidad LIEAG+', 'Probabilidad cáncer']);
expect(lines[0].x).toEqual([1, 3, 5]);
expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]);
expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere
expect(lines[1].mode).toBe('markers');
expect(lines[0].color ?? lines[0].line.color).not.toBe(lines[1].line.color);
});
it('puts the axis ticks on the published horizons and invents none between them', () => {
const f = curveFigure(
[
model('M v1', [
{ years: 0, p: 0.01 },
{ years: 5, p: 0.05 },
]),
],
0.05,
);
expect((f.layout!.xaxis as any).tickvals).toEqual([0, 5]);
expect((f.layout!.xaxis as any).title.text).toBe(
'Horizonte (años desde la fecha índice (2026-06-01))',
);
const mixed = curveFigure(
[model('A v1', [{ years: 1, p: 0.1 }]), model('B v1', [{ years: 3, p: 0.2 }], '2026-07-01')],
0.2,
);
expect((mixed.layout!.xaxis as any).tickvals).toEqual([1, 3]);
expect((mixed.layout!.xaxis as any).title.text).toBe('Horizonte (años desde la fecha índice)'); // two index dates: none is named
});
it('draws a band only where intervals are published, with its own legend entry, and no band without them', () => {
const none = traces([
model('Sin IC v1', [
{ years: 1, p: 0.1 },
{ years: 5, p: 0.3 },
]),
]);
expect(none).toHaveLength(1);
expect(none[0].fill).toBeUndefined();
const withBand = traces([
model('Con IC v1', [
{ years: 1, p: 0.1, low: 0.05, high: 0.12 },
{ years: 3, p: 0.2, low: 0.15, high: 0.28 },
{ years: 5, p: 0.3, low: 0.26, high: 0.44 },
]),
]);
expect(withBand.map((t) => t.name)).toEqual([undefined, 'IC 95 % Con IC', 'Con IC']);
expect(withBand[1].fill).toBe('tonexty');
expect(withBand[1].y.map((y: number) => Math.round(y))).toEqual([5, 15, 26]);
});
it('a horizon without an interval is a gap in the band, never filled with the probability', () => {
const [high, low] = traces([
model('Hueco v1', [
{ years: 1, p: 0.1, low: 0.05, high: 0.12 },
{ years: 3, p: 0.2 },
{ years: 5, p: 0.3, low: 0.26, high: 0.44 },
]),
]);
expect(high.y[1]).toBeNull();
expect(low.y[1]).toBeNull();
expect(low.connectgaps).toBe(false);
});
it('one published interval is an error bar, not a band', () => {
const found = traces([model('Uno v1', [{ years: 5, p: 0.34, low: 0.26, high: 0.44 }])]);
expect(found).toHaveLength(1);
expect(found[0].error_y.array[0]).toBeCloseTo(10);
expect(found[0].error_y.arrayminus[0]).toBeCloseTo(8);
});
it('says each model, its index date and every horizon it publishes, with intervals only where there are', () => {
expect(
curveText([
model('Riesgo LIEAG+ v3', [
{ years: 5, p: 0.34, low: 0.26, high: 0.44 },
{ years: 1, p: 0.08 },
]),
model('Vacío v1', []),
]),
).toEqual([
'Probabilidad LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
]);
});
});
+92 -56
View File
@@ -1,63 +1,76 @@
import { Figure, PALETTE } from '../plot'; import { Figure, PALETTE } from '../plot';
import type { Prediction } from './risk-scales';
/** A model's (or a source's) probabilities by horizon. */ export interface CurvePrediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface CurveModel { export interface CurveModel {
/** its own title, with its version */ /** the model's own title, with its version */
text: string; text: string;
/** its index date ('' when it has none) */ /** the model's index date */
index: string; index: string;
predictions: Prediction[]; predictions: CurvePrediction[];
} }
const percent = (n: number) =>
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 });
const title = (m: CurveModel) => const title = (m: CurveModel) =>
m.text m.text
.replace(/ v\d+$/, '') .replace(/ v\d+$/, '')
.replace(/riesgo/gi, (w) => (w[0] === 'R' ? 'Probabilidad' : 'probabilidad')); .replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'));
const bounded = (p: Prediction) => p.low !== undefined && p.high !== undefined; const interval = (p: CurvePrediction) => p.low !== undefined && p.high !== undefined;
const percent = (n: number | undefined) => (n === undefined ? null : n * 100);
/** One series per model drawn only at the horizons it publishes (one horizon is a point); its /** The institutional models' risk by horizon: one series per model, drawn only at the horizons it
* 95 % interval a band where two or more horizons have one, else an error bar. Nothing is made up * publishes (a model with one horizon is a point), its 95 % interval as a band where it publishes
* between horizons: a gap in the intervals stays a gap. */ * one at two or more horizons and as an error bar at a single one. No horizon, interval or
* probability is made up: between published horizons the line joins them and nothing else. The
* NCI reference is not here. */
export function curveFigure(models: CurveModel[], top: number): Figure { export function curveFigure(models: CurveModel[], top: number): Figure {
const shown = models.filter((m) => m.predictions.length); const shown = models.filter((m) => m.predictions.length);
const ticks = [...new Set(shown.flatMap((m) => m.predictions.map((p) => p.years)))].sort( const years = [...new Set(shown.flatMap((m) => m.predictions.map((p) => p.years)))].sort(
(a, b) => a - b, (a, b) => a - b,
); );
const dates = [...new Set(shown.map((m) => m.index))]; const dates = [...new Set(shown.map((m) => m.index))];
const data = shown.flatMap((m, i) => { return {
const color = PALETTE[i % PALETTE.length]; data: shown.flatMap((m, i) => {
const sorted = [...m.predictions].sort((a, b) => a.years - b.years); const color = PALETTE[i % PALETTE.length];
const x = sorted.map((p) => p.years); const sorted = [...m.predictions].sort((a, b) => a.years - b.years);
const name = title(m); const x = sorted.map((p) => p.years);
const banded = sorted.filter(bounded).length; const name = title(m);
const edge = (pick: (p: Prediction) => number | undefined) => ({ const bounded = sorted.filter(interval);
x, const traces: object[] = [];
y: sorted.map((p) => (bounded(p) ? percent(pick(p)) : null)), if (bounded.length > 1) {
mode: 'lines', // a gap in the published intervals stays a gap: nothing is drawn between them
line: { width: 0 }, const at = (pick: (p: CurvePrediction) => number | undefined) =>
connectgaps: false, sorted.map((p) => (interval(p) ? (pick(p) as number) * 100 : null));
legendgroup: name, traces.push(
hoverinfo: 'skip', {
}); x,
const band = y: at((p) => p.high),
banded > 1 mode: 'lines',
? [ line: { width: 0 },
{ ...edge((p) => p.high), showlegend: false }, connectgaps: false,
{ showlegend: false,
...edge((p) => p.low), hoverinfo: 'skip',
fill: 'tonexty', legendgroup: name,
fillcolor: color + '33', },
name: `IC 95 % ${name}`, {
}, x,
] y: at((p) => p.low),
: []; mode: 'lines',
const bar = sorted.map((p) => (bounded(p) ? (p.high! - p.p) * 100 : 0)); line: { width: 0 },
const barMinus = sorted.map((p) => (bounded(p) ? (p.p - p.low!) * 100 : 0)); fill: 'tonexty',
return [ connectgaps: false,
...band, fillcolor: color + '33',
{ name: `IC 95 % ${name}`,
legendgroup: name,
hoverinfo: 'skip',
},
);
}
traces.push({
x, x,
y: sorted.map((p) => p.p * 100), y: sorted.map((p) => p.p * 100),
mode: sorted.length > 1 ? 'lines+markers' : 'markers', mode: sorted.length > 1 ? 'lines+markers' : 'markers',
@@ -65,24 +78,31 @@ export function curveFigure(models: CurveModel[], top: number): Figure {
legendgroup: name, legendgroup: name,
line: { color }, line: { color },
marker: { color, size: 8 }, marker: { color, size: 8 },
...(banded === 1 ...(bounded.length === 1
? { error_y: { type: 'data', symmetric: false, color, array: bar, arrayminus: barMinus } } ? {
error_y: {
type: 'data',
symmetric: false,
color,
array: sorted.map((p) => (interval(p) ? (p.high! - p.p) * 100 : 0)),
arrayminus: sorted.map((p) => (interval(p) ? (p.p - p.low!) * 100 : 0)),
},
}
: {}), : {}),
hovertemplate: `${name}<br>%{x} años: %{y:.2f} %<extra></extra>`, hovertemplate: `${name}<br>%{x} años: %{y:.2f} %<extra></extra>`,
}, });
]; return traces;
}); }) as Figure['data'],
const at = dates.length === 1 && dates[0] ? ` (${dates[0]})` : '';
return {
data,
layout: { layout: {
xaxis: { xaxis: {
title: { text: `Horizonte (años desde la fecha índice${at})` }, title: {
text: `Horizonte (años desde la fecha índice${dates.length === 1 ? ` (${dates[0]})` : ''})`,
},
tickmode: 'array', tickmode: 'array',
tickvals: ticks, tickvals: years,
ticktext: ticks.map(String), ticktext: years.map(String),
}, },
// at least 0–5 %: a near-zero probability reads as near zero, not as a full axis // At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: { yaxis: {
title: { text: 'Probabilidad (%)' }, title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, top * 110)], range: [0, Math.max(5, top * 110)],
@@ -91,3 +111,19 @@ export function curveFigure(models: CurveModel[], top: number): Figure {
}, },
} as Figure; } as Figure;
} }
/** The curves in words: each model, its index date and every horizon it publishes, with its
* interval where it has one. */
export function curveText(models: CurveModel[]): string[] {
return models
.filter((m) => m.predictions.length)
.map((m) => {
const sorted = [...m.predictions].sort((a, b) => a.years - b.years);
const said = sorted.map(
(p) =>
`${p.years === 0 ? 'al índice' : `${p.years} ${p.years === 1 ? 'año' : 'años'}`}: ${percent(p.p)} %` +
(interval(p) ? ` (IC 95 %: ${percent(p.low!)}–${percent(p.high!)} %)` : ''),
);
return `${title(m)} (fecha índice ${m.index}): ${said.join('; ')}.`;
});
}
-94
View File
@@ -1,94 +0,0 @@
@for (g of groups(); track $index) {
@if (g.title) {
<h3>{{ g.title }}</h3>
}
@for (s of g.scales; track s.label) {
<div class="scale" [attr.data-scale]="s.label">
<p>
<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' }} %
}
} @else {
· No disponible
}
</p>
<div class="plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="line" aria-hidden="true"></div>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
<span
class="interval"
[style.left.%]="r.low * 100"
[style.width.%]="(r.high - r.low) * 100"
aria-hidden="true"
></span>
}
<span class="marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
<strong
class="value"
[style.left]="'clamp(2.5rem, ' + r.p * 100 + '%, calc(100% - 2.5rem))'"
>{{ r.p * 100 | number: '1.1-2' }} %</strong
>
}
</div>
<div class="ticks" aria-hidden="true">
@for (t of [0, 25, 50, 75, 100]; track t) {
<span>{{ t }} %</span>
}
</div>
</div>
}
@if (g.index) {
<p class="muted foot">
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p>
}
@if (g.title && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (i of entries(g.inputs); track i[0]) {
<div>
<dt>{{ inputName(i[0]) }}</dt>
<dd>{{ inputValue(i[0], i[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</section>
}
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (i of entries(g.inputs); track i[0]) {
<div>{{ inputName(i[0]) }}: {{ inputValue(i[0], i[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
}
-84
View File
@@ -1,84 +0,0 @@
$ink: #17324d;
.scale {
margin: 8px 0 14px;
max-width: 740px;
p {
margin: 0;
}
}
.plot {
padding-top: 30px;
position: relative;
}
// four equal parts, low to high; survival reads the other way
.line {
background: linear-gradient(
to right,
#42a77e 0 25%,
#a8c243 25% 50%,
#df8640 50% 75%,
#c24269 75% 100%
);
height: 12px;
}
.survival .line {
background: linear-gradient(
to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
}
.unavailable .line {
background: repeating-linear-gradient(
to right,
#d9dfe2 0,
#d9dfe2 calc(25% - 1px),
#fff calc(25% - 1px),
#fff 25%
);
}
.interval {
border-left: 2px solid $ink;
border-right: 2px solid $ink;
height: 8px;
min-width: 2px;
position: absolute;
top: 32px;
&::before {
background: $ink;
content: '';
height: 2px;
left: 0;
position: absolute;
right: 0;
top: 3px;
}
}
.marker {
background: $ink;
bottom: -2px;
height: 20px;
position: absolute;
transform: translateX(-50%);
width: 3px;
}
.value {
color: $ink;
font-size: 13px;
position: absolute;
top: 1px;
transform: translateX(-50%);
white-space: nowrap;
}
.ticks {
display: flex;
font-size: 12px;
justify-content: space-between;
margin-top: 3px;
}
.foot {
font-size: 12px;
}
+85 -106
View File
@@ -1,125 +1,104 @@
import { curveFigure } from './risk-curve'; import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
import { group, hpvApart } from './record-groups';
import { horizon, riskGroups, survivalGroups, titleParts } from './risk-scales';
import { parseSeries, seriesName } from './risk-series';
import { insufficientText, sortUndrawn } from './survival';
describe('risk scales', () => { const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
it('take a horizon only as published, zero included, and an interval only when whole', () => {
const p = [ describe('the risk scales', () => {
{ years: 0, p: 0 }, it('keeps zero as a value, and a missing horizon as none', () => {
{ years: 5, p: 0.2, low: 0.3, high: 0.1 }, expect(horizon([at(0, 0), at(5, 0.5)], 0)).toMatchObject({ p: 0 });
{ years: 3, p: 1.4 }, expect(horizon([at(5, 0.5)], 0)).toBeUndefined(); // never taken from another horizon
]; expect(horizon([at(0, 0.02)], 5)).toBeUndefined();
expect(horizon(p, 0)).toEqual({ years: 0, p: 0 }); expect(horizon([], 5)).toBeUndefined();
expect(horizon(p, 5)).toEqual({ years: 5, p: 0.2 });
expect(horizon(p, 3)).toBeUndefined();
expect(horizon(p, 1)).toBeUndefined();
}); });
it('name a model by its outcome and scenario, and say both horizons even when none is known', () => { it('reads 0, 2, 50, 98 and 100 % as they are', () => {
expect(titleParts('Riesgo de CIN3+ en precolposcopía v2')).toEqual({ for (const p of [0, 0.02, 0.5, 0.98, 1]) expect(horizon([at(5, p)], 5)?.p).toBe(p);
title: 'Probabilidad de CIN3+', });
scenario: 'precolposcopía', it('a value outside 0 to 1 is not a prediction; an interval needs both ends inside 0 to 1', () => {
expect(horizon([at(5, 1.2)], 5)).toBeUndefined();
expect(horizon([at(5, -0.1)], 5)).toBeUndefined();
expect(horizon([at(5, Number.NaN)], 5)).toBeUndefined();
expect(horizon([at(5, 0.4, 0.3, 0.5)], 5)).toMatchObject({ low: 0.3, high: 0.5 });
expect(horizon([at(5, 0.4, 0.3)], 5)).toMatchObject({
p: 0.4,
low: undefined,
high: undefined,
}); });
expect(riskGroups([])[0].scales.map((s) => s.risk)).toEqual([undefined, undefined]); expect(horizon([at(5, 0.4, 0.6, 0.5)], 5)?.low).toBeUndefined();
expect(horizon([at(5, 0.4, -0.1, 0.5)], 5)?.low).toBeUndefined();
}); });
it('turn survival models (mortality) into S(t), the interval turned too', () => { it('draws both horizons of every model, each model with its own title and index day', () => {
const [g] = survivalGroups([ const groups = riskGroups([
{ {
text: 'Supervivencia v1', text: 'Supervivencia v3',
index: '2026-01-01', index: '2026-02-01',
predictions: [{ years: 5, p: 0.1, low: 0.05, high: 0.2 }], predictions: [at(0, 0), at(5, 0.5, 0.4, 0.6)],
}, },
{ 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', 'Recurrencia', 'Otro']);
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
const labels = ['Probabilidad inmediata (al índice)', 'Probabilidad a 5 años'];
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]);
expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]);
expect(groups[2].scales.map((s) => s.risk)).toEqual([undefined, undefined]);
});
it('with no model, both horizons are drawn unavailable', () => {
const [none, ...rest] = riskGroups([]);
expect(rest).toEqual([]);
expect(none.title).toBeUndefined();
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
['Probabilidad inmediata (al índice)', undefined],
['Probabilidad a 5 años', undefined],
]);
});
it('the PDF keeps its flat list, with no scale for a page with no model', () => {
expect(riskScales([])).toEqual([]);
expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([
'M, probabilidad inmediata',
'M, probabilidad a 5 años',
]); ]);
const risk = g.scales[0].risk!;
expect([risk.p, risk.low, risk.high].map((v) => +v!.toFixed(2))).toEqual([0.9, 0.8, 0.95]);
}); });
}); });
describe('risk curves', () => { describe('which models feed the risk scales', () => {
it('band an interval published at two horizons and bar one published at one', () => { it('excludes survival and recurrence estimates, which are not risks of the scales outcome', () => {
const banded = curveFigure( expect(['cacu.cin2_pim', 'cacu.cancer_pim', 'cacu.cin2_logistic'].every(isRiskModel)).toBe(
[ true,
{
text: 'Riesgo de CIN3+ v1',
index: '2026-01-01',
predictions: [
{ years: 0, p: 0.1, low: 0.05, high: 0.2 },
{ years: 5, p: 0.2, low: 0.1, high: 0.3 },
],
},
],
0.3,
); );
expect(banded.data.map((t) => t.name)).toEqual([ 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, undefined,
'IC 95 % Probabilidad de CIN3+',
'Probabilidad de CIN3+',
]); ]);
const point = curveFigure(
[{ text: 'x', index: '', predictions: [{ years: 5, p: 0.2, low: 0.1, high: 0.3 }] }],
0.3,
);
expect(point.data).toHaveLength(1);
expect((point.data[0] as { error_y?: object }).error_y).toBeTruthy();
}); });
}); });
describe('series and report gaps', () => { describe('survival scales', () => {
it('read a series as published and name the platform own as the hospital', () => { it('complements mortality and reverses interval bounds at every published horizon', () => {
const [s] = parseSeries({ const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
resourceType: 'Parameters', expect(g.survival).toBe(true);
parameter: [ expect(g.index).toBe('2026-01-01');
{ expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
name: 'series', expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
part: [ expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
{ name: 'id', valueString: 'institutional-CIN3+' },
{ name: 'source', valueString: 'Institucional' },
{ name: 'outcome', valueString: 'CIN3+' },
{
name: 'point',
part: [
{ name: 'years', valueInteger: 5 },
{ name: 'probability', valueDecimal: 0.04 },
],
},
],
},
],
});
expect(seriesName(s)).toBe('ISSSTELEON, CIN3+');
expect(s.points).toEqual([{ years: 5, p: 0.04, low: undefined, high: undefined }]);
}); });
it('tell a scenario short of deaths from one the report does not mention', () => { it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
const report = { const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
escenarios_sin_curvas: [{ escenario: 'A', n: 12, fallecidos: 1 }], expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
min_fallecidos_escenario: 5, .toEqual(inputs);
}; expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
const { insufficient, missing } = sortUndrawn(report, ['A', 'B']); .toBeUndefined();
expect(missing).toEqual(['B']);
expect(insufficientText(insufficient[0])).toBe(
'Datos insuficientes para trazar la curva (n = 12, fallecidos = 1; mínimo requerido: 5 fallecidos).',
);
});
it('keep the form apart from the study: antecedents, results, findings and HPV', () => {
const fact = (field: string, title: string, value: string) => ({
study: 'cervical_cytology',
field,
title,
value,
});
const { hpv, rest } = hpvApart([
fact('hpv', 'VPH', 'positivo'),
fact('screening_history', 'Detección', 'Subsecuente'),
fact('result', 'Resultado', 'LIEBG'),
fact('finding_trichomonas', 'Hallazgo: tricomonas', 'positivo'),
fact('findings', 'Texto', 'inflamación'),
]);
expect(hpv.map((f) => f.field)).toEqual(['hpv']);
expect(group(rest)).toEqual({
antecedents: { screening_history: 'Subsecuente' },
results: ['Resultado: LIEBG'],
findings: ['Texto del informe: inflamación', 'Tricomonas'],
});
}); });
}); });
+304 -100
View File
@@ -1,7 +1,7 @@
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core'; import { Component, input } from '@angular/core';
export interface Prediction { interface Prediction {
years: number; years: number;
p: number; p: number;
low?: number; low?: number;
@@ -11,81 +11,62 @@ export interface RiskScale {
label: string; label: string;
risk?: Prediction; risk?: Prediction;
} }
/** One model's scales: its title, scenario and index, what it was fed and who scored her. */
export interface RiskGroup {
title?: string;
scenario?: string;
index?: string;
/** S(t): its scale reads the other way (high is good) */
survival?: boolean;
inputs?: Record<string, unknown>;
model?: string;
evaluated?: string;
scales: RiskScale[];
}
interface Scored {
text: string;
index: string;
predictions: Prediction[];
inputs?: Record<string, unknown>;
evaluated?: string;
scenarios?: string[];
}
/** "Riesgo" as "probabilidad", its capital kept. */ /** Whether a model's estimate is a risk of the outcome the scales and curves draw. Survival (S(t)) and
const probability = (text: string) => * recurrence-free survival are estimates of another outcome, shown in their own analysis: they are
text.replace(/riesgo/gi, (w) => (w[0] === 'R' ? 'Probabilidad' : 'probabilidad')); * never drawn on these scales, and no conversion (1 − S) is made. */
const unit = (n?: number): n is number => typeof n === 'number' && n >= 0 && n <= 1; export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(model);
const years = (n: number) => `${n} ${n === 1 ? 'año' : 'años'}`;
/** A model's prediction at one horizon when it is a probability: zero is a value, a missing /** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
* horizon or a value outside 0–1 is none, and an interval stands only when it is whole. */ export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
export function horizon(predictions: Prediction[], at: number): Prediction | undefined {
const found = predictions.find((p) => p.years === at);
if (!found || !unit(found.p)) return undefined;
const whole = unit(found.low) && unit(found.high) && found.low <= found.high;
return whole ? found : { years: at, p: found.p };
}
/** Each model's probability at its index visit and at five years (the record's PDF). */
export function riskScales(models: Scored[]): RiskScale[] {
return models.flatMap((m) => return models.flatMap((m) =>
[0, 5].map((at) => ({ [0, 5].map((years) => ({
label: `${probability(m.text)}, probabilidad ${at ? 'a 5 años' : 'inmediata'}`, label: `${m.text.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'))}, probabilidad ${years ? 'a 5 años' : 'inmediata'}`,
risk: horizon(m.predictions, at), risk: m.predictions.find((p) => p.years === years),
})), })),
); );
} }
/** "Riesgo de X en <escenario> v1" as its outcome and its scenario. */ const unit = (n?: number): n is number => typeof n === 'number' && n >= 0 && n <= 1;
export function titleParts(text: string): { title: string; scenario?: string } {
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!; /** A model's published prediction at one horizon, when it is a probability: zero is a real value,
return { title: probability(title), scenario }; * a missing horizon is none (never taken from another horizon), a value outside 0 to 1 is none. */
export function horizon(predictions: Prediction[], years: number): Prediction | undefined {
const found = predictions.find((p) => p.years === years);
if (!found || !unit(found.p)) return undefined;
const interval = unit(found.low) && unit(found.high) && found.low <= found.high;
return {
...found,
low: interval ? found.low : undefined,
high: interval ? found.high : undefined,
};
} }
const HORIZONS: [number, string][] = [ /** One model's two horizons, each with its prediction or none. */
[0, 'Probabilidad inmediata (al índice)'], export interface RiskGroup {
[5, 'Probabilidad a 5 años'], /** the model's own title and the day it was scored (none: no model has scored her) */
]; title?: string;
scenario?: string;
/** Both horizons of every risk model; with no model, both horizons unavailable. */ index?: string;
export function riskGroups(models: Scored[]): RiskGroup[] { survival?: boolean;
const scales = (p: Prediction[]) => inputs?: Record<string, unknown>;
HORIZONS.map(([at, label]) => ({ label, risk: horizon(p, at) })); /** the model and version that scored her, and the day it did */
if (!models.length) return [{ scales: scales([]) }]; model?: string;
return models.map((m) => ({ evaluated?: string;
...titleParts(m.text), scales: { label: string; risk?: Prediction }[];
index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions),
}));
} }
/** Survival models publish mortality: their scales are its complement, S(t), interval swapped. */ /** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(models: Scored[]): RiskGroup[] { export function survivalGroups(
const complement = (n?: number) => (n === undefined ? undefined : 1 - n); models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
text?: string;
evaluated?: string;
}[],
): RiskGroup[] {
return models return models
.map((m) => ({ .map((m) => ({
title: 'Supervivencia', title: 'Supervivencia',
@@ -95,52 +76,275 @@ export function survivalGroups(models: Scored[]): RiskGroup[] {
model: m.text, model: m.text,
evaluated: m.evaluated, evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '), scenario: m.scenarios?.join(' · '),
scales: m.predictions scales: m.predictions.flatMap((p) => {
.map((p) => horizon(m.predictions, p.years)) const v = horizon(m.predictions, p.years);
.filter((v) => !!v) return v
.map((v) => ({ ? [
label: `Supervivencia a ${years(v.years)}`, {
risk: { years: v.years, p: 1 - v.p, low: complement(v.high), high: complement(v.low) }, label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
})), risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
})) }))
.filter((g) => g.scales.length); .filter((g) => g.scales.length);
} }
const INPUTS: Record<string, string> = { const HORIZONS: [number, string][] = [
age_group: 'Edad al diagnóstico', [0, 'Probabilidad inmediata (al índice)'],
cytology: 'Citología', [5, 'Probabilidad a 5 años'],
bethesda: 'Citología', ];
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
referral_grade: 'Citología de referencia',
};
/** A model input's value as the screens say it. */ /** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */
export function inputValue(name: string, value: unknown): string { export function titleParts(text: string): { title: string; scenario?: string } {
if (value === null || value === undefined) return 'No documentado'; const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
if (name === 'referral_grade' && (value === 'high' || value === 'low')) return {
return value === 'high' ? 'Alto grado' : 'Bajo grado'; title: title.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad')),
if (name.startsWith('hpv')) { scenario,
if (value === 1 || value === true || value === 'positive') return 'Positivo'; };
if (value === 0 || value === false || value === 'negative') return 'Negativo';
}
return String(value);
} }
/** Scales of 0 to 100 % in four equal parts (descriptive, not clinical thresholds), the /** The scales the page draws: both horizons of every model, or, with no model, both horizons
* probability marked with its interval; one with no prediction is grey and says so. */ * unavailable. */
export function riskGroups(
models: {
text: string;
index: string;
predictions: Prediction[];
inputs?: Record<string, unknown>;
evaluated?: string;
}[],
): RiskGroup[] {
const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
return models.length
? models.map((m) => ({
...titleParts(m.text),
index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions),
}))
: [{ scales: scales([]) }];
}
/** Segmented scales of 0 to 100 %. The four equal parts are numeric and descriptive: they do not
* stand for clinical thresholds. Without a prediction the bar is neutral grey, says it is not
* available and has no marker. */
@Component({ @Component({
selector: 'app-risk-scales', selector: 'app-risk-scales',
imports: [DecimalPipe], imports: [DecimalPipe],
templateUrl: './risk-scales.html', template: `
styleUrl: './risk-scales.scss', @for (g of groups(); track $index) {
@if (g.title) {
<h3>{{ g.title }}</h3>
}
@for (s of g.scales; track s.label) {
<div class="risk-scale" [attr.data-scale]="s.label">
<p>
<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' }}
%
}
} @else {
· No disponible
}
</p>
<div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<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"
[style.left]="'clamp(2.5rem, ' + r.p * 100 + '%, calc(100% - 2.5rem))'"
>{{ r.p * 100 | number: '1.1-2' }} %</strong
>
}
</div>
<div class="risk-labels" aria-hidden="true">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span>
</div>
</div>
}
@if (g.index) {
<p class="muted foot">
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p>
}
@if (g.title && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (item of entries(g.inputs); track item[0]) {
<div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</section>
}
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (item of entries(g.inputs ?? {}); track item[0]) {
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
}
`,
styles: `
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
}
.risk-scale p {
margin: 0;
}
.risk-plot {
padding-top: 30px;
position: relative;
}
.risk-line {
background: linear-gradient(
to right,
#42a77e 0 25%,
#a8c243 25% 50%,
#df8640 50% 75%,
#c24269 75% 100%
);
height: 16px;
}
.unavailable .risk-line {
background: repeating-linear-gradient(
to right,
#d9dfe2 0,
#d9dfe2 calc(25% - 1px),
#fff calc(25% - 1px),
#fff 25%
);
}
.survival .risk-line {
background: linear-gradient(
to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
}
.risk-interval {
border-left: 2px solid #17324d;
border-right: 2px solid #17324d;
height: 8px;
min-width: 2px;
position: absolute;
top: 20px;
}
.risk-interval::before {
background: #17324d;
content: '';
height: 2px;
left: 0;
position: absolute;
right: 0;
top: 3px;
}
.foot {
font-size: 12px;
}
.risk-marker {
background: #17324d;
bottom: -2px;
height: 20px;
position: absolute;
transform: translateX(-50%);
width: 3px;
}
.risk-value {
color: #17324d;
font-size: 13px;
position: absolute;
top: 1px;
transform: translateX(-50%);
white-space: nowrap;
}
.risk-labels {
display: flex;
font-size: 12px;
justify-content: space-between;
margin-top: 3px;
}
`,
}) })
export class RiskScales { export class RiskScales {
readonly groups = input.required<RiskGroup[]>(); readonly groups = input.required<RiskGroup[]>();
protected readonly entries = (o?: Record<string, unknown>) => Object.entries(o ?? {}); protected readonly entries = Object.entries;
protected readonly inputName = (name: string) => INPUTS[name] ?? name; protected readonly inputName = (name: string) =>
protected readonly inputValue = inputValue; (
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Citología de referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado';
if (name === 'referral_grade' && (value === 'high' || value === 'low'))
return value === 'high' ? 'Alto grado' : 'Bajo grado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
} }
+32
View File
@@ -0,0 +1,32 @@
import { parseSeries, seriesName } from './risk-series';
describe('risk series', () => {
it('reads each series and keeps an absent interval absent', () => {
const [series] = parseSeries({
resourceType: 'Parameters',
parameter: [
{
name: 'series',
part: [
{ name: 'id', valueString: 'cacu.cin2_pim' },
{ name: 'source', valueString: 'Institucional' },
{ name: 'outcome', valueString: 'CIN2+' },
{ name: 'status', valueCode: 'resolved' },
{
name: 'point',
part: [
{ name: 'years', valueInteger: 0 },
{ name: 'probability', valueDecimal: 0 },
],
},
],
},
],
});
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
'NCI, ingreso a LIEAG+',
);
});
});
+70 -40
View File
@@ -2,35 +2,54 @@ import { Component, computed, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
import { CurveChooser } from './curve-chooser'; import { CurveChooser } from './curve-chooser';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import type { Prediction } from './risk-scales';
/** One series of `$risk-series`: a source, an outcome, what it assumes and its points. */ 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 { export interface Series {
id: string; id: string;
source: string; source: string;
outcome: string; outcome: string;
label: string;
resolved: boolean;
reasons: string[];
assumptions: string[]; assumptions: string[];
points: Prediction[]; points: SeriesPoint[];
} }
const OUTCOMES: Record<string, string> = { 'CIN2+': 'LIEAG+', 'CIN3+': 'CIN3+', cancer: 'Cáncer' }; const OUTCOME_TEXT: Record<string, string> = {
/** Drawn until the user says otherwise: the platform's own and the NCI master table's CIN2+/3+. */ 'CIN2+': 'LIEAG+ (CIN2+)',
const SHOWN = new Set(['nci-master-CIN2+', 'nci-master-CIN3+']); 'CIN3+': 'CIN3+',
cancer: 'Cáncer',
};
/** "ISSSTELEON, CIN3+": the platform's own series are the hospital's. */ export const seriesName = (s: Series) => {
export const seriesName = (s: Series) => const outcome = OUTCOME_TEXT[s.outcome] ?? s.outcome;
`${s.source === 'Institucional' ? 'ISSSTELEON' : s.source}, ${OUTCOMES[s.outcome] ?? s.outcome}`; if (s.source === 'NCI (tabla de ingreso)')
return `NCI, ingreso a ${outcome.replace(' (CIN2+)', '').replace(/^Cáncer$/, 'cáncer')}`;
// the platform's own models are the hospital's: its name, and the outcome without its synonym
return s.source === 'Institucional'
? `ISSSTELEON, ${outcome.replace(' (CIN2+)', '')}`
: `${s.source} · ${outcome}`;
};
type Part = ParametersParameter; /** The series of the answer. A value absent from it stays absent. */
const all = (of: Part[] | undefined, name: string) => (of ?? []).filter((p) => p.name === name);
const one = (of: Part[] | undefined, name: string) => all(of, name)[0];
/** The answer's series; a value it leaves out stays out. */
export function parseSeries(answer: Parameters): Series[] { 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 }) => ({ return all(answer.parameter, 'series').map(({ part }) => ({
id: one(part, 'id')?.valueString ?? '', id: one(part, 'id')?.valueString ?? '',
source: one(part, 'source')?.valueString ?? '', source: one(part, 'source')?.valueString ?? '',
outcome: one(part, 'outcome')?.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 ?? ''), assumptions: all(part, 'assumption').map((a) => a.valueString ?? ''),
points: all(part, 'point').map(({ part: at }) => ({ points: all(part, 'point').map(({ part: at }) => ({
years: one(at, 'years')?.valueInteger ?? 0, years: one(at, 'years')?.valueInteger ?? 0,
@@ -41,47 +60,58 @@ export function parseSeries(answer: Parameters): Series[] {
})); }));
} }
/** Her series side by side, to choose from; no difference between them is computed. */ /** The chosen series as curves. Series are shown side by side; no difference is computed. */
@Component({ @Component({
selector: 'app-risk-series', selector: 'app-risk-series',
imports: [CurveChooser], imports: [CurveChooser],
template: ` template: `
@if (drawn().length) { @if (available().length) {
<app-curve-chooser [choices]="choices()" [draw]="draw" [notes]="assumptions" /> <app-curve-chooser [choices]="choices()" [draw]="draw()" [notes]="assumptions()" />
} @else { } @else {
<p class="muted">No disponible: datos insuficientes.</p> <p class="muted">No disponible: datos insuficientes.</p>
} }
`, `,
styles: `
:host {
display: block;
}
`,
}) })
export class RiskSeries { export class RiskSeries {
readonly series = input.required<Series[]>(); readonly series = input.required<Series[]>();
protected readonly drawn = computed(() => this.series().filter((s) => s.points.length)); protected readonly available = computed(() => this.series().filter((s) => s.points.length));
/** the platform's own series and the NCI master table's are drawn until the user says
* otherwise */
protected readonly choices = computed(() => protected readonly choices = computed(() =>
this.drawn().map((s) => ({ this.available().map((s) => ({
id: s.id, id: s.id,
name: seriesName(s), name: seriesName(s),
on: s.source === 'Institucional' || SHOWN.has(s.id), on: s.source === 'Institucional' || s.id === 'nci-master-CIN3+',
})), })),
); );
private chosen(ids: Set<string>) { private readonly among = computed(() => {
return this.drawn().filter((s) => ids.has(s.id)); const all = this.available();
} return (ids: Set<string>) => all.filter((s) => ids.has(s.id));
});
/** what the chosen series assume, each said once */ /** what the chosen series assume, each said once */
protected readonly assumptions = (ids: Set<string>) => [ protected readonly assumptions = computed(() => {
...new Set(this.chosen(ids).flatMap((s) => s.assumptions)), const chosen = this.among();
]; return (ids: Set<string>) => [...new Set(chosen(ids).flatMap((s) => s.assumptions))];
protected readonly draw = (ids: Set<string>) => { });
const shown = this.chosen(ids).map((s) => ({ protected readonly draw = computed(() => {
text: seriesName(s), const chosen = this.among();
index: '', return (ids: Set<string>) => {
predictions: s.points, const shown = chosen(ids).map((s) => ({
})); model: s.id,
const figure = curveFigure( text: seriesName(s),
shown, index: '',
Math.max(0, ...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p))), predictions: s.points,
); }));
// the sources share no index date: the axis says only the horizon const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' }; const figure = curveFigure(shown, top);
return figure; // sources do not share an index date: the axis says only the horizon
}; figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure;
};
});
} }
-116
View File
@@ -1,116 +0,0 @@
$line: #667b8a;
:host {
display: block;
}
ol {
display: flex;
gap: 6px;
list-style: none;
margin: 0;
padding: 0;
}
li {
position: relative;
}
// recorded: solid green; inferred: double blue; pending: pale; ambiguous: double rose;
// no data: an empty dashed circle
.node {
background: #fff;
border: 2px dashed $line;
border-radius: 50%;
box-sizing: border-box;
display: block;
height: 12px;
position: relative;
width: 12px;
z-index: 1;
}
.recorded {
background: #387b66;
border-style: solid;
}
.inferred {
background: #4269a0;
border-style: double;
}
.pending {
background: #fff1c9;
border-style: solid;
}
.ambiguous {
border-color: #a84460;
border-style: double;
}
// the detail: a column per stage across the width, the nodes joined by a line
ol.detail {
background: #fff;
border: 1px solid #dce3e7;
border-radius: 8px;
gap: 0;
padding: 18px 12px;
li {
flex: 1;
min-width: 0;
text-align: center;
}
li:not(:last-child)::after {
border-top: 1px solid $line;
content: '';
left: calc(50% + 9px);
position: absolute;
right: calc(-50% + 9px);
top: 9px;
}
.node {
height: 18px;
margin: 0 auto;
width: 18px;
}
}
.info {
color: #60717d;
display: flex;
flex-direction: column;
font-size: 12px;
gap: 3px;
overflow-wrap: anywhere;
padding: 8px 4px 0;
strong {
color: #243d4b;
}
}
.interval {
color: #365b69;
font-weight: 600;
}
.origin {
font-style: italic;
}
// narrow screens: the stages one under another
@media (max-width: 700px) {
ol.detail {
display: block;
li {
display: flex;
gap: 12px;
padding-bottom: 10px;
text-align: left;
}
li:not(:last-child)::after {
border-left: 1px solid $line;
border-top: 0;
bottom: 0;
left: 9px;
right: auto;
top: 18px;
}
.node {
flex: none;
margin: 0;
}
}
.info {
padding: 0;
}
}
+97 -24
View File
@@ -1,5 +1,5 @@
import { EXT } from '../fhir'; import { EXT } from '../fhir';
import { interval, route } from './stages'; import { between, interval, route } from './stages';
const ext = (name: string, value: object) => ({ url: EXT + name, ...value }); const ext = (name: string, value: object) => ({ url: EXT + name, ...value });
const cytology = (...extension: object[]): any => ({ effectiveDateTime: '2026-01-10', extension }); const cytology = (...extension: object[]): any => ({ effectiveDateTime: '2026-01-10', extension });
@@ -23,31 +23,104 @@ describe('the route of a cytology', () => {
expect(states('2026-02-15')[3]).toBe('pending'); expect(states('2026-02-15')[3]).toBe('pending');
expect(states('2026-01-15').slice(2)).toEqual(['unknown', 'unknown', 'unknown']); expect(states('2026-01-15').slice(2)).toEqual(['unknown', 'unknown', 'unknown']);
}); });
it('takes the states and sources the backend publishes, and the day a pending biopsy was asked', () => { });
const report = cytology(
ext('colposcopy-date', { valueDate: '2026-02-01' }), describe('the days between stages', () => {
ext('stage-colposcopy-state', { valueCode: 'ambiguous' }), it('counts whole days and says nothing for a missing or out-of-order day', () => {
ext('stage-colposcopy-source', { valueCode: 'clinical-note' }), expect(between('2026-01-10', '2026-02-01')).toBe(22);
ext('stage-colposcopy-source', { valueCode: 'not-a-source' }), expect(between('2026-01-10', '2026-01-10')).toBe(0);
ext('biopsy-request-date', { valueDate: '2026-02-03' }), expect(between(undefined, '2026-02-01')).toBeUndefined();
ext('stage-biopsy-state', { valueCode: 'pending' }), expect(between('2026-02-01', '2026-01-10')).toBeUndefined();
ext('stage-biopsy-source', { valueCode: 'biopsy-order' }), });
); it('writes a dash, never a zero, for a missing day, and marks an interval that rests on an inference', () => {
const [, , colposcopy, biopsy] = route(report, '2026-12-31'); expect(interval(undefined, '2026-02-01')).toBe('—');
expect(colposcopy).toMatchObject({ state: 'ambiguous', sources: ['clinical-note'] }); expect(interval('2026-01-10', undefined)).toBe('—');
expect(biopsy).toEqual({ expect(interval('2026-01-10', '2026-01-11')).toBe('1 día');
label: 'Reporte de biopsia', expect(interval('2026-01-10', '2026-02-01')).toBe('22 días');
state: 'pending', expect(interval('2026-01-10', '2026-02-01', true)).toBe('22 días (inferido)');
requested: '2026-02-03', });
sources: ['biopsy-order'], it('knows an ambiguous stage the backend does not publish yet', () => {
}); const report = cytology(ext('colposcopy-date', { valueDate: '2026-02-01' }));
expect(route(report, '2026-12-31').map((s) => s.state)).not.toContain('ambiguous');
}); });
}); });
describe('days between stages', () => { describe('the route by what the backend says of each stage', () => {
it('say a missing day as a dash, never zero, and mark an inferred one', () => { const full = (...more: object[]) =>
expect(interval('2026-01-01', undefined)).toBe('—'); cytology(
expect(interval('2026-01-01', '2026-01-02')).toBe('1 día'); ext('report-date', { valueDate: '2026-01-20' }),
expect(interval('2026-01-01', '2026-01-11', true)).toBe('10 días (inferido)'); ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('stage-colposcopy-state', { valueCode: 'inferred' }),
ext('stage-colposcopy-source', { valueCode: 'clinical-note' }),
ext('stage-colposcopy-source', { valueCode: 'biopsy-order' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-date', { valueDate: '2026-03-01' }),
ext('biopsy-link', { valueCode: 'recorded' }),
ext('stage-biopsy-state', { valueCode: 'recorded' }),
ext('stage-biopsy-source', { valueCode: 'biopsy-record' }),
ext('diagnosis-date', { valueDate: '2026-03-10' }),
ext('stage-diagnosis-state', { valueCode: 'inferred' }),
ext('stage-diagnosis-source', { valueCode: 'clinical-note' }),
...more,
);
it('carries the state and every source of each stage, and the form for the first two', () => {
const stages = route(full(), '2026-12-31');
expect(stages.map((s) => s.state)).toEqual([
'recorded',
'recorded',
'inferred',
'recorded',
'inferred',
]);
expect(stages.map((s) => s.sources)).toEqual([
['cytology-form'],
['cytology-form'],
['clinical-note', 'biopsy-order'],
['biopsy-record'],
['clinical-note'],
]);
});
it("an ambiguous or pending state is the backend's, and a source it does not know is dropped", () => {
const ambiguous = full().extension!.map((e: any) =>
e.url.endsWith('stage-biopsy-state') ? { ...e, valueCode: 'ambiguous' } : e,
);
expect(route({ ...full(), extension: ambiguous }, '2026-12-31')[3].state).toBe('ambiguous');
const odd = full(ext('stage-diagnosis-source', { valueCode: 'something-new' }));
expect(route(odd, '2026-12-31')[4].sources).toEqual(['clinical-note']);
const pending = cytology(
ext('stage-biopsy-state', { valueCode: 'pending' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-link', { valueCode: 'inferred' }),
ext('stage-biopsy-source', { valueCode: 'date-association' }),
);
const biopsy = route(pending, '2026-12-31')[3];
expect(biopsy).toMatchObject({
state: 'pending',
requested: '2026-02-01',
sources: ['date-association'],
});
expect(biopsy.day).toBeUndefined();
});
it('by a cut-off before a stage its state is not known, and one before the report is pending', () => {
const early = route(full(), '2026-01-25');
expect(early.slice(2).map((s) => s.state)).toEqual(['unknown', 'unknown', 'unknown']);
expect(early.slice(2).map((s) => s.sources)).toEqual([undefined, undefined, undefined]);
const between = route(full(), '2026-02-15')[3];
expect(between).toMatchObject({ state: 'pending', requested: '2026-02-01' });
});
it('a request with no biopsy day and no pending state is not read as pending when the backend speaks', () => {
// reported outside the route's horizon: the backend gives the request and no biopsy state
const outside = cytology(
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('stage-colposcopy-state', { valueCode: 'inferred' }),
);
expect(route(outside, '2026-12-31')[3].state).toBe('unknown');
// a report with no state extensions: the request alone reads as pending
const older = cytology(ext('biopsy-request-date', { valueDate: '2026-02-01' }));
expect(route(older, '2026-12-31')[3].state).toBe('pending');
});
it('an ambiguous stage rests no interval on its day', () => {
expect(interval(undefined, '2026-03-01')).toBe('—');
}); });
}); });
+174 -43
View File
@@ -2,18 +2,19 @@ import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4'; import type { DiagnosticReport } from 'fhir/r4';
import { EXT, ext } from '../fhir'; import { EXT, ext } from '../fhir';
/** A step of the route a cytology starts. A stage with no day is unknown; `ambiguous` is a day /** A step of the route that a cytology starts. A day with no state is unknown. `ambiguous` is how
* the backend does not stand behind. */ * the page would draw a step the backend flagged as ambiguous; the current contract never does. */
export interface Stage { export interface Stage {
label: string; label: string;
day?: string; day?: string;
state: 'recorded' | 'inferred' | 'pending' | 'ambiguous' | 'unknown'; state: 'recorded' | 'inferred' | 'pending' | 'ambiguous' | 'unknown';
/** where its day comes from, as the backend says it (`SOURCES`) */ /** where the stage's day comes from, as the backend says it (see `SOURCES`); none: not said */
sources?: string[]; sources?: string[];
/** a stage with no day yet: the day its biopsy was requested */ /** what a stage without a day knows: a biopsy requested on this day */
requested?: string; requested?: string;
} }
/** Where a stage's day comes from. */
export const SOURCES: Record<string, string> = { export const SOURCES: Record<string, string> = {
'cytology-form': 'Formulario de citología', 'cytology-form': 'Formulario de citología',
'clinical-note': 'Nota clínica', 'clinical-note': 'Nota clínica',
@@ -21,6 +22,7 @@ export const SOURCES: Record<string, string> = {
'biopsy-record': 'Registro de la biopsia (nombra la citología)', 'biopsy-record': 'Registro de la biopsia (nombra la citología)',
'date-association': 'Asociación por fechas', 'date-association': 'Asociación por fechas',
}; };
export const STATES: Record<Stage['state'], string> = { export const STATES: Record<Stage['state'], string> = {
recorded: 'Registrada', recorded: 'Registrada',
inferred: 'Inferida por fechas', inferred: 'Inferida por fechas',
@@ -28,39 +30,55 @@ export const STATES: Record<Stage['state'], string> = {
ambiguous: 'Ambigua', ambiguous: 'Ambigua',
unknown: 'Sin dato', unknown: 'Sin dato',
}; };
const SAID: Stage['state'][] = ['recorded', 'inferred', 'ambiguous'];
const FORM = ['cytology-form'];
/** The route of one cytology by `cutoff`. Each later stage's state and sources are the backend's /** The route of one cytology, as its report says it, by `cutoff`. The backend says each later
* (`stage-<name>-state`, `stage-<name>-source`); a report without them is read from its days and * stage's state and sources (`stage-<name>-state`, `stage-<name>-source`); a report without them
* its biopsy link. */ * is read from its days and the biopsy link. */
export function route(cytology: DiagnosticReport | undefined, cutoff: string): Stage[] { export function route(cytology: DiagnosticReport | undefined, cutoff: string): Stage[] {
const by = (day?: string) => (day && day.slice(0, 10) <= cutoff ? day.slice(0, 10) : undefined); const by = (day?: string) => (day && day.slice(0, 10) <= cutoff ? day.slice(0, 10) : undefined);
const at = (name: string) => by(ext(cytology, name)?.valueDate); const at = (name: string) => by(ext(cytology, name)?.valueDate);
const said = (k: string) => ext(cytology, `stage-${k}-state`)?.valueCode as Stage['state']; const said = (k: string) => ext(cytology, `stage-${k}-state`)?.valueCode;
const sources = (k: string) => const published = ['colposcopy', 'biopsy', 'diagnosis'].some((k) => said(k));
const from = (k: string) =>
(cytology?.extension ?? []) (cytology?.extension ?? [])
.filter((e) => e.url === `${EXT}stage-${k}-source` && e.valueCode! in SOURCES) .filter((e) => e.url === EXT + `stage-${k}-source`)
.map((e) => e.valueCode!); .map((e) => e.valueCode!)
const stage = (label: string, day: string | undefined, state: Stage['state'], from: string[]) => .filter((c) => c in SOURCES);
day ? { label, day, state, sources: from } : { label, state: 'unknown' as const }; const KNOWN: Stage['state'][] = ['recorded', 'inferred', 'pending', 'ambiguous'];
const later = (label: string, k: string, otherwise: Stage['state']): Stage => /** A stage's state by what the backend says (or, with nothing said, by `otherwise`). */
stage(label, at(`${k}-date`), SAID.includes(said(k)) ? said(k) : otherwise, sources(k)); const later = (
const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded'; label: string,
const biopsy = later('Reporte de biopsia', 'biopsy', linked ? 'recorded' : 'inferred'); k: string,
day: string | undefined,
otherwise: Stage['state'],
): Stage => {
const state = said(k) as Stage['state'] | undefined;
const found = state && KNOWN.includes(state) && state !== 'pending' ? state : otherwise;
return { label, day, state: day ? found : 'unknown', sources: day ? from(k) : undefined };
};
const day = (label: string, d: string | undefined, sources: string[]): Stage => ({
label,
day: d,
state: d ? 'recorded' : 'unknown',
sources: d ? sources : undefined,
});
const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded' ? 'recorded' : 'inferred';
const biopsy = later('Reporte de biopsia', 'biopsy', at('biopsy-date'), linked);
const requested = at('biopsy-request-date'); const requested = at('biopsy-request-date');
// asked by the cut-off and unreported by it: pending, as the backend says, or reported after const reportedAfter = !!ext(cytology, 'biopsy-date')?.valueDate && !biopsy.day;
// the cut-off, or with no states published at all // asked by the cut-off and not reported by it: pending (the backend's pending, or a report after the
const published = ['colposcopy', 'biopsy', 'diagnosis'].some(said); // cut-off); a report with no states at all reads a request with no day as pending
const reportedLater = !!ext(cytology, 'biopsy-date')?.valueDate; if (!biopsy.day && requested && (reportedAfter || said('biopsy') === 'pending' || !published)) {
if (!biopsy.day && requested && (reportedLater || said('biopsy') === 'pending' || !published)) biopsy.state = 'pending';
Object.assign(biopsy, { state: 'pending', requested, sources: sources('biopsy') }); biopsy.requested = requested;
biopsy.sources = from('biopsy');
}
return [ return [
stage('Toma de muestra', by(cytology?.effectiveDateTime), 'recorded', FORM), day('Toma de muestra', by(cytology?.effectiveDateTime), ['cytology-form']),
stage('Resultado de citología', at('report-date'), 'recorded', FORM), day('Resultado de citología', at('report-date'), ['cytology-form']),
later('Colposcopía', 'colposcopy', 'inferred'), later('Colposcopía', 'colposcopy', at('colposcopy-date'), 'inferred'),
biopsy, biopsy,
later('Diagnóstico', 'diagnosis', 'inferred'), later('Diagnóstico', 'diagnosis', at('diagnosis-date'), 'inferred'),
]; ];
} }
@@ -70,16 +88,17 @@ export function between(from?: string, to?: string): number | undefined {
return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000); return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);
} }
/** Days between two stages as text: "—" for a missing day (never zero), "(inferido)" when it /** Days between two stages as text: "—" for a missing day (never a zero), and "(inferido)" when the
* rests on a stage inferred from dates. */ * interval rests on a stage that is only inferred from dates. */
export function interval(from?: string, to?: string, inferred = false): string { export function interval(from?: string, to?: string, inferred = false): string {
const days = between(from, to); const days = between(from, to);
if (days === undefined) return '—'; return days === undefined
return `${days} ${days === 1 ? 'día' : 'días'}${inferred ? ' (inferido)' : ''}`; ? '—'
: `${days} ${days === 1 ? 'día' : 'días'}${inferred ? ' (inferido)' : ''}`;
} }
/** The stages as nodes on a line; `detail` adds each one's state, day, source and the days since /** The stages as a line of nodes joined by a line; `detail` adds each one's state, day and the
* the stage before and since the sample. */ * days elapsed since the previous stage and since the sample. */
@Component({ @Component({
selector: 'app-stages', selector: 'app-stages',
template: ` template: `
@@ -94,7 +113,7 @@ export function interval(from?: string, to?: string, inferred = false): string {
<span>{{ <span>{{
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha') s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
}}</span> }}</span>
@if (s.origin) { @if (s.origin && s.origin !== 'Formulario de citología') {
<span class="origin">Procedencia: {{ s.origin }}</span> <span class="origin">Procedencia: {{ s.origin }}</span>
} }
<span class="interval">Desde anterior: {{ s.previous }}</span> <span class="interval">Desde anterior: {{ s.previous }}</span>
@@ -105,7 +124,123 @@ export function interval(from?: string, to?: string, inferred = false): string {
} }
</ol> </ol>
`, `,
styleUrl: './stages.scss', styles: `
:host {
display: block;
}
ol {
display: flex;
gap: 6px;
list-style: none;
margin: 0;
padding: 0;
}
li {
position: relative;
}
/* the states: recorded is solid green, inferred double blue, pending a pale solid, ambiguous a
double rose border, and what has no data a dashed empty circle */
.node {
background: #fff;
border: 2px dashed #667b8a;
border-radius: 50%;
box-sizing: border-box;
display: block;
height: 12px;
position: relative;
width: 12px;
z-index: 1;
}
.recorded {
background: #387b66;
border-style: solid;
}
.inferred {
background: #4269a0;
border-style: double;
}
.pending {
background: #fff1c9;
border-style: solid;
}
.ambiguous {
border-color: #a84460;
border-style: double;
}
/* the detail: one column per stage across the whole width, the nodes joined by a line */
ol.detail {
background: #fff;
border: 1px solid #dce3e7;
border-radius: 8px;
gap: 0;
padding: 18px 12px;
}
.detail li {
flex: 1;
min-width: 0;
text-align: center;
}
.detail .node {
height: 18px;
margin: 0 auto;
width: 18px;
}
.detail li:not(:last-child)::after {
border-top: 1px solid #667b8a;
content: '';
left: calc(50% + 9px);
position: absolute;
right: calc(-50% + 9px);
top: 9px;
}
.info {
color: #60717d;
display: flex;
flex-direction: column;
font-size: 12px;
gap: 3px;
overflow-wrap: anywhere;
padding: 8px 4px 0;
}
.info strong {
color: #243d4b;
}
.interval {
color: #365b69;
font-weight: 600;
}
.origin {
font-style: italic;
}
@media (max-width: 700px) {
ol.detail {
display: block;
}
.detail li {
display: flex;
gap: 12px;
padding-bottom: 10px;
text-align: left;
}
.detail li:not(:last-child)::after {
border-left: 1px solid #667b8a;
border-top: 0;
bottom: 0;
left: 9px;
right: auto;
top: 18px;
}
.detail .node {
flex: none;
margin: 0;
}
.info {
padding: 0;
}
}
`,
}) })
export class Stages { export class Stages {
readonly stages = input.required<Stage[]>(); readonly stages = input.required<Stage[]>();
@@ -113,17 +248,13 @@ export class Stages {
protected readonly shown = computed(() => { protected readonly shown = computed(() => {
const all = this.stages(); const all = this.stages();
const inferred = (s?: Stage) => s?.state === 'inferred'; const inferred = (s?: Stage) => s?.state === 'inferred';
// no interval rests on an ambiguous day // an ambiguous stage has a day the backend does not stand behind: no interval rests on it
const day = (s?: Stage) => (s?.state === 'ambiguous' ? undefined : s?.day); const day = (s?: Stage) => (s?.state === 'ambiguous' ? undefined : s?.day);
return all.map((s, i) => ({ return all.map((s, i) => ({
...s, ...s,
text: STATES[s.state], text: STATES[s.state],
title: `${s.label}: ${STATES[s.state]}`, title: `${s.label}: ${STATES[s.state]}`,
// every sample's day comes from its form: only another source is said origin: (s.sources ?? []).map((c) => SOURCES[c]).join(' · '),
origin: (s.sources ?? [])
.filter((c) => c !== 'cytology-form')
.map((c) => SOURCES[c])
.join(' · '),
previous: i ? interval(day(all[i - 1]), day(s), inferred(s) || inferred(all[i - 1])) : '—', previous: i ? interval(day(all[i - 1]), day(s), inferred(s) || inferred(all[i - 1])) : '—',
sample: interval(day(all[0]), day(s), inferred(s)), sample: interval(day(all[0]), day(s), inferred(s)),
})); }));
-110
View File
@@ -1,110 +0,0 @@
<mat-card appearance="outlined" data-section="supervivencia">
<mat-card-header>
<mat-card-title>{{ cacu() ? 'Supervivencia' : 'Riesgo de muerte' }}</mat-card-title>
</mat-card-header>
<mat-card-content>
@if (cacu()) {
<app-risk-scales [groups]="scales()" />
@for (g of scales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
@if (v.risk; as r) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ r.years }} {{ r.years === 1 ? 'año' : 'años' }}</td>
<td>{{ r.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (r.low !== undefined && r.high !== undefined) {
{{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }} %
} @else {
—
}
</td>
</tr>
}
}
</tbody>
</table>
</details>
}
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.curves) {
<p class="muted">
Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 % Greenwood;
n = {{ c.n }}, fallecidos = {{ c.deaths }}).
</p>
<app-curve-chooser [choices]="c.curves.choices" [draw]="c.curves.draw" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else {
<h3>Análisis de supervivencia</h3>
@if (loading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (analysis(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@if (s.methods.length) {
<details>
<summary>Métodos</summary>
<ul class="scenarios">
@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" />
}
@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 (failed()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else {
<p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
}
}
</mat-card-content>
</mat-card>
-61
View File
@@ -1,61 +0,0 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { Api } from '../api/api';
import { Loading } from '../loading';
import { Plot } from '../plot';
import { Analysis, combination } from './analysis';
import { CurveChooser } from './curve-chooser';
import { Factores } from './factores';
import type { Model } from './record';
import { RiskScales, survivalGroups } from './risk-scales';
import { insufficientText } from './survival';
/** Her survival. CaCu: her S(t) at each horizon, its values and the Kaplan-Meier of the patients
* who share her values; elsewhere, the curves of her clinical scenarios. */
@Component({
selector: 'app-survival-card',
imports: [CurveChooser, DecimalPipe, Factores, Loading, MatCardModule, Plot, RiskScales],
templateUrl: './survival-card.html',
styles: `
mat-card-content {
overflow-x: auto;
}
.scenarios {
display: flex;
flex-wrap: wrap;
gap: 6px 8px;
list-style: none;
margin: 0 0 12px;
padding: 0;
li {
background: var(--color-action-hover, #f1f6f6);
border: 1px solid var(--color-border);
border-radius: 999px;
font-size: 13px;
padding: 2px 10px;
}
}
`,
})
export class SurvivalCard {
private readonly api = inject(Api);
readonly domain = input.required<string>();
/** her survival models */
readonly models = input.required<Model[]>();
/** her scenarios' curves, as read (not CaCu) */
readonly analysis = input<Analysis>();
readonly loading = input(false);
readonly failed = input(false);
protected readonly cacu = computed(() => this.domain() === 'cacu');
protected readonly scales = computed(() => (this.cacu() ? survivalGroups(this.models()) : []));
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.cacu() && m ? { ...m, inputs: m.inputs! } : undefined;
},
loader: ({ params }) => combination(this.api, params),
});
protected readonly insufficientText = insufficientText;
}

Some files were not shown because too many files have changed in this diff Show More