Compare commits

...

54 Commits

Author SHA1 Message Date
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
76 changed files with 5204 additions and 543 deletions
+16 -16
View File
@@ -9,13 +9,13 @@ test.beforeEach(async ({ page }) => {
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', 'Por estatus de seguimiento', ROUND.name];
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: 'Valor predictivo positivo de la colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia',
colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
};
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
@@ -28,19 +28,19 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje',
expect(headings.slice(headings.indexOf('Indicadores clínicos'))).toEqual([
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
'Tasa de confirmación histopatológica de referencia a colposcopía',
'Indicadores de oportunidad',
'Tiempos de tamizaje',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
const route = tab.locator('app-readings').filter({ has: page.getByRole('heading', { name: 'Tiempos de tamizaje' }) });
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 expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
@@ -105,14 +105,14 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
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 }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
@@ -187,7 +187,7 @@ async function withRounds(page: Page, how: Simulation) {
}
/** 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>n = N", the width of the first bar and the colour of
/** 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) => {
@@ -202,7 +202,7 @@ const traces = (readings: Locator) =>
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>n = ${g.querySelector('.n')!.textContent!.replace('n = ', '').trim()}`,
`${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(
@@ -277,7 +277,7 @@ for (const card of ['cytology', 'genotype'] as const) {
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>n = 0');
expect(found.y[0]).toBe('Detección inicial<br>Pacientes: 0');
expect(found.x[0]).toBe(0);
});
@@ -307,7 +307,7 @@ test('rondas (simulado): the genotype card never shows the incomplete positives,
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo',
'Positivo sin genotipo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
+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);
});
+743 -31
View File
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
/** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!;
@@ -118,17 +118,18 @@ async function open(page: Page, url: string) {
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
}
test('ficha (simulado): states why a hysterectomy makes this risk assessment unavailable', async ({
test('ficha (simulado): uses the recorded hysterectomy when eligibility is unavailable', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
const previousDay = plus(sample, -1);
await eligibilityIs(page, {}, 503);
await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
const response = await route.fetch();
const patient = await response.json();
patient.extension = [
...(patient.extension ?? []),
{ url: EXT + 'first-hysterectomy-recorded', valueDate: sample },
{ url: EXT + 'first-hysterectomy-recorded', valueDate: sample.slice(0, 10) },
];
await route.fulfill({ response, json: patient });
});
@@ -136,7 +137,7 @@ test('ficha (simulado): states why a hysterectomy makes this risk assessment una
await open(page, url);
await expect(
page.getByText('Sin estimación de riesgo por antecedente de histerectomía', {
page.getByText('No disponible por: histerectomía registrada el', {
exact: false,
}),
).toBeVisible();
@@ -321,11 +322,11 @@ test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tel
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [
[0, 0],
[5, 0.5, 0.4, 0.6],
]),
risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [
risk('b', 'Recurrencia v2', 'cacu.cancer_pim', '2026-03-01', [
[0, 0.02, 0.01, 0.03],
[5, 0.98, 0.95, 1],
]),
@@ -373,7 +374,7 @@ test('ficha (simulado): the scale is drawn in four equal segments with the numer
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
]);
await open(page, url);
const box = scale(page, FIVE);
@@ -415,7 +416,7 @@ for (const width of [1440, 480]) {
link: 'recorded',
});
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
risk('a', 'Supervivencia v3', 'cacu.cin2_pim', '2026-02-01', [
[0, 0],
[5, 0.98, 0.95, 1],
]),
@@ -703,6 +704,7 @@ function fixture(
part: [
part('id', { valueString: 'fixture-table' }),
part('file', { valueString: 'fixture.xlsx' }),
part('outcome', { valueCode: 'CIN3+' }),
],
}),
...more,
@@ -745,7 +747,7 @@ test('referencia NCI: a resolved cytology shows its reference with scenario, sou
await expect(box).toContainText('Tamizaje');
await expect(box).toContainText('CIN3 o más grave (CIN3+)');
await expect(box).toContainText('Master_NCI_Risk_Table.xlsx');
const rows = box.locator('tbody tr');
const rows = box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr');
await expect(rows).toHaveCount(2);
await expect(rows.first()).toContainText('Inmediato (al índice)');
await expect(rows.nth(1)).toContainText('5 años');
@@ -756,10 +758,13 @@ test('referencia NCI: a resolved cytology shows its reference with scenario, sou
(h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2),
);
for (const [i, pct] of expected.entries())
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`);
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
await expect(rows.nth(i).locator('td').nth(1)).toContainText(`${pct} %`);
// no model evaluated her: said once, not on every horizon
await expect(box.locator('.nomodel')).toContainText('No disponible');
await expect(box.getByText('Ningún modelo institucional ha evaluado a la paciente.')).toHaveCount(
1,
);
await expect(box.locator('[data-model]')).toHaveCount(0);
// the antecedents used are collapsed
const used = box.locator('details.used');
expect(await used.getAttribute('open')).toBeNull();
@@ -832,13 +837,17 @@ test('referencia NCI (simulado): a comparison that is valid shows the difference
]),
);
await open(page, url);
const row = section(page).locator('tbody tr').first();
await expect(row).toContainText('Modelo de prueba');
const block = section(page).locator('[data-model]');
await expect(block.locator('h5')).toContainText('Modelo de prueba');
await expect(block.locator('h5')).toContainText('CIN3 o más grave (CIN3+)');
const row = block.locator('tbody tr').first();
await expect(row).toContainText('1.27 %');
await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
await expect(row.locator('td').nth(3)).toContainText('+1.00');
await expect(row.locator('td').nth(3)).not.toContainText('No comparable');
await expect(
section(page).locator('table').first().locator('tbody tr').first().locator('td').nth(1),
).toContainText('0.27 %');
await expect(row.locator('td').nth(2)).toContainText('+1.00');
await expect(row.locator('td').nth(2)).not.toContainText('No comparable');
});
test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({
@@ -863,15 +872,15 @@ test('referencia NCI (simulado): another outcome or horizon is "No comparable" w
]),
);
await open(page, url);
const first = section(page).locator('tbody tr').first();
await expect(first.locator('td').nth(3)).toContainText('No comparable');
await expect(first.locator('td').nth(3)).toContainText(
const first = section(page).locator('[data-model] tbody tr').first();
await expect(first.locator('td').nth(2)).toContainText('No comparable');
await expect(first.locator('td').nth(2)).toContainText(
'El desenlace del modelo no es el de la tabla (CIN3+)',
);
await expect(first.locator('td').nth(3)).toContainText(
await expect(first.locator('td').nth(2)).toContainText(
'no publica una predicción a este horizonte',
);
await expect(first.locator('td').nth(3)).not.toContainText(/[+-]\d/); // no signed difference
await expect(first.locator('td').nth(2)).not.toContainText(/[+-]\d/); // no signed difference
await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted
});
@@ -881,12 +890,12 @@ test('referencia NCI (simulado): a year-one reference is a year, never the immed
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
await open(page, url);
const rows = section(page).locator('tbody tr');
const rows = section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr');
await expect(rows.first()).toContainText('1 año');
await expect(section(page)).not.toContainText('Inmediato');
await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %');
await expect(rows.nth(1).locator('td').nth(1)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(1)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(1)).toContainText('1.36 %');
});
for (const width of [1440, 480]) {
@@ -929,12 +938,12 @@ for (const width of [1440, 480]) {
),
);
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
@@ -956,12 +965,12 @@ test('curvas (simulado): one series per model at its published horizons, its ban
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
risk('b', 'Riesgo cáncer v2', 'cacu.cancer_pim', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
@@ -1003,3 +1012,706 @@ test('curvas (simulado): one series per model at its published horizons, its ban
).not.toContain('0.27');
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
});
// ---- the grouped NCI comparison, the survival texts and the risk-model selection (all "simulado") ------
const SHOTS = process.env['SHOTS_DIR']; // when set, the simulated pages are saved for the report
const shot = async (page: Page, name: string, kind = 'SIMULADO') => {
if (SHOTS) await page.screenshot({ path: `${SHOTS}/${kind}-${name}.png`, fullPage: true });
};
const institutional = (p: number, low?: number, high?: number, diff?: number) => [
part('institutional', { valueDecimal: p }),
...(low === undefined ? [] : [part('institutional-low', { valueDecimal: low })]),
...(high === undefined ? [] : [part('institutional-high', { valueDecimal: high })]),
...(diff === undefined ? [] : [part('difference-pp', { valueDecimal: diff })]),
];
const model = (
code: string,
title: string,
outcome: string,
status: string,
reasons: string[],
extra: object[] = [],
) =>
part('comparison', {
part: [
part('model', { valueCode: code }),
part('title', { valueString: title }),
part('outcome', { valueString: outcome }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const SHARED = ['index_date_differs', 'population_not_verified'];
for (const width of [1440, 480]) {
test(`referencia NCI (simulado) at ${width} px: several models, outcomes and horizons are grouped without losing any`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await answerWith(
page,
fixture(
[
{
years: 0,
reference: 0.0001,
comparison: [
model(
'cacu.cin2_pim',
'Riesgo LIEAG+',
'CIN2+',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.05, 0.03, 0.08),
),
model(
'cacu.cancer_pim',
'Riesgo de cáncer',
'cancer',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.002),
),
model(
'cacu.cin2_logistic',
'Riesgo LIEAG+ a un año',
'CIN2+ within one year',
'not_comparable',
['horizon_not_published_by_model', 'outcome_differs', ...SHARED],
),
],
},
{
years: 1,
comparison: [
model(
'cacu.cin2_logistic',
'Riesgo LIEAG+ a un año',
'CIN2+ within one year',
'not_comparable',
['no_reference', 'outcome_differs', ...SHARED],
institutional(0.04),
),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
model(
'cacu.cin2_pim',
'Riesgo LIEAG+',
'CIN2+',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.12, 0.08, 0.17),
),
model(
'cacu.cancer_pim',
'Riesgo de cáncer',
'cancer',
'not_comparable',
['outcome_differs', ...SHARED],
institutional(0.011, 0.006, 0.02),
),
model(
'cacu.cin3_fixture',
'Modelo CIN3+ de prueba',
'CIN3+',
'comparable',
[],
institutional(0.0127, 0.005, 0.02, 1),
),
],
},
],
[part('assumption', { valueString: 'un supuesto sin verificar' })],
),
);
await open(page, url);
const box = section(page);
// the outcome of the reference comes from the answer; the models' are translated for display only
await expect(box).toContainText('Desenlace de la referencia');
const blocks = box.locator('[data-model]');
await expect(blocks).toHaveCount(4);
await expect(blocks.locator('h5 [data-outcome="cancer"]')).toHaveText('Cáncer');
await expect(blocks.locator('h5 [data-outcome="CIN2+ within one year"]')).toHaveText(
'CIN2+ en un año',
);
await expect(blocks.locator('h5 [data-outcome="CIN2+"]')).toContainText('CIN2');
// the reference is one table; each model keeps its own horizons, values and intervals
await expect(
box.locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'),
).toHaveCount(3);
const pim = box.locator('[data-model="cacu.cin2_pim"] tbody tr');
await expect(pim).toHaveCount(2);
await expect(pim.first()).toContainText('5.00 %');
await expect(pim.first()).toContainText('IC 95 %: 3.00–8.00 %');
await expect(pim.nth(1)).toContainText('12.00 %');
// an absent interval stays absent; a missing value says so
await expect(box.locator('[data-model="cacu.cancer_pim"] tbody tr').first()).not.toContainText(
'IC 95 %',
);
await expect(box.locator('[data-model="cacu.cin2_logistic"] tbody tr').first()).toContainText(
'No disponible',
);
// reasons every incompatible comparison gives are said once, not on each row
const common = box.locator('ul[aria-label="Motivos comunes"] li');
await expect(common).toHaveCount(3); // outcome_differs is in every incompatible row too
await expect(
box.getByText('La fecha índice del modelo no es la de la citología evaluada.'),
).toHaveCount(1);
// a difference only on the valid comparison
const valid = box.locator('[data-model="cacu.cin3_fixture"] tbody tr');
await expect(valid.locator('td').nth(2)).toContainText('+1.00');
await expect(
box.locator('[data-model="cacu.cin2_pim"] tbody td:nth-child(3)').first(),
).not.toContainText(/[+-]\d/);
// the reasons of one horizon only stay on that row
await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText(
'no publica una predicción a este horizonte',
);
await expect(box.locator('[data-model="cacu.cin2_logistic"]')).toContainText(
'no dan un riesgo a este horizonte',
);
await box.locator('details.used summary').click();
await page.waitForTimeout(600);
expect(await layoutProblems(page)).toEqual([]);
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
await shot(page, `referencia-nci-agrupada-${width}`);
});
}
test('referencia NCI (simulado): with no institutional model it says so once; the reference stays', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 0,
reference: 0.0001,
comparison: [
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
},
]),
);
await open(page, url);
await expect(
section(page).getByText('Ningún modelo institucional ha evaluado a la paciente.'),
).toHaveCount(1);
await expect(
section(page).locator('table[aria-label="Referencia NCI por horizonte"] tbody tr'),
).toHaveCount(2);
await shot(page, 'referencia-nci-sin-modelos');
});
const scenarioReport = (name: string, n: number, deaths: number) => ({
escenario: name,
n,
fallecidos: deaths,
horizons_months: [12, 36, 60],
km: {
months: [0, 12, 36, 60],
S: [1, 0.92, 0.8, 0.7],
low: [1, 0.85, 0.7, 0.55],
high: [1, 0.97, 0.9, 0.82],
},
weibull: { t: [0, 12, 36, 60], S: [1, 0.93, 0.81, 0.69] },
weibull_fractional: { t: [0, 12, 36, 60], S: [1, 0.91, 0.79, 0.71] },
points: { COMB: { S: [0.92, 0.8, 0.7], low: [0.85, 0.7, 0.55], high: [0.97, 0.9, 0.82] } },
});
async function withSurvival(
page: Page,
domain: 'cacu' | 'cama',
others: object[] = [],
report?: object,
scenarios = ['Edad al diagnóstico · 45-54 años', 'VPH positivo'],
) {
const assessed = {
...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]),
extension: scenarios.map((valueString) => ({ url: EXT + 'escenario-clinico', valueString })),
};
await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: [assessed, ...others].map((resource) => ({ resource })),
}),
}),
);
await page.route(
`**/api/models/${domain}/survival/versions/*/reports/interpretability`,
(route) =>
route.fulfill({
contentType: 'application/json',
body: JSON.stringify(
report ?? {
escenarios: [
scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6),
scenarioReport('VPH positivo', 30, 9),
],
factores_escenarios: [],
},
),
}),
);
}
for (const width of [1440, 480]) {
test(`supervivencia (simulado) at ${width} px: CaCu says the curves are the scenario group's, not individual predictions`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu');
await open(page, url);
const card = page.locator('[data-section=supervivencia]');
await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico');
await expect(card).not.toContainText('Riesgo de muerte');
await expect(card.locator('[data-note=grupo]')).toContainText(
'estimaciones del grupo de pacientes del escenario clínico',
);
await expect(card.locator('[data-note=grupo]')).toContainText(
'no son predicciones individuales',
);
await expect(card.locator('h4')).toHaveText([
'Edad al diagnóstico · 45-54 años (n = 12, fallecidos = 6)',
'VPH positivo (n = 30, fallecidos = 9)',
]);
// the curves are the report's, untouched
const plot = await card
.locator('.js-plotly-plot')
.first()
.evaluate((e: any) => ({
names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name),
y: e.layout.yaxis.title.text,
x: e.layout.xaxis.title.text,
}));
expect(plot.y).toBe('Supervivencia S(t)');
expect(plot.x).toBe('Meses desde el diagnóstico');
expect(plot.names).toContain('Kaplan-Meier (IC 95 % Greenwood)');
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
await shot(page, `supervivencia-cacu-${width}`);
});
}
test('supervivencia (simulado): CaMa keeps its own title and no group note', async ({ page }) => {
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
const id = patients.entry[0].resource.id;
await withSurvival(page, 'cama');
await page.goto(`/indicadores/cama/pacientes/${id}`);
const card = page.locator('[data-section=supervivencia]');
await expect(card).toBeVisible({ timeout: 120_000 });
await expect(card.locator('mat-card-title')).toHaveText('Riesgo de muerte');
await expect(card.locator('[data-note=grupo]')).toHaveCount(0);
await shot(page, 'supervivencia-cama-sin-cambios');
});
const SCALES = [IMMEDIATE, 'Riesgo a 5 años'];
test('escalas (simulado): a survival estimate alone never feeds the risk scales or curves; they say "No disponible"', async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu'); // only cacu.survival: S(5 years) = 70 %
await open(page, url);
for (const label of SCALES) {
await expect(scale(page, label)).toContainText('No disponible');
await expect(scale(page, label).locator('.risk-marker')).toHaveCount(0);
}
await expect(page.locator('.risk-value')).toHaveCount(0); // no 70 % on a risk scale
await expect(page.locator('details.curves')).toHaveCount(0);
await expect(page.locator('table.plain', { hasText: 'Probabilidad' })).toHaveCount(0);
// the survival is still in its own analysis, as the group's estimate
const card = page.locator('[data-section=supervivencia]');
await expect(card.locator('mat-card-title')).toHaveText('Supervivencia por escenario clínico');
await expect(card.locator('h4').first()).toContainText('n = 12');
await shot(page, 'escalas-solo-supervivencia-1440');
});
test('escalas (simulado): with a survival model and compatible risk models, only the risk models feed the scales and curves', async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu', [
risk('r1', 'Riesgo LIEAG+ v3', 'cacu.cin2_pim', '2026-06-01', [
[0, 0.03, 0.02, 0.05],
[5, 0.12, 0.08, 0.17],
]),
risk('r2', 'Riesgo de cáncer v2', 'cacu.cancer_pim', '2026-06-01', [[5, 0.011, 0.006, 0.02]]),
]);
await open(page, url);
const values = await page.locator('.risk-value').allInnerTexts();
expect(values.map((v) => v.trim())).toEqual(['3.0 %', '12.0 %', '1.1 %']); // none is the 70 % survival
await expect(scale(page, 'Riesgo a 5 años', 0)).toContainText('IC 95 %: 8.0–17.0');
await expect(scale(page, IMMEDIATE, 1)).toContainText('No disponible'); // the cancer model has no immediate risk
await expect(page.locator('app-risk-scales h3')).toHaveText([
'Riesgo LIEAG+ v3 · fecha índice 2026-06-01',
'Riesgo de cáncer v2 · fecha índice 2026-06-01',
]);
const curves = page.locator('details.curves');
await expect(curves).not.toContainText('Supervivencia');
expect(
JSON.stringify(await curves.locator('.js-plotly-plot').evaluate((e: any) => e.data)),
).not.toContain('70');
const table = page.locator('table.plain', { hasText: 'Probabilidad' });
await expect(table).not.toContainText('Supervivencia');
// the survival analysis and the NCI reference stay
await expect(page.locator('[data-section=supervivencia]')).toBeVisible();
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
await shot(page, 'escalas-supervivencia-y-riesgo-1440');
});
// ---- Eligibility decisions in "Riesgos y recomendaciones" ----
const ELIGIBILITY = '**/api/cacu/fhir/Patient/*/$eligibility*';
const SCENARIO_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
const CRITERION_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
const riskBox = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
});
const visit = (scenario: string, date: string, eligible: boolean, criteria: string[] = []) =>
part('candidate', {
part: [
part('scenario', { valueCoding: { system: SCENARIO_SYSTEM, code: scenario } }),
part('index-date', { valueDate: date }),
part('eligible', { valueBoolean: eligible }),
...criteria.map((code) =>
part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code } }),
),
],
});
const eligibilityAnswer = (status: string, ...candidates: object[]) =>
answerOf(part('status', { valueCode: status }), ...candidates);
const eligibilityIs = (page: Page, body: object, status = 200) =>
page.route(ELIGIBILITY, (route) =>
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }),
);
async function withFollowUp(page: Page, status: string, recorded?: string) {
await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
const response = await route.fetch();
const patient = await response.json();
patient.extension = (patient.extension ?? []).filter(
(e: { url: string }) =>
e.url !== EXT + 'follow-up-status' && e.url !== EXT + 'first-hysterectomy-recorded',
);
patient.extension.push({ url: EXT + 'follow-up-status', valueCoding: { code: status } });
if (recorded) {
patient.extension.push({ url: EXT + 'first-hysterectomy-recorded', valueDate: recorded });
}
await route.fulfill({ response, json: patient });
});
}
test('elegibilidad: the risk section shows the published post-treatment exclusion', async ({ page }) => {
const patients = await page.request.get(
'/api/cacu/fhir/Patient?_count=200&follow-up-status=post_treatment',
);
expect(patients.ok()).toBe(true);
const { entry } = await patients.json();
const code = 'no_pretreatment_biopsy';
let patientId: string | undefined;
for (const { resource } of entry ?? []) {
const response = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$eligibility`);
expect(response.ok()).toBe(true);
const { parameter } = await response.json();
const latest = parameter
.filter((p: any) =>
p.name === 'candidate' && p.part.some((v: any) =>
v.name === 'scenario' && v.valueCoding.code === 'post_treatment',
),
)
.map((p: any) => ({
day: p.part.find((v: any) => v.name === 'index-date').valueDate as string,
eligible: p.part.find((v: any) => v.name === 'eligible').valueBoolean as boolean,
criteria: p.part.filter((v: any) => v.name === 'criterion').map((v: any) => v.valueCoding.code),
}))
.sort((a: { day: string }, b: { day: string }) => b.day.localeCompare(a.day))[0];
if (latest && !latest.eligible && latest.criteria.length === 1 && latest.criteria[0] === code) {
patientId = resource.id;
break;
}
}
expect(patientId, 'a synthetic patient with a published post-treatment exclusion').toBeDefined();
await open(page, `/indicadores/cacu/pacientes/${patientId}`);
const box = riskBox(page);
await expect(box.getByRole('status')).toHaveText(/paciente ya tratada\.$/);
await expect(box.locator('app-risk-scales')).toHaveCount(0);
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
});
for (const width of [1440, 480]) {
test('elegibilidad (simulado) at ' + width + ' px: the risk section shows all reasons from the selected visit', async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url, sample } = await firstRecord(page);
const day = sample.slice(0, 10);
await withFollowUp(page, 'pre_colposcopy');
await eligibilityIs(
page,
eligibilityAnswer(
'evaluated',
visit('pre_colposcopy', plus(day, 1), true),
visit('pre_colposcopy', plus(day, -3), false, ['regla_anterior']),
visit('pre_colposcopy', plus(day, -2), false, ['no_index_result', 'regla_nueva']),
visit('surveillance', day, false, ['cancer_history']),
visit('post_colposcopy', day, false, ['prior_treatment']),
),
);
await open(page, url);
const box = riskBox(page);
await expect(box.getByRole('status')).toHaveText(
'No disponible por: Sin resultado de citología o VPH en la visita índice; regla_nueva.',
);
await expect(box.locator('app-risk-scales')).toHaveCount(0);
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
expect(await layoutProblems(page)).toEqual([]);
});
}
test('elegibilidad (simulado): precolposcopy falls back to surveillance when it has no visit by the index', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
const day = sample.slice(0, 10);
await withFollowUp(page, 'pre_colposcopy');
await eligibilityIs(
page,
eligibilityAnswer(
'evaluated',
visit('pre_colposcopy', plus(day, 1), true),
visit('surveillance', day, false, ['prior_outcome']),
),
);
await open(page, url);
await expect(riskBox(page).getByRole('status')).toHaveText(
'No disponible por: Resultado CIN2+ previo al índice.',
);
});
for (const status of ['evaluated', 'no_candidate']) {
test('elegibilidad (simulado): ' + status + ' takes precedence over recorded hysterectomy', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
const day = sample.slice(0, 10);
await withFollowUp(page, 'pre_colposcopy', day);
await eligibilityIs(
page,
status === 'evaluated'
? eligibilityAnswer(
status,
visit('pre_colposcopy', day, true),
visit('surveillance', day, false, ['hysterectomy']),
)
: eligibilityAnswer(status),
);
const answer = page.waitForResponse((r) => r.url().includes('/$eligibility'));
await open(page, url);
await answer;
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
await expect(riskBox(page).getByText('No disponible por:', { exact: false })).toHaveCount(0);
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
});
}
test('elegibilidad (simulado): a new patient never inherits the previous risk exclusion', async ({
page,
}) => {
await firstRecord(page);
const links = page.locator('table.worklist tbody tr a');
const records = await links.evaluateAll((els) => {
const unique = new Map<string, string>();
for (const el of els) {
const href = el.getAttribute('href')!;
const id = /pacientes\/([^?]+)/.exec(href)![1];
if (!unique.has(id)) unique.set(id, href);
if (unique.size === 2) break;
}
return [...unique];
});
expect(records).toHaveLength(2);
const [[firstId, firstUrl], [secondId]] = records;
await withFollowUp(page, 'pre_colposcopy');
let release!: () => void;
const gate = new Promise<void>((resolve) => (release = resolve));
await page.route(ELIGIBILITY, async (route) => {
const first = new URL(route.request().url()).pathname.endsWith(`/${firstId}/$eligibility`);
if (!first) await gate;
await route.fulfill({
contentType: 'application/fhir+json',
json: eligibilityAnswer(
'evaluated',
visit('pre_colposcopy', '1900-01-01', !first, first ? ['prior_outcome'] : []),
),
});
});
const reason = riskBox(page).getByText('No disponible por: Resultado CIN2+ previo al índice.');
try {
await open(page, firstUrl);
await expect(reason).toBeVisible();
await page.getByRole('link', { name: 'Regresar' }).click();
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click();
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
await expect(reason).toHaveCount(0);
const answer = page.waitForResponse((r) => r.url().includes(`/${secondId}/$eligibility`));
release();
await answer;
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
await expect(reason).toHaveCount(0);
} finally {
release();
}
});
test('elegibilidad: CaMa has no such section and never asks for it', async ({ page }) => {
let asked = false;
await page.route('**/$eligibility*', (route) => {
asked = true;
return route.abort();
});
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
await expect(page.locator('app-paciente')).toBeVisible({ timeout: 120_000 });
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
expect(asked).toBe(false);
});
// ---- survival curves: absent values, insufficient data and absent scenarios (all "simulado") ----
const A = 'Edad al diagnóstico · 45-54 años';
const B = 'VPH negativo';
const C = 'Citología · LIEAG';
const partial = scenarioReport(A, 12, 6);
partial.km = {
months: [0, 12, 24, 36],
S: [1, 0.9, 0.8, 0.7],
low: [1, 0.8, null, 0.55],
high: [1, 0.95, null, 0.82],
} as any;
partial.points = {
COMB: { S: [0, null, 0.7], low: [null, null, 0.55], high: [null, null, 0.82] },
} as any;
const contract = {
escenarios: [partial],
escenarios_sin_curvas: [{ escenario: B, n: 9, fallecidos: 2 }],
min_fallecidos_escenario: 5,
factores_escenarios: [],
};
for (const width of [1440, 480]) {
test(`supervivencia (simulado) at ${width} px: absent limits draw no band, zero is not unavailable, insufficient data is told apart from an absent scenario`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu', [], contract, [A, B, C]);
await open(page, url);
const card = page.locator('[data-section=supervivencia]');
await expect(card.locator('[data-note=grupo]')).toContainText(
'no son predicciones individuales',
);
const plot = await card
.locator('.js-plotly-plot')
.first()
.evaluate((e: any) => ({
bands: e.data.filter((t: any) => t.fill === 'toself').map((t: any) => t.y),
model: e.data.find((t: any) => t.name?.startsWith('LR + HBN')),
km: e.data.find((t: any) => t.name?.startsWith('Kaplan')),
}));
expect(plot.bands.length).toBe(1); // only where both limits exist (the first two points)
expect(plot.bands[0].every((v: unknown) => typeof v === 'number')).toBe(true);
expect(plot.km.y).toEqual([1, 0.9, 0.8, 0.7]); // the curve itself stays whole
expect(plot.model.y).toEqual([0, null, 0.7]); // a real zero is drawn; the unavailable value is a gap
expect(plot.model.error_y.array).toEqual([null, null, expect.closeTo(0.12, 5)]); // no bar from absent limits
const insufficient = card.locator('[data-state=insuficiente]');
await expect(insufficient).toHaveCount(1);
await expect(insufficient).toContainText('Datos insuficientes para trazar la curva');
await expect(insufficient).toContainText('n = 9, fallecidos = 2');
await expect(insufficient).toContainText('mínimo requerido: 5 fallecidos');
const absent = card.locator('[data-state=sin-informacion]');
await expect(absent).toHaveCount(1);
await expect(absent).toContainText(
'Sin información de este escenario en el informe del modelo',
);
await expect(absent).not.toContainText('insuficientes');
await expect(card.locator('h4', { hasText: C })).toHaveCount(1);
await expect(card.locator('h4', { hasText: B })).toHaveCount(1);
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
await shot(page, `supervivencia-valores-ausentes-${width}`);
});
}
test('supervivencia (simulado): CaCu distinguishes an unlisted scenario from having no applicable report', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withSurvival(page, 'cacu', [], { escenarios: [], factores_escenarios: [] }, [A]);
await open(page, url);
const card = page.locator('[data-section=supervivencia]');
await expect(card.locator('[data-state=sin-informacion]')).toHaveCount(1);
await expect(card.locator('[data-state=insuficiente]')).toHaveCount(0);
await expect(card).not.toContainText('datos insuficientes');
await page.unroute('**/api/cacu/fhir/RiskAssessment**');
await withSurvival(page, 'cacu', [], undefined, []);
await open(page, url);
await expect(card.locator('[data-state=sin-informe]')).toHaveText(
'No disponible: no hay un informe de supervivencia para los escenarios de la paciente.',
);
await expect(card.locator('[data-state=insuficiente]')).toHaveCount(0);
});
test('supervivencia (simulado): CaMa keeps its own wording for a scenario without a curve', async ({
page,
}) => {
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
await withSurvival(page, 'cama', [], contract, [A, B]);
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
const card = page.locator('[data-section=supervivencia]');
await expect(card).toBeVisible({ timeout: 120_000 });
await expect(card.locator('mat-card-title')).toHaveText('Riesgo de muerte');
await expect(card).toContainText('No disponible: datos insuficientes.');
await expect(card.locator('[data-state=insuficiente], [data-state=sin-informacion]')).toHaveCount(
0,
);
});
+40 -15
View File
@@ -65,7 +65,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
@@ -85,13 +85,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
expect(problems).toEqual([]);
});
@@ -205,6 +205,16 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: '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 ({
@@ -216,22 +226,17 @@ for (const domain of ['cama', 'tea']) {
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
// The histopathology figures are two cards: the result by BI-RADS and the confirmation.
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
(i) => i.text === 'Tipo histológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ 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).map(detection), ...all.slice(clinical, results), ...cards]
? [...all.slice(0, route + 1), ...all.slice(clinical, results), ...cards]
: all;
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
@@ -241,9 +246,29 @@ for (const domain of ['cama', 'tea']) {
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
);
if (domain === 'cama') {
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).
const drawn = await tab
.locator('.js-plotly-plot')
+285
View File
@@ -292,6 +292,7 @@
"default": "identity",
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -443,6 +444,7 @@
"description": "Qu\u00e9 estudio se saca del documento.",
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -465,6 +467,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -641,6 +647,7 @@
"entity": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -663,6 +670,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -1530,6 +1541,7 @@
"entity": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -2117,6 +2129,7 @@
"description": "En qu\u00e9 estudio de la plataforma se guarda.",
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -2139,6 +2152,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -4056,6 +4073,7 @@
"schema": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -4164,6 +4182,7 @@
"schema": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -5907,6 +5926,272 @@
]
}
},
"/{domain}/fhir/Patient/{id}/$eligibility": {
"get": {
"description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.",
"operationId": "cacu_eligibility",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Limit the report to one CaCu scenario",
"in": "query",
"name": "scenario",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Limit the report to one CaCu scenario",
"title": "Scenario"
}
},
{
"description": "Only index dates up to this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only index dates up to this day",
"title": "Cutoff"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Eligibility",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$reference-risk": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.",
"operationId": "reference_risk",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Reference Risk",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$risk-series": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.",
"operationId": "cacu_risk_series",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Risk Series",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Procedure": {
"get": {
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
+292
View File
@@ -42,8 +42,10 @@
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1",
"typescript": "~6.0.2",
"vitest": "^5.0.0"
@@ -2013,6 +2015,283 @@
"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": {
"version": "1.1.1",
"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"
}
},
"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": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
+2
View File
@@ -46,8 +46,10 @@
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1",
"typescript": "~6.0.2",
"vitest": "^5.0.0"
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuEligibility$Params {
domain: Domain;
id: string;
/**
* Limit the report to one CaCu scenario
*/
scenario?: (string | null);
/**
* Only index dates up to this day
*/
cutoff?: (string | null);
}
export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('scenario', params.scenario, {});
rb.query('cutoff', params.cutoff, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuRiskSeries$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ReferenceRisk$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+6
View File
@@ -113,6 +113,12 @@ export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/sea
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export 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';
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
+1 -1
View File
@@ -25,7 +25,7 @@ export interface Extract {
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
+1 -1
View File
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'fhir';
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export interface Target {
/**
* En qué estudio de la plataforma se guarda.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'target';
+53 -19
View File
@@ -10,23 +10,44 @@ interface Band {
high?: (number | null)[];
}
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The stretches of x where the curve has both limits: a band is drawn only there, never from a
* limit that is absent (an absent limit is not zero). */
function bandRuns(b: Band): number[][] {
const runs: number[][] = [];
let run: number[] = [];
b.x.forEach((x, i) => {
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
else {
if (run.length > 1) runs.push(run);
run = [];
}
});
if (run.length > 1) runs.push(run);
return runs;
}
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
lines.push({
x: [...b.x, ...[...b.x].reverse()],
y: [...b.high, ...[...b.low].reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
for (const run of bandRuns(b)) {
const x = run.map((i) => b.x[i]);
lines.push({
x: [...x, ...[...x].reverse()],
y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
}
}
lines.push({
x: b.x,
y: b.y,
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name,
type: 'scatter',
mode: 'lines',
@@ -295,20 +316,33 @@ export function scenarioFigure(
};
}
/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
* point without both limits has no bar. */
function points(
name: string,
x: number[],
p: { S: number[]; low: number[]; high: number[] },
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> {
const errors = p.S.map((value, i) => {
const low = p.low?.[i];
const high = p.high?.[i];
return finite(value) && finite(low) && finite(high)
? { up: high - value, down: value - low }
: null;
});
return {
x,
y: p.S,
error_y: {
type: 'data',
symmetric: false,
array: p.high.map((h, i) => h - p.S[i]),
arrayminus: p.S.map((v, i) => v - p.low[i]),
},
y: p.S.map((v) => (finite(v) ? v : null)) as number[],
...(errors.some((error) => error !== null)
? {
error_y: {
type: 'data' as const,
symmetric: false,
array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: errors.map((error) => error?.down ?? null) as number[],
},
}
: {}),
name,
type: 'scatter',
mode: 'markers',
+153 -11
View File
@@ -3,6 +3,64 @@ import { scenarioBars } from './figures';
import { Reading } from './measures';
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', () => {
const r: Reading = {
populations: {},
@@ -17,6 +75,41 @@ describe('bars', () => {
['1', '25.0 %'],
]);
});
it('aggregates only named abnormal cytology results without changing the denominator', () => {
const cell = (n: number) => ({ 'initial-population': n });
const r: Reading = {
populations: { 'initial-population': 10 },
strata: {
category: { NILM: cell(4), LSIL: cell(2), HSIL: cell(1), no_data: cell(3) },
'age_group-category': {
'25-34|NILM': cell(4),
'25-34|LSIL': cell(2),
'25-34|HSIL': cell(1),
'25-34|no_data': cell(3),
},
},
};
const catalog = ['NILM', 'LSIL', 'HSIL'].map((code) => ({ code, label: code, color: '#000' }));
const aggregate = { label: 'Anormal', color: '#f00', codes: ['LSIL', 'HSIL'] };
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, () => r)!;
expect(t.rows[1].cells).toEqual(['3', '30.0 %']);
expect(t.rows.map((row) => !!row.sub)).toEqual([false, false, true, true, false].slice(0, t.rows.length));
const g = grouped(
{
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: {},
@@ -47,7 +140,7 @@ describe('bars', () => {
const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial',
'Detección subsecuente',
'Con detección anterior',
'Sin dato',
]);
expect(t.rows.map((x) => x.cells)).toEqual([
@@ -145,7 +238,7 @@ describe('bars', () => {
c === 'initial'
? 'Detección inicial'
: c === 'subsequent'
? 'Detección subsecuente'
? 'Con detección anterior'
: 'Sin dato',
['initial', 'subsequent', 'no_data'],
{ fill: true },
@@ -157,15 +250,15 @@ describe('bars', () => {
);
const y = (f.data[0] as any).y;
expect(y).toEqual([
'Detección inicial<br>n = 0',
'Detección subsecuente<br>n = 8',
'Sin dato<br>n = 2',
'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(['Detección subsecuente<br>n = 6']);
expect((f.data[0] as any).y).toEqual(['Con detección anterior<br>Pacientes: 6']);
});
});
});
@@ -173,7 +266,7 @@ describe('bars', () => {
describe('shared views of cytology and HPV by genotype', () => {
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' },
{ code: 'positive_other', label: 'Positivo', color: '#A8C243', 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) },
@@ -198,7 +291,7 @@ describe('shared views of cytology and HPV by genotype', () => {
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']);
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 %'],
@@ -247,7 +340,7 @@ describe('shared views of cytology and HPV by genotype', () => {
});
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>n = 10']);
expect((all.data[0] as any).y).toEqual(['25-34<br>Reportes: 10']);
});
});
@@ -282,7 +375,7 @@ describe('independent bars by group', () => {
)!;
expect(g.groups.map((x) => [x.label, x.total])).toEqual([
['Detección inicial', 4],
['Detección subsecuente', 6],
['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'],
@@ -300,7 +393,7 @@ describe('independent bars by group', () => {
['0/0 · —', undefined],
['0/0 · —', undefined],
]);
expect(empty.note).toContain('una categoría en cero significa');
expect(empty.note).toBeUndefined();
const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5),
)!;
@@ -415,3 +508,52 @@ describe('independent bars by group', () => {
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 = [
{ label: 'a', measure: 'A' },
{ label: 'b', measure: 'B' },
];
const table = bars({ kind: 'days', label: 'x', steps, staggered: true }, (m) =>
m === 'A' ? median(10, 5, 10) : median(20, 10, 30),
)!;
expect(table.rows.map((r) => [r.offset, r.width, r.marks])).toEqual([
[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],
]);
});
});
+189 -46
View File
@@ -1,4 +1,5 @@
import { CIE10 } from './cie10';
import { chainStarts } from './durations';
import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures';
@@ -16,6 +17,11 @@ export type Mode = {
kind: 'counts';
measure: string;
catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** The records counted in the category distribution. */
unit?: string;
/** What the share in the second column is a share of. */
percentLabel?: string;
hidden?: Hidden;
/** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
percent?: boolean;
@@ -27,6 +33,7 @@ export type Mode = {
order: string[];
complete?: boolean;
colors?: Colors;
percentLabel?: string;
}
| {
kind: 'positives';
@@ -35,28 +42,54 @@ export type Mode = {
order: string[];
complete?: boolean;
colors?: Colors;
percentLabel?: string;
}
| {
kind: 'signs';
measure: string;
strata: string[];
colors?: Colors;
percentLabel?: string;
}
| { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
| {
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;
hidden?: Hidden;
}
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
| {
kind: 'days';
steps: { label: string; measure: string }[];
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'; measure: string; yes: string; no: string; colors?: [string, string] }
| {
kind: 'split';
measure: string;
yes: string;
no: string;
colors?: [string, string];
unit?: string;
percentLabel?: string;
}
/** Each row's units by result (a bar in segments), and the share of the row's units with a
* result that are `malignant`; a row with units and no result is not a row with none */
| {
@@ -66,6 +99,8 @@ export type Mode = {
rows: Category[];
results: Category[];
malignant: string[];
dynamicResults?: boolean;
malignancyMeasure?: string;
}
| {
kind: 'figure';
@@ -95,6 +130,7 @@ export type Tint = { bar: string; mark: string };
/** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
export interface GroupRow {
sub?: boolean;
label: string;
color: string;
count: number;
@@ -121,10 +157,14 @@ export interface Groups {
/** 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;
color?: string;
/** where the bar starts, in % of the scale */
offset?: number;
width: number;
marks: number[];
cells: string[];
@@ -146,10 +186,8 @@ export interface Bars {
export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo';
const EMPTY_ROUND =
'Hay pacientes sin clasificación de ronda («Sin dato»): una categoría en cero significa que no hay pacientes clasificadas en esa ronda según la información disponible.';
const NO_ROUND =
'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
'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.';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
@@ -204,6 +242,25 @@ const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) {
case 'ratio': {
const r = of(mode.measure);
const n = r?.populations['numerator'] ?? 0;
const total = r?.populations['denominator'] ?? 0;
if (r?.score === undefined || !total) return undefined;
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return {
head: ['n/N', mode.percentLabel ?? 'Porcentaje', 'IC 95 %'],
rows: [
{
label: 'Total',
color: mode.colors?.['numerator'],
width: 100 * r.score,
marks: ends.map((v) => 100 * v),
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
},
],
};
}
case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
@@ -218,11 +275,25 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
];
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return {
head: ['n', '%'],
rows: all.map(({ code, label, color }) => {
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: all.flatMap(({ code, label, color }, index) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
const part = !!mode.aggregate?.codes.includes(code);
const row = { label, color, width: (100 * n) / most, marks: [], cells: cols, sub: part };
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),
};
@@ -240,6 +311,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
cells[c]['denominator'] ?? 0,
mode.colors?.[c],
]),
mode.percentLabel,
);
if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) =>
@@ -256,6 +328,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors,
mode.percentLabel,
);
}
case 'positives': {
@@ -270,6 +343,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
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(
@@ -285,6 +359,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
return [positive, positive + size(cells[`${c}|negative`])];
},
mode.colors,
mode.percentLabel,
);
}
case 'signs': {
@@ -296,6 +371,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}),
mode.percentLabel,
);
}
case 'days':
@@ -305,6 +381,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
mode.tint,
mode.staggered,
);
case 'days-by': {
const r = of(mode.measure);
@@ -328,7 +405,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
[mode.no, denominator - numerator],
];
return {
head: ['n', '%'],
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: parts.map(([label, n], i) => ({
label,
color: mode.colors?.[i],
@@ -343,16 +420,33 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
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', ...mode.results.map((x) => x.label), '% maligno'],
legend: mode.results.map(({ label, color }) => ({ label, color })),
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 = mode.results.map((x) => size(cells[`${code}|${x.code}`]));
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0);
const bad = by.reduce(
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0),
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 {
@@ -360,7 +454,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: mode.results.map((x, i) => ({
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)})`,
@@ -369,11 +463,13 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
`${n}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? den
? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')]
? 'Sin biopsias clasificables'
: 'Sin biopsias'
? !hasMalignancy
? 'No disponible'
: den
? `${bad}/${den} (${pct(bad, den)})`
: size(malignancyCells[`${code}|no_data`])
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
@@ -385,6 +481,13 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
}
}
/** The subsequent round split by the form's last screening, drawn in place of that round's group. */
const LAST_SCREENING: [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'],
];
/** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with
* one independent bar per category over the group's own records. A group the report leaves out is
* drawn empty only when the listed ones add up to every record of the period (`complete`). */
@@ -397,7 +500,16 @@ export function grouped(
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 n = (g: string, c: string) => size(cells[`${g}|${c}`]);
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),
@@ -408,28 +520,53 @@ export function grouped(
];
const total = (g: string) =>
mode.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === g)
.reduce((t, [, c]) => t + size(c), 0)
? cellsOf(g).reduce((t, [, c]) => t + size(c), 0)
: mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
const groups: Group[] = codes.map((code) => {
const at = codes.indexOf('subsequent');
const drawn =
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: name(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.map((c) => {
rows: mode.catalog.flatMap((c, index) => {
const count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined;
return {
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) + ' %'}`,
},
];
}),
};
});
@@ -442,9 +579,7 @@ export function grouped(
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
: none && unclassified
? NO_ROUND
: unclassified && classified.some((g) => !g.total)
? EMPTY_ROUND
: undefined;
: undefined;
note = [sentence, note].filter(Boolean).join(' ') || undefined;
}
return { groups, note };
@@ -459,6 +594,7 @@ function complete(
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) => {
@@ -484,25 +620,24 @@ function complete(
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;
const unclassified = counts('no_data')?.[1] ?? 0;
return {
head: ['n/N', '%'],
head: ['n/N', percentLabel],
rows,
note: !reconciled
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
: none && listed.includes('no_data')
? NO_ROUND
: unclassified &&
(empty.length || order.some((c) => !listed.includes(c) && c !== 'no_data'))
? EMPTY_ROUND
: undefined,
: undefined,
};
}
function ratios(rows: [string, number, number, string?][]): Bars | undefined {
function ratios(
rows: [string, number, number, string?][],
percentLabel = 'Porcentaje',
): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', '%'],
head: ['n/N', percentLabel],
rows: rows.map(([label, n, total, color]) => ({
label,
color,
@@ -517,21 +652,29 @@ 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 top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
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;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
head: ['Mediana', 'Observaciones', 'Q1–Q3'],
markColor: tint?.mark,
rows: rows.map(({ label, n, score: s }) => {
rows: rows.map(({ label, n, score: s }, i) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
color: tint?.bar,
offset: staggered ? at(starts[i]) : undefined,
width: at(s.score),
marks: spread.map(at),
marks: spread.map((v) => at(starts[i] + v)),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
};
}),
+4
View File
@@ -19,7 +19,9 @@ export const CYTOLOGY_COLORS: Record<string, string> = {
'ASC-US': '#2778B8',
LSIL: '#B19525',
'ASC-H': '#7955B1',
CIN2: '#E07A9C',
HSIL: '#CE4778',
CIN3: '#BC4163',
CIS: '#AA394D',
no_data: NEUTRAL,
};
@@ -43,7 +45,9 @@ export const HPV_COLORS: Record<string, string> = {
export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651',
LSIL: '#B19525',
CIN2: '#E07A9C',
HSIL: '#CE4778',
CIN3: '#BC4163',
CIS: '#AA394D',
carcinoma: '#8D4C79',
cin1_plus: '#B19525',
@@ -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');
});
});
+8 -1
View File
@@ -1,4 +1,4 @@
import { durationMax, durationRows } from './durations';
import { chainStarts, durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
@@ -53,3 +53,10 @@ describe('durationRows', () => {
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]);
});
});
+27 -5
View File
@@ -5,6 +5,8 @@ import { Reading } from './measures';
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.
@@ -17,6 +19,25 @@ export interface DurationRow {
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
@@ -26,12 +47,13 @@ export function durationRows(
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' };
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, status: 'empty' };
if (r?.score === undefined) return { label, after, status: 'empty' };
return {
label,
after,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
@@ -41,6 +63,6 @@ export function durationRows(
});
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
/** 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) => Math.max(r.median ?? 0, r.high ?? 0)));
Math.max(0, ...rows.map((r) => (r.start ?? 0) + Math.max(r.median ?? 0, r.high ?? 0)));
+5 -3
View File
@@ -125,7 +125,7 @@ export function scenarioBars(
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
);
const y = order
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
? scenarios.map((s, i) => `${label(s)}<br>${options.ofAll ? 'Reportes' : 'Pacientes'}: ${totals[i]}`)
: scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
@@ -304,9 +304,11 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
line: { color: '#FFFFFF', width: 2 },
},
// an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
texttemplate: values.map((v) =>
v ? `%{label}<br>%{percent} del total de ${center}` : '',
),
textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`,
} as Partial<Plotly.Data>,
],
layout: {
+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 -1
View File
@@ -1,6 +1,6 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { Row } from './follow-up';
import type { CamaRow, Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
@@ -50,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 { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures';
import { historyPeriods, periods } from './measures';
describe('follow-up list', () => {
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();
});
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', () => {
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([
+3 -3
View File
@@ -36,7 +36,7 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
<mat-tab label="Indicadores">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab>
<mat-tab label="Trazabilidad">
@@ -45,7 +45,7 @@ import { Loading } from '../loading';
</ng-template>
</mat-tab>
@if (domain() === 'cacu') {
<mat-tab label="Análisis de riesgos">
<mat-tab label="Análisis de Riesgo">
<ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" />
</ng-template>
@@ -57,7 +57,7 @@ import { Loading } from '../loading';
</ng-template>
</mat-tab>
} @else if (domain() === 'cama') {
<mat-tab label="Análisis de riesgos">
<mat-tab label="Análisis de Riesgo">
<ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" />
</ng-template>
+3 -3
View File
@@ -13,6 +13,7 @@ export const LAYOUTS: Record<string, Layout> = {
'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
],
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
label: 'Diagnóstico tras biopsia',
step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
@@ -50,7 +51,6 @@ export const LAYOUTS: Record<string, Layout> = {
'CAMA_EU38A',
'CAMA_DIAS_TOMA_DIAGNOSTICO',
'CAMA_CONFIRMACION_BIRADS45',
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
],
route: [
{
+28 -3
View File
@@ -23,6 +23,13 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
return found;
}
/** Historical periods ending in the selected month or semester, oldest first. */
export function historyPeriods(type: PeriodType, selected: string): string[] {
const [year, part] = selected.split('-');
const month = type === 'semester' ? (part === 'S1' ? 0 : 6) : Number(part) - 1;
return periods(type, 6, new Date(Number(year), month, 1)).reverse();
}
export function periodLabel(period: string): string {
const [year, part] = period.split('-');
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
@@ -103,9 +110,12 @@ 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',
@@ -134,7 +144,7 @@ export const LABELS: Record<string, string> = {
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Detección inicial',
subsequent: 'Detección subsecuente',
subsequent: 'Con detección anterior',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
@@ -153,6 +163,21 @@ export const LABELS: Record<string, string> = {
['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> = {
@@ -165,11 +190,11 @@ export const STRATA: Record<string, string> = {
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente',
round: 'Detección inicial o anterior',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
};
export const name = (value: string) => LABELS[value] ?? value;
export const name = (value: string) => LABELS[value] ?? HISTOLOGIC_TYPES[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
if (!r || r.score === undefined) return 'Sin dato';
+83 -44
View File
@@ -8,13 +8,13 @@ import {
PPV_DONUT,
PPV_LEVEL_COLORS,
QUARTILE,
REQUEST_COLORS,
ROUND_COLORS,
} from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
const ABNORMAL = { label: 'Anormal', color: ROSE, codes: ['ASC-US', 'LSIL', 'ASC-H', 'HSIL', 'CIS', 'carcinoma'] };
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
@@ -29,6 +29,12 @@ const CYTOLOGY: Catalog = {
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
{
code: 'carcinoma',
label: 'Carcinoma epidermoide invasor',
color: BIOPSY_COLORS['carcinoma'],
group: 'abnormal',
},
],
};
@@ -41,7 +47,9 @@ const BIOPSY: Catalog = {
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',
@@ -59,15 +67,8 @@ const HPV = [
{ 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', color: HPV_COLORS['positive_other'] },
{ code: 'positive_other', label: 'Positivo sin genotipo', color: HPV_COLORS['positive_other'] },
];
const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: REQUEST_COLORS['below_high_grade'] },
{ code: 'pending', label: 'Pendiente', color: REQUEST_COLORS['pending'] },
{ code: 'no_grade', label: 'Sin grado', color: REQUEST_COLORS['no_grade'] },
];
/** The screening route's bars: a median, and the marks of its quartiles. */
const TINT = { bar: DURATION, mark: QUARTILE };
@@ -75,16 +76,14 @@ const TINT = { bar: DURATION, mark: QUARTILE };
const ROUNDS = ['initial', 'subsequent', 'no_data'];
const ROUND_CAPTION =
'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección inicial (primera vez en la vida), ' +
'subsecuente (detección previa registrada, o ya con colposcopía o tratamiento) o «Sin dato». ' +
'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 BY_AGE = 'Por grupo de edad';
const BY_STATUS = 'Por estatus de seguimiento';
const BY_ROUND = 'Por detección inicial y subsecuente';
const BY_ROUND = 'Por detección inicial y anterior';
const AGE_GROUPS = ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'];
const STATUSES = ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case', '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'],
@@ -96,29 +95,38 @@ const groupViews = (
measure: string,
catalog: { code: string; label: string; color: string }[],
unit: string,
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {},
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string }; aggregate?: typeof ABNORMAL } = {},
): Mode[] =>
[
{ label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS },
{ label: BY_STATUS, stratum: 'follow_up_status', order: STATUSES },
{ label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
].map((v) => ({
kind: 'grouped' as const,
measure,
catalog,
unit,
caption: measure === 'CACU_VPH_GENOTIPO'
? 'Porcentaje de reportes de VPH del grupo por genotipo.'
: 'Porcentaje de pacientes del grupo por resultado citológico.',
...v,
...more,
}));
/** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
const ppv = (
measure: string,
title: string,
note: string,
percentLabel: string,
...more: Mode[]
): ReadingsCard => ({
kind: 'readings',
title,
headline: measure,
footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT },
{ kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT, percentLabel },
{
kind: 'shares',
label: 'Citología previa',
@@ -127,6 +135,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
stratum: 'cytology',
colors: PPV_CYTOLOGY_COLORS,
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
percentLabel: 'Porcentaje de pacientes con esta citología previa',
},
{
kind: 'shares',
@@ -136,6 +145,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
stratum: 'hpv',
colors: HPV_COLORS,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
percentLabel: 'Porcentaje de pacientes de cada grupo de VPH previo',
},
{
kind: 'shares',
@@ -144,16 +154,18 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
stratum: 'level',
colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
percentLabel: 'Porcentaje de pacientes de cada nivel de histología',
},
{
kind: 'shares',
label: 'Por detección inicial y subsecuente',
label: 'Por detección inicial y anterior',
caption: ROUND_CAPTION,
measure,
stratum: 'round',
colors: ROUND_COLORS,
order: ROUNDS,
complete: true,
percentLabel: 'Porcentaje de pacientes de cada ronda',
},
...more,
],
@@ -178,8 +190,8 @@ export const CACU: Page = {
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS,
},
{
@@ -189,14 +201,14 @@ export const CACU: Page = {
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempos de la ruta del tamizaje',
title: 'Tiempos de tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [
{
@@ -207,28 +219,45 @@ export const CACU: Page = {
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
{
label: 'Diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
},
{
kind: 'days',
tint: TINT,
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
label: 'Por ventana de tiempo',
staggered: true,
caption:
'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{
label: 'Toma a resultado de citología',
measure: 'CACU_EU_TIEMPO_REPORTE',
},
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
],
},
{
kind: 'days-by',
kind: 'days',
tint: TINT,
label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
stratum: 'diagnosis_code',
label: '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',
},
],
},
],
},
@@ -238,7 +267,7 @@ export const CACU: Page = {
kind: 'columns',
title: 'Resultados de citología, VPH y biopsia',
viewsLabel: 'Lectura de la distribución citológica y del VPH por genotipo',
views: [GENERAL, BY_AGE, BY_STATUS, BY_ROUND],
views: [GENERAL, BY_AGE, BY_ROUND],
sections: [
{
kind: 'readings',
@@ -246,8 +275,16 @@ export const CACU: Page = {
title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.',
modes: [
{ kind: 'counts', label: GENERAL, measure: 'CACU_EU7', catalog: CYTOLOGY.categories },
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'),
{
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 }),
],
},
{
@@ -261,9 +298,14 @@ export const CACU: Page = {
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 }),
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
ofAll: true,
hidden: HPV_HIDDEN,
}),
],
},
{
@@ -276,6 +318,8 @@ export const CACU: Page = {
label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories,
unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
@@ -289,23 +333,18 @@ export const CACU: Page = {
label: 'Colposcopía',
section: ppv(
'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía',
'Tasa de confirmación histopatológica de referencia a colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
'Porcentaje de pacientes',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la biopsia',
'Tasa de confirmación histopatológica de referencia a biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
},
'Porcentaje de biopsias reportadas',
),
},
],
+58 -32
View File
@@ -26,6 +26,8 @@ export interface ReadingsCard {
kind: 'readings';
title: string;
headline?: string;
/** say the headline under the figure instead of above it */
footnote?: boolean;
/** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string;
note?: string;
@@ -122,7 +124,6 @@ const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
};
const PENDING = 'Indicador no publicado en el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = {
@@ -248,6 +249,7 @@ export const PAGES: Record<string, Page> = {
},
cama: {
anchor: 'CAMA_BIRADS456_PACIENTE',
// every single-number card, together at the start, in the order asked for
kpis: [
{
measure: 'CAMA_BIRADS456_PACIENTE',
@@ -255,12 +257,6 @@ export const PAGES: Record<string, Page> = {
value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
},
{
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de detección histopatológica',
value: '{pct} %',
note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
},
{
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
@@ -272,15 +268,25 @@ export const PAGES: Record<string, Page> = {
...CAMA_DAYS,
},
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: PENDING,
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',
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' },
@@ -295,11 +301,16 @@ export const PAGES: Record<string, Page> = {
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,
},
{ label: 'Diagnóstico a tratamiento' },
],
},
],
@@ -325,28 +336,31 @@ export const PAGES: Record<string, Page> = {
},
{
kind: 'readings',
title: 'Resultado histopatoló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. El porcentaje maligno se calcula solo sobre las pacientes con biopsia con grado.',
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_HISTOPATOLOGIA_BIRADS',
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
results: [...BIOPSY_GRADES, ...NO_RESULT],
results: NO_RESULT,
malignant: ['in_situ', 'invasive'],
dynamicResults: true,
malignancyMeasure: 'CAMA_HISTOPATOLOGIA_BIRADS',
},
{
kind: 'counts',
label: 'Todas las categorías',
heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: [...BIOPSY_GRADES, ...NO_RESULT],
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
catalog: [],
unit: 'Pacientes',
percent: true,
percentLabel: 'Porcentaje de pacientes',
},
],
},
@@ -356,21 +370,22 @@ export const PAGES: Record<string, Page> = {
card: true,
choices: [
{
label: 'Resultado de biopsias',
label: 'Tipos histológicos',
section: {
kind: 'readings',
title: 'Resultado de biopsias',
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tipos histológicos',
unit: 'biopsias',
note: 'Biopsias con resultado reportado, por fecha del reporte (no son pacientes ni mastografías). La tasa divide los carcinomas (in situ o invasor) entre biopsias con grado conocido. Los porcentajes de la distribución incluyen todas las biopsias reportadas, también «Sin dato» (sin grado), por lo que sus denominadores pueden ser distintos.',
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: 'Biopsias reportadas',
heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
label: 'Tipos histológicos',
heading: 'Tipo histológico',
measure: 'CAMA_TIPO_HISTOLOGICO',
catalog: [],
unit: 'Biopsias',
percent: true,
percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
@@ -382,7 +397,7 @@ export const PAGES: Record<string, Page> = {
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; no es equivalente a la tasa de detección.',
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',
@@ -391,6 +406,8 @@ export const PAGES: Record<string, Page> = {
yes: 'Con reporte de biopsia',
no: 'Sin reporte de biopsia',
colors: [INSTITUTIONAL, NEUTRAL],
unit: 'Mastografías',
percentLabel: 'Porcentaje de mastografías',
},
],
},
@@ -468,7 +485,9 @@ export const HISTORY: Record<string, History> = {
[
['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],
@@ -481,17 +500,22 @@ export const HISTORY: Record<string, History> = {
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
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 a tratamiento',
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median',
},
@@ -506,6 +530,7 @@ export const HISTORY: Record<string, History> = {
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',
@@ -517,10 +542,11 @@ export const HISTORY: Record<string, History> = {
kind: 'median',
},
{
title: 'Días de tamizaje a diagnóstico',
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',
@@ -541,7 +567,7 @@ export const HISTORY: Record<string, History> = {
['no_data', 'Sin dato', GREY],
]),
{
title: 'Tasa de confirmación histopatológica',
title: 'Confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent',
},
+18 -3
View File
@@ -54,13 +54,13 @@ import { Reading } from './measures';
@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">n = {{ group.total }}</span>
{{ 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" [attr.data-category]="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
@@ -94,7 +94,7 @@ import { Reading } from './measures';
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<tr>
<tr [class.sub]="row.sub">
<th scope="row">
{{ row.label }}
@if (row.hint) {
@@ -116,6 +116,7 @@ import { Reading } from './measures';
} @else {
<span
class="bar"
[style.margin-left.%]="row.offset"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
@@ -146,8 +147,15 @@ import { Reading } from './measures';
} @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;
@@ -347,6 +355,8 @@ export class Readings {
readonly title = input.required<string>();
readonly headline = 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);
@@ -359,6 +369,11 @@ export class Readings {
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal('');
protected readonly countUnit = computed(() => {
const mode = this.mode();
const unit = mode.kind === 'grouped' ? mode.unit : 'pacientes';
return unit[0].toUpperCase() + unit.slice(1);
});
protected readonly mode = computed(
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
);
+9 -6
View File
@@ -2,7 +2,7 @@ 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 { DurationRow, durationMax } from './durations';
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
@@ -29,15 +29,16 @@ import { DurationRow, durationMax } from './durations';
@if (loading()) {
<app-loading what="los tiempos" [figure]="true" />
} @else {
@let rows = mode() === 'sample' ? sample() : step();
@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 {
Cada barra es la mediana de su paso, desde cero y por separado; los pasos pueden
corresponder a poblaciones diferentes, por lo que las medianas no se suman.
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) {
@@ -62,16 +63,17 @@ import { DurationRow, durationMax } from './durations';
<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.low) / max : 0"
[style.left.%]="max ? (100 * ((row.start ?? 0) + row.low)) / max : 0"
></span>
<span
class="mark"
[style.left.%]="max ? (100 * row.high) / max : 0"
[style.left.%]="max ? (100 * ((row.start ?? 0) + row.high)) / max : 0"
></span>
}
</span>
@@ -180,4 +182,5 @@ export class RouteCard {
protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax;
protected readonly chain = chained;
}
+10 -2
View File
@@ -28,7 +28,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
<app-readings
[title]="s.title"
[camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)"
[headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''"
[modes]="s.modes"
[view]="view()"
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
[title]="c.section.title"
[hideTitle]="true"
[camaStyle]="true"
[headline]="headlineOf(c.section)"
[headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''"
[modes]="c.section.modes"
[loading]="of().loading"
@@ -162,6 +164,12 @@ export class ReadingsSection {
const words = detail(measure, r, s.unit);
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);
+29
View File
@@ -31,6 +31,21 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
espécimen fue insatisfactorio.
</p>
<h4>Riesgos de referencia NCI</h4>
<p>
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 con el riesgo de CIN3+. Los riesgos publicados de CIN2+ y cáncer son
resultados complementarios; no son directamente comparables con las estimaciones
institucionales porque no están validados para la población de esta plataforma.
</p>
<ul>
<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><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>
<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>
<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>
<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>
</ul>
}
@if (available().length) {
<p>Periodicidad disponible: {{ available().join(', ') }}.</p>
@@ -48,6 +63,20 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
@if (m.description) {
<p>{{ m.description }}</p>
}
@if (m.relatedArtifact?.length) {
<h4>Referencias</h4>
<ul>
@for (reference of m.relatedArtifact; track $index) {
<li>
@if (reference.url) {
<a [href]="reference.url" target="_blank" rel="noopener noreferrer">{{ reference.citation || reference.display || reference.url }}</a>
} @else {
{{ reference.citation || reference.display }}
}
</li>
}
</ul>
}
<h4>Cálculo</h4>
<p>
{{ scoring[code(m.scoring) ?? ''] }}
+84 -37
View File
@@ -40,49 +40,96 @@
}
@if (page(); as pg) {
@if (applied(); as period) {
<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">
@for (k of pg.kpis; track k.title) {
<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>
@if (domain() === 'cama') {
<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: 3; --kpi-cols-lg: 3">
@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 }"
/>
}
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
</section>
<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>
} @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>
<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 }"
/>
@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>
}
}
<ng-template #kpiView let-k>
<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>
</ng-template>
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('readings')
+2 -2
View File
@@ -42,13 +42,13 @@ h2 {
@media (min-width: 1000px) {
.kpis {
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(var(--kpi-cols-md, 3), 1fr);
}
}
@media (min-width: 1350px) {
.kpis {
grid-template-columns: repeat(5, 1fr);
grid-template-columns: repeat(var(--kpi-cols-lg, 5), 1fr);
}
}
+1 -1
View File
@@ -142,7 +142,7 @@
</td>
<td>
{{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup }}</small>
<small>Grupo: {{ name(row.ageGroup) }}</small>
</td>
<td>{{ name(row.status) }}</td>
<td>
+20 -16
View File
@@ -16,8 +16,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { saveExcel, savePdf } from '../export';
import { Stages } from '../paciente/stages';
import { saveFollowUp } from './follow-up-export';
import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
@@ -140,24 +140,28 @@ export class TabRiesgos {
/** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true);
this.saveError.set('');
try {
const cutoff = this.applied();
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
const pages = await this.fhir.all(this.domain(), 'Patient', asked);
const start = windowStart(cutoff, this.window());
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon()));
const sheet = followUpSheet(all, [
['Ventana consultada', `${start} al ${cutoff}`],
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`],
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`],
['Búsqueda', this.search() || 'Ninguna'],
['Horizonte de la probabilidad (años)', `${this.horizon()}`],
]);
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu');
else await savePdf([sheet], 'seguimiento-cacu', true);
await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) => {
const cutoffYear = Number(query.cutoff.slice(0, 4));
// bornFor encodes the minimum with le and the maximum with gt at one year earlier.
const lower = query.birthdates.find((value) => value.startsWith('le'));
const upper = query.birthdates.find((value) => value.startsWith('gt'));
const minimum = lower ? `${cutoffYear - Number(lower.slice(2, 6))}` : 'Sin límite';
const maximum = upper ? `${cutoffYear - Number(upper.slice(2, 6)) - 1}` : 'Sin límite';
const all = pages.flatMap((p) => rows(p, query.start, query.cutoff, query.horizon));
return followUpSheet(all, [
['Ventana consultada', query.window],
['Estatus de seguimiento', query.status],
['Edad mínima', minimum],
['Edad máxima', maximum],
['Búsqueda', query.search],
['Horizonte de la probabilidad (años)', `${query.horizon}`],
]);
});
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
+19
View File
@@ -35,7 +35,26 @@
}
</mat-select>
</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>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) {
<p class="muted" role="alert">
+41 -14
View File
@@ -7,6 +7,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { saveFollowUp } from './follow-up-export';
import { camaFollowUpSheet } from './follow-up-sheet';
import { camaRows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
@@ -46,23 +48,23 @@ export class TabSeguimiento {
protected readonly statuses = STATUSES;
protected readonly name = name;
protected readonly priority = (code: string) => PRIORITY[code] ?? code;
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({
params: () => ({
domain: this.domain(),
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
loader: ({ params: { domain, query, size } }) => {
this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', {
...params,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
},
});
protected readonly loading = signal(false);
@@ -95,6 +97,31 @@ export class TabSeguimiento {
this.first.reload();
}
/** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true);
this.saveError.set('');
try {
await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) =>
camaFollowUpSheet(
pages.flatMap((p) => camaRows(p, query.cutoff)),
[
['Ventana consultada', query.window],
['Estatus de seguimiento', query.status],
['Búsqueda', query.search],
],
this.priority,
),
);
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected has(relation: 'next' | 'previous'): boolean {
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');
});
}
});
+43 -7
View File
@@ -1,11 +1,13 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { historyFigure } from './figures';
import { periodLabel, periods, PeriodType, reading } from './measures';
import { historyPeriods, periodLabel, periods, PeriodType, reading } from './measures';
import { HISTORY, HistoryPanel } from './pages';
interface Drawn {
@@ -19,24 +21,37 @@ interface Drawn {
* each measure period by period. */
@Component({
selector: 'app-tab-trazabilidad',
imports: [Loading, MatButtonToggleModule, Plot],
imports: [Loading, MatButtonModule, MatButtonToggleModule, MatSelectModule, Plot],
template: `
<section class="card filters" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group
[value]="type()"
(change)="type.set($event.value)"
(change)="setType($event.value)"
aria-label="Intervalo de análisis"
>
<mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group>
@if (domain() === 'cama' || domain() === 'cacu') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodo seleccionado</mat-label>
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
@for (p of options(); track p) {
<mat-option [value]="p">{{ p }}</mat-option>
}
</mat-select>
</mat-form-field>
<button mat-flat-button (click)="applied.set(chosen())" [disabled]="chosen() === applied()">
Aplicar
</button>
}
</section>
@if (series.isLoading()) {
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" />
<app-loading what="el histórico" text="Cargando histórico…" />
} @else if (series.error()) {
<p class="muted" role="alert">
No se pudo cargar la trazabilidad.
No se pudo cargar el histórico.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p>
} @else {
@@ -71,6 +86,12 @@ interface Drawn {
padding: 16px 20px;
margin-bottom: 16px;
}
.filters {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
}
.filters-title {
font-size: 16px;
font-weight: 500;
@@ -95,13 +116,28 @@ export class TabTrazabilidad {
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('month');
protected readonly options = computed(() => periods(this.type()));
protected readonly chosen = signal(periods('month')[0]);
protected readonly applied = signal(periods('month')[0]);
protected setType(type: PeriodType): void {
this.type.set(type);
const latest = this.options()[0];
this.chosen.set(latest);
this.applied.set(latest);
}
protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
params: () => ({
domain: this.domain(),
type: this.type(),
measures: this.measures(),
period: this.applied(),
}),
loader: async ({ params }) => {
const history = HISTORY[params.domain];
if (!history) return [];
const asked = periods(params.type).reverse();
const asked = historyPeriods(params.type, params.period);
return Promise.all(
history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure);
@@ -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,
},
]
: []),
];
}
+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);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { Figure, Plot } from '../plot';
export interface Choice {
id: string;
name: string;
/** drawn before the user touches it */
on: boolean;
}
/** A figure's curves as choices, all on: a band has no name of its own and goes with the line
* after it. */
export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw } {
const groups = new Map<string, Figure['data']>();
let pending: Figure['data'] = [];
for (const trace of figure.data) {
pending.push(trace);
const { name, showlegend } = trace as { name?: string; showlegend?: boolean };
if (name && showlegend !== false) {
groups.set(name, pending);
pending = [];
}
}
return {
choices: [...groups.keys()].map((name) => ({ id: name, name, on: true })),
draw: (ids) => ({ ...figure, data: [...ids].flatMap((id) => groups.get(id) ?? []) }),
};
}
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({
selector: 'app-curve-chooser',
imports: [MatCheckboxModule, Plot],
template: `
<div class="choices">
@for (c of choices(); track c.id) {
<mat-checkbox [checked]="chosen().has(c.id)" (change)="toggle(c.id)">
{{ c.name }}
</mat-checkbox>
}
</div>
@if (chosen().size) {
@for (note of notes()(chosen()); track note) {
<p class="muted">{{ note }}</p>
}
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
}
`,
styles: `
:host {
display: block;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
`,
})
export class CurveChooser {
readonly choices = input.required<Choice[]>();
readonly draw = input.required<Draw>();
/** what the chosen curves assume, said under the choices */
readonly notes = input<(ids: Set<string>) => string[]>(() => []);
/** what the user toggled away from its default */
private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed(
() =>
new Set(
this.choices()
.filter((c) => c.on !== this.toggled().has(c.id))
.map((c) => c.id),
),
);
protected readonly figure = computed(() => this.draw()(this.chosen()));
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
}
+130
View File
@@ -0,0 +1,130 @@
import { HttpErrorResponse } from '@angular/common/http';
import type { Parameters } from 'fhir/r4';
import { eligibilityFailure, eligibilityView } from './eligibility';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
const candidate = (
scenario: string,
date: string,
eligible: boolean,
criteria: string[] = [],
sample?: string,
display?: string,
) =>
part('candidate', {
part: [
part('scenario', { valueCoding: { system: SCENARIOS, code: scenario, display } }),
part('index-date', { valueDate: date }),
...(sample ? [part('index-sample-id', { valueString: sample })] : []),
part('eligible', { valueBoolean: eligible }),
...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERIA, code: c } })),
],
});
const answer = (status: string, ...candidates: object[]): Parameters =>
({
resourceType: 'Parameters',
parameter: [
part('status', { valueCode: status }),
part('patient', { valueReference: { reference: 'Patient/p' } }),
part('cutoff', { valueDate: '2026-12-02' }),
...candidates,
],
}) as Parameters;
// Each test fails if the section merged visits, dropped a reason or read silence as eligibility.
describe('the eligibility answer as the section shows it', () => {
it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate(
'post_colposcopy',
'2020-08-10',
false,
['cancer_history', 'outcome_by_index', 'prior_treatment'],
'2020-08-10',
),
candidate('surveillance', '2024-01-05', true, [], 'a'),
candidate('surveillance', '2025-03-01', false, ['no_index_result'], 'b'),
candidate('post_colposcopy', '2022-02-02', true, [], '2022-02-02'),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.cutoff).toBe('2026-12-02');
expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([
['post_colposcopy', 'Postcolposcopia', 2],
['surveillance', 'Vigilancia', 2],
]);
const post = view.groups[0].visits; // newest visit first
expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([
['2022-02-02', true, []],
['2020-08-10', false, ['cancer_history', 'outcome_by_index', 'prior_treatment']],
]);
expect(post[1].reasons[0].text).toBe('Antecedente de cáncer cervicouterino');
expect(view.groups[1].visits.map((v) => v.sampleId)).toEqual(['b', 'a']);
});
it('the backend decides: a visit it calls eligible is eligible, one with reasons is not derived', () => {
const view = eligibilityView(answer('evaluated', candidate('survival', '2025-01-01', true)));
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups[0].visits[0]).toMatchObject({
eligible: true,
reasons: [],
sampleId: undefined,
});
});
it('without candidates it says so, which is not eligibility', () => {
expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' });
});
it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => {
for (const bad of [
null,
undefined,
{} as any,
{ resourceType: 'Bundle' } as any,
answer('evaluated'),
answer('other', candidate('survival', '2025-01-01', true)),
answer('evaluated', part('candidate', { part: [] })),
])
expect(eligibilityView(bad)).toEqual({ kind: 'unavailable' });
});
it('unknown codes show the display the API gave, else the code, and keep the code', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'),
candidate('other_scenario', '2025-01-02', false, ['another_rule']),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups.map((g) => [g.code, g.text])).toEqual([
['new_scenario', 'Escenario nuevo'],
['other_scenario', 'other_scenario'],
]);
expect(view.groups[1].visits[0].reasons).toEqual([
{ code: 'another_rule', text: 'another_rule' },
]);
});
});
describe('what a failed call is', () => {
const failure = (status: number, error: unknown = null) =>
eligibilityFailure(new HttpErrorResponse({ status, error }));
it('a 409 asks for the gold update and keeps the backend diagnostics', () => {
expect(
failure(409, {
resourceType: 'OperationOutcome',
issue: [{ code: 'conflict', diagnostics: 'rebuild gold.cacu_eligibility' }],
}),
).toEqual({ kind: 'gold', text: 'rebuild gold.cacu_eligibility' });
expect(failure(409)).toEqual({ kind: 'gold', text: undefined });
});
it('404 and 422 are "unavailable"; any other status or no connection is a communication error', () => {
expect(failure(404)).toEqual({ kind: 'unavailable' });
expect(failure(422)).toEqual({ kind: 'unavailable' });
expect(failure(500)).toEqual({ kind: 'error' });
expect(failure(0)).toEqual({ kind: 'error' });
expect(eligibilityFailure(new Error('boom'))).toEqual({ kind: 'error' });
});
});
+254
View File
@@ -0,0 +1,254 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */
export const SCENARIO_TEXT: Record<string, string> = {
surveillance: 'Vigilancia',
pre_colposcopy: 'Precolposcopia',
post_colposcopy: 'Postcolposcopia',
post_colposcopy_second_visit: 'Segunda visita postcolposcopia',
post_treatment: 'Postratamiento',
survival: 'Supervivencia',
};
/** The exclusion criteria the backend publishes, as the screens say them. */
export const CRITERION_TEXT: Record<string, string> = {
hysterectomy: 'Histerectomía previa al índice',
under_18: 'Edad menor de 18 años al índice',
prior_outcome: 'Resultado CIN2+ previo al índice',
no_index_result: 'Sin resultado de citología o VPH en la visita índice',
unreported_biopsy: 'Biopsia solicitada sin resultado',
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
cancer_history: 'Antecedente de cáncer cervicouterino',
prior_treatment: 'Tratamiento previo a la visita índice',
no_referral: 'Sin citología de referencia previa a la colposcopia',
referral_not_graded: 'Citología de referencia de bajo grado sin VPH positivo',
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
no_birth_date: 'Fecha de nacimiento desconocida',
died_by_index: 'Defunción en o antes de la visita índice',
not_evaluated: 'Escenario que la plataforma no evalúa por ahora',
};
export interface Reason {
/** the API's code, untouched */
code: string;
text: string;
}
export interface Visit {
indexDate: string;
/** the sample the visit is evaluated at, when the backend names one */
sampleId?: string;
/** the backend's decision; it is never derived from the reasons */
eligible: boolean;
reasons: Reason[];
}
export interface ScenarioGroup {
code: string;
text: string;
visits: Visit[];
}
/** What the section can be in; none of them says "eligible" unless the backend did. */
export type EligibilityState =
| { kind: 'loading' }
| { kind: 'error' }
| { kind: 'unavailable' }
| { kind: 'gold'; text?: string }
| { kind: 'none'; cutoff?: string }
| { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] };
type Part = ParametersParameter;
const value = (p?: Part): unknown =>
p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueBoolean ?? undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const coding = (p?: Part) => p?.valueCoding;
/** The answer of `$eligibility`, grouped by scenario and keeping the visits apart: each visit has
* its own decision and its own reasons. A code the screens do not know shows the display the API
* gave, else the code itself. An answer that is not what the contract says is "unavailable". */
export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
const top = answer?.parameter;
if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' };
const status = value(named(top, 'status')[0]);
const cutoff = value(named(top, 'cutoff')[0]) as string | undefined;
const candidates = named(top, 'candidate');
if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff };
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
const groups = new Map<string, ScenarioGroup>();
for (const c of candidates) {
const scenario = coding(named(c.part, 'scenario')[0]);
const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined;
const eligible = value(named(c.part, 'eligible')[0]);
if (!scenario?.code || !indexDate || typeof eligible !== 'boolean')
return { kind: 'unavailable' };
const group = groups.get(scenario.code) ?? {
code: scenario.code,
text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code,
visits: [],
};
groups.set(scenario.code, group);
group.visits.push({
indexDate,
sampleId: value(named(c.part, 'index-sample-id')[0]) as string | undefined,
eligible,
reasons: named(c.part, 'criterion').flatMap((r) => {
const k = coding(r);
return k?.code
? [{ code: k.code, text: CRITERION_TEXT[k.code] ?? k.display ?? k.code }]
: [];
}),
});
}
for (const g of groups.values()) g.visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate));
return { kind: 'evaluated', cutoff, groups: [...groups.values()] };
}
/** What the answer's failure says: the gold must be updated (409), the patient has no such
* operation (404, 422), or the call itself failed (anything else, including no connection). */
export function eligibilityFailure(error: unknown): EligibilityState {
if (error instanceof HttpErrorResponse) {
if (error.status === 409) {
const issue = (error.error as { issue?: { diagnostics?: string }[] } | null)?.issue?.[0];
return { kind: 'gold', text: issue?.diagnostics };
}
if (error.status === 404 || error.status === 422) return { kind: 'unavailable' };
}
return { kind: 'error' };
}
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
/** "Elegibilidad por escenario clínico": the decisions the backend publishes for each indexed visit,
* one scenario at a time. It shows them; it decides nothing. */
@Component({
selector: 'app-eligibility',
template: `
@let s = state();
@switch (s.kind) {
@case ('loading') {
<p class="state" role="status" data-state="loading">Consultando la elegibilidad…</p>
}
@case ('error') {
<p class="state" role="alert" data-state="error">
No se pudo consultar la elegibilidad. Intente de nuevo más tarde.
</p>
}
@case ('unavailable') {
<p class="state" role="status" data-state="unavailable">
Información de elegibilidad no disponible para esta paciente.
</p>
}
@case ('gold') {
<p class="state" role="status" data-state="gold">
La elegibilidad requiere actualizar la capa gold del servidor; todavía no está disponible.
</p>
@if (s.text) {
<p class="muted detail">{{ s.text }}</p>
}
}
@case ('none') {
<p class="state" role="status" data-state="none">
Sin candidatos: la paciente no tiene visitas indexadas en estos escenarios
@if (s.cutoff) {
a la fecha de corte {{ s.cutoff }}
}
. Esto no significa que sea elegible.
</p>
}
@case ('evaluated') {
@for (g of s.groups; track g.code) {
<details class="scenario" [attr.data-scenario]="g.code" [open]="g.visits.length <= 2">
<summary>
<strong>{{ g.text }}</strong>
<span class="muted">
· {{ plural(g.visits.length, 'visita', 'visitas') }} ·
{{ plural(count(g, true), 'elegible', 'elegibles') }},
{{ plural(count(g, false), 'no elegible', 'no elegibles') }}
</span>
</summary>
<ul class="visits">
@for (v of g.visits; track $index) {
<li class="visit" [attr.data-eligible]="v.eligible">
<p class="head">
<span class="badge" [class.ok]="v.eligible">{{
v.eligible ? 'Elegible' : 'No elegible'
}}</span>
Fecha índice {{ v.indexDate }}
<span class="muted"
>· {{ v.sampleId ? 'Muestra ' + v.sampleId : 'Sin muestra asociada' }}</span
>
</p>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivos de exclusión">
@for (r of v.reasons; track r.code) {
<li [attr.data-code]="r.code">{{ r.text }}</li>
}
</ul>
}
</li>
}
</ul>
</details>
}
@if (s.cutoff) {
<p class="muted note">Visitas hasta la fecha de corte {{ s.cutoff }}.</p>
}
}
}
`,
styles: `
.note,
.detail {
font-size: 12px;
}
.state {
margin: 8px 0;
}
.scenario {
border-top: 1px solid #dce3e7;
padding: 6px 0;
}
.scenario summary {
cursor: pointer;
}
.visits {
list-style: none;
margin: 6px 0 0;
padding: 0;
}
.visit {
padding: 4px 0 4px 12px;
}
.head {
margin: 0;
}
.badge {
background: #f3d6dc;
border-radius: 10px;
color: #7a1f36;
font-size: 12px;
font-weight: 500;
margin-right: 6px;
padding: 1px 8px;
}
.badge.ok {
background: #dcefe4;
color: #1d5a3b;
}
.why {
margin: 2px 0 0;
padding-left: 22px;
}
`,
})
export class Eligibility {
readonly state = input.required<EligibilityState>();
protected plural = plural;
protected count(g: ScenarioGroup, eligible: boolean) {
return g.visits.filter((v) => v.eligible === eligible).length;
}
}
+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;
}
+177 -75
View File
@@ -5,9 +5,21 @@
@if (error()) {
<p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) {
<h1>
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1>
<div class="record-head">
<h1>
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1>
@if (cama()) {
<div class="head-actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
}
</div>
@if (cama() && saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<dl class="summary">
<div>
<dt>CURP</dt>
@@ -119,15 +131,11 @@
@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.
</p>
<div data-section="etapas">
<app-stages [stages]="s" [detail]="true" />
<p class="muted route-note">
Etapas de la citología{{ s[0].day ? ' del ' + s[0].day : '' }} a la fecha de corte
{{ cutoff() }}. «Inferida por fechas» es una asociación por cercanía de fechas, no
un vínculo clínico confirmado; un intervalo «(inferido)» depende de una etapa
inferida; «Pendiente» es una biopsia solicitada sin reporte a la fecha de corte;
«Sin dato» indica que no hay dato.
</p>
</div>
}
<table class="plain">
@@ -146,7 +154,7 @@
<td>
{{ h.text }}
@if (h.code && h.code !== h.text) {
<span class="muted">({{ h.code }})</span>
<span class="muted">(CIE-10: {{ h.code }})</span>
}
</td>
</tr>
@@ -253,66 +261,73 @@
</mat-card>
}
<mat-card appearance="outlined" class="wide">
<mat-card-header
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
@if (riskExclusion(); as reason) {
<p role="status">{{ reason }}</p>
} @else {
<app-risk-scales [groups]="groups()" />
@if (reference.value(); as ref) {
<app-reference-risk [view]="ref" />
}
@if (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>
}
@if (models().length) {
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Probabilidad</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (m of models(); track m.model) {
@for (p of m.predictions; track p.years) {
<tr>
<td>{{ $first ? m.text : '' }}</td>
<td>{{ $first ? m.index : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }}
%
} @else {
—
<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>
}
</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" />
}
}
</tbody>
</table>
<details class="curves" open data-section="curvas">
<summary>Curvas de probabilidad con su intervalo</summary>
<ul class="curve-text">
@for (t of curveText(); track $index) {
<li>{{ t }}</li>
}
</ul>
<app-plot [figure]="curve()" [height]="300" />
</details>
} @else if (!riskExclusion()) {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
</mat-card-content>
</mat-card>
</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') {
<mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -560,12 +575,77 @@
</mat-card-content>
</mat-card>
}
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) {
@if (models().some((m) => m.model.endsWith('.survival'))) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header><mat-card-title>Riesgo de muerte</mat-card-title></mat-card-header>
<mat-card-header>
<mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
}}</mat-card-title>
</mat-card-header>
<mat-card-content>
<h3>Análisis de supervivencia</h3>
@if (survival.isLoading()) {
@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>
@@ -574,17 +654,39 @@
<li>{{ name }}</li>
}
</ul>
@if (s.methods.length) {
<details>
<summary>Métodos</summary>
<ul class="scenarios methods">
@for (name of s.methods; track name) {
<li>{{ name }}</li>
}
</ul>
</details>
}
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios no tienen fallecimientos suficientes para trazar curvas.
}
@for (name of s.unavailable; track name) {
<h4>{{ name }}</h4>
<p class="muted">No disponible: datos insuficientes.</p>
}
@for (u of s.insufficient; track u.name) {
<h4>{{ u.name }}</h4>
<p class="muted" data-state="insuficiente">{{ insufficientText(u) }}</p>
}
@for (name of s.missing; track name) {
<h4>{{ name }}</h4>
<p class="muted" data-state="sin-informacion">
Sin información de este escenario en el informe del modelo.
</p>
}
<app-factores [rows]="s.factors" />
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else {
<p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
}
</mat-card-content>
</mat-card>
+16
View File
@@ -138,3 +138,19 @@ h1 .id {
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;
}
+214 -36
View File
@@ -13,6 +13,8 @@ import type {
RiskAssessment,
} from 'fhir/r4';
import { Api } from '../api/api';
import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study';
import { readReport$Json } from '../api/fn/models/read-report-json';
@@ -20,15 +22,19 @@ 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 { camaRecordSheets } from './cama-record-sheets';
import { recordSheets } from './record-sheets';
import { HttpClient } from '@angular/common/http';
import type { Parameters as FhirParameters } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import { ANTECEDENTS, Fact, group, split } from './record-groups';
import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk';
import { curveFigure, curveText } from './risk-curve';
import { riskGroups, riskScales, RiskScales } from './risk-scales';
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve';
import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationOf, noCurveText, survivalFigure } from './survival-combination';
import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -45,6 +51,7 @@ 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 {
@@ -69,10 +76,36 @@ function facts(observations: Observation[]): Fact[] {
/** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */
/** The names of the methods the figures draw, each once. */
function methods(figures: { figure: { data: unknown[] } }[]): string[] {
const names = figures.flatMap((f) => f.figure.data.map((t) => (t as { name?: string }).name));
return [...new Set(names.filter((n): n is string => !!n))];
}
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({
selector: 'app-paciente',
imports: [
Factores,
CurveChooser,
Loading,
DecimalPipe,
MatButtonModule,
@@ -81,7 +114,7 @@ function facts(observations: Observation[]): Fact[] {
RouterLink,
Plot,
RiskScales,
ReferenceRisk,
RiskSeries,
Stages,
],
templateUrl: './paciente.html',
@@ -148,16 +181,33 @@ export class Paciente {
});
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
* hysterectomy of her record is still held against her when the backend does not report it,
* as with evidence loaded without the day it was available. */
protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined;
const patient = this.patient();
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
const reported = ineligibility(this.eligibility(), status, index);
if (reported) return reported;
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index
? `Sin estimación de riesgo por antecedente de histerectomía registrado el ${recorded}.`
? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined;
});
/** CaCu: 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. */
protected readonly stages = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
@@ -166,47 +216,103 @@ export class Paciente {
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
});
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.models()) : [],
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
);
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */
/** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
* survival only there is nothing to draw here: its scales are in the survival section. */
protected readonly groups = computed(() =>
this.domain() === 'cacu' ? riskGroups(this.models()) : [],
this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
? riskGroups(this.riskModels())
: [],
);
/** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API
* answers 404 while the feature is off: then nothing is shown. */
protected readonly reference = resource({
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<ReferenceView | undefined> => {
loader: async ({ params }): Promise<Series[] | undefined> => {
try {
const answer = await firstValueFrom(
this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$reference-risk`,
`${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
{
params: Object.fromEntries(
Object.entries({ cutoff: params.cutoff, sample: params.sample }).filter(
([, v]) => !!v,
),
) as Record<string, string>,
Object.entries({
cutoff: params.cutoff,
sample: params.sample?.slice(0, 10),
}).filter((e): e is [string, string] => !!e[1]),
),
},
),
);
return referenceView(answer);
return parseSeries(answer);
} catch {
return undefined;
}
},
});
/** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a
* state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */
private readonly eligibilityData = resource({
params: () => (this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined),
loader: async ({ params }): Promise<EligibilityState> => {
try {
const answer = await this.api.invoke(cacuEligibility, {
domain: 'cacu' as Domain,
id: params.id,
cutoff: params.cutoff,
});
return eligibilityView(answer as FhirParameters);
} catch (error) {
return eligibilityFailure(error);
}
},
});
protected readonly eligibility = computed<EligibilityState>(() =>
this.eligibilityData.isLoading()
? { kind: 'loading' }
: (this.eligibilityData.value() ?? { kind: 'loading' }),
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** CaCu: her record as a PDF. */
/** Her record as a PDF (CaCu's or CaMa's). */
protected async save(): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
if (this.domain() === 'cama') {
await this.saveCama();
return;
}
const { name: who, curp, numbers } = this.identity();
const facts: [string, string | undefined][] = [
['Nombre', who],
@@ -217,7 +323,7 @@ export class Paciente {
['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()],
];
if (this.riskExclusion()) facts.push(['Evaluación de riesgo', this.riskExclusion()]);
if (this.riskExclusion()) facts.push(['Evaluación de probabilidad', this.riskExclusion()]);
const sheets = recordSheets(
facts,
this.stages() ?? [],
@@ -233,17 +339,63 @@ export class Paciente {
this.saving.set(false);
}
}
/** 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 p = this.patient();
const facts: [string, string | undefined][] = [
['Nombre', who],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', p?.birthDate],
['Sexo', p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined],
['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})`) : undefined,
],
['Prioridad', c?.priority],
['Días de mastografía a diagnóstico', c?.days?.toString()],
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as [string, string][]) : []),
];
const studies: [string, string | undefined][] = [
['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],
];
const analysis = (title: string, r: typeof this.survival) => {
// a report that failed to load is no analysis: its absence is said, the file is still made
const v = r.hasValue() ? r.value() : undefined;
return v
? [{ title, scenarios: v.scenarios, figures: v.figures.map((f) => f.title), undrawn: v.unavailable }]
: [];
};
const sheets = camaRecordSheets(
facts,
studies,
this.history(),
this.tests(),
this.models(),
[...analysis('Supervivencia', this.survival), ...analysis('Recurrencia', this.recurrence)],
);
await savePdf(sheets, 'expediente-cama');
}
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
return d.reports.map((r) => {
return d.reports.flatMap((r) => {
const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[];
// the study's own results; the form's antecedents are in their own section and the extra
// findings are collapsed (record-groups)
const found = group(facts(results));
return {
const { hpv, rest } = hpvApart(facts(results));
const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
@@ -251,6 +403,10 @@ export class Paciente {
results: found.results,
findings: found.findings,
};
// an HPV result is a study of its own: its own row, only when there is one
return hpv.length
? [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]
: [row];
});
});
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
@@ -296,6 +452,9 @@ export class Paciente {
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')
@@ -345,6 +504,10 @@ export class Paciente {
return {
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
scenarios: m.scenarios,
unavailable: [] as string[],
insufficient: [] as Insufficient[],
missing: [] as string[],
methods: [] as string[],
figures: mine(r['escenarios'] ?? []).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
@@ -355,17 +518,29 @@ export class Paciente {
),
};
}
const drawn = mine((report?.['escenarios'] ?? []) as any[]);
const figures = drawn.map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
);
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
// CaCu: the report says which scenarios lack deaths (`escenarios_sin_curvas`); one it does not
// mention is not "insufficient", it is absent from the report. Other domains keep one list.
const { insufficient, missing } =
domain === 'cacu' ? sortUndrawn(report, undrawn) : { insufficient: [], missing: [] };
return {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
scenarios: m.scenarios,
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
figures,
// her scenarios the report draws no curve for
unavailable: domain === 'cacu' ? [] : undrawn,
insufficient,
missing,
methods: methods(figures),
};
},
});
@@ -479,11 +654,14 @@ export class Paciente {
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
protected readonly curve = computed<Figure>(() => curveFigure(this.models(), this.top()));
protected readonly curveText = computed(() => curveText(this.models()));
protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
private top(): number {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
return Math.max(
0,
...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)),
);
}
protected readonly insufficientText = insufficientText;
protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES;
protected readonly identity = computed(() => {
+8
View File
@@ -46,3 +46,11 @@ export function group(facts: Fact[]) {
}
return { antecedents, results, findings };
}
const HPV_FIELDS = ['hpv', 'hpv_16', 'hpv_18'];
/** The cytology report's HPV results, apart from the cytology's own facts. */
export function hpvApart(facts: Fact[]) {
const isHpv = (f: Fact) => f.study === 'cervical_cytology' && HPV_FIELDS.includes(f.field);
return { hpv: facts.filter(isHpv), rest: facts.filter((f) => !isHpv(f)) };
}
+1 -1
View File
@@ -51,7 +51,7 @@ describe('the PDF of a record', () => {
'Historial médico',
'Antecedentes y evaluación ginecológica',
'Pruebas y resultados',
'Riesgos',
'Probabilidades',
]);
});
it('writes each stage with its state, its day or its request, and where it comes from', () => {
+2 -2
View File
@@ -75,8 +75,8 @@ export function recordSheets(
]),
},
{
title: 'Riesgos',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
title: 'Probabilidades',
head: ['Estimación', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [
label,
risk ? percent(risk.p) : NONE,
+171 -1
View File
@@ -1,5 +1,5 @@
import type { Parameters } from 'fhir/r4';
import { horizonLabel, referenceView } from './reference-risk';
import { groupReference, horizonLabel, outcomeText, referenceView } from './reference-risk';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const answer = (...parameter: object[]): Parameters =>
@@ -88,3 +88,173 @@ describe('the reference answer as the section shows it', () => {
});
});
});
const cmp = (
model: string,
outcome: string,
status: string,
reasons: string[],
extra: object[] = [],
) =>
part('comparison', {
part: [
part('model', { valueCode: model }),
part('title', { valueString: model }),
part('outcome', { valueString: outcome }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const two = (a: object[], b: object[]) =>
answer(
part('status', { valueCode: 'resolved' }),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.001 }),
...a,
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 5 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.0027 }),
...b,
],
}),
);
describe('outcome names', () => {
it('translates the known outcomes for display and leaves the API identifier untouched', () => {
expect(outcomeText('cancer')).toBe('Cáncer');
expect(outcomeText('CIN2+ within one year')).toBe('CIN2+ en un año');
expect(outcomeText('CIN3+')).toBe('CIN3 o más grave (CIN3+)');
expect(outcomeText('something new')).toBe('something new');
expect(outcomeText(undefined)).toBe('');
const view = referenceView(
two([cmp('m', 'cancer', 'not_comparable', ['outcome_differs'])], []),
);
expect(view.horizons[0].comparisons[0].outcome).toBe('cancer');
});
});
describe('grouping the comparison', () => {
const reasons = ['outcome_differs', 'population_not_verified'];
it('keeps every model, horizon, value and interval, and says shared reasons once', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN2+',
'not_comparable',
[...reasons, 'index_date_differs'],
[part('institutional', { valueDecimal: 0.05 })],
),
cmp('b', 'cancer', 'not_comparable', reasons),
],
[
cmp('a', 'CIN2+', 'not_comparable', reasons, [
part('institutional', { valueDecimal: 0.07 }),
part('institutional-low', { valueDecimal: 0.05 }),
part('institutional-high', { valueDecimal: 0.09 }),
]),
cmp('b', 'cancer', 'not_comparable', [...reasons, 'horizon_not_published_by_model']),
],
),
),
);
expect(g.reference.map((r) => [r.years, r.reference])).toEqual([
[0, 0.001],
[5, 0.0027],
]);
expect(g.common).toEqual(reasons); // every model gives them
expect(g.models.map((m) => [m.model, m.outcome, m.rows.length])).toEqual([
['a', 'CIN2+', 2],
['b', 'cancer', 2],
]);
expect(g.models[0].reasons).toEqual([]); // nothing else shared by both of a's horizons
expect(g.models[0].rows[0].reasons).toEqual(['index_date_differs']);
expect(g.models[0].rows[1]).toMatchObject({
institutional: 0.07,
low: 0.05,
high: 0.09,
reasons: [],
});
expect(g.models[1].rows[1].reasons).toEqual(['horizon_not_published_by_model']);
});
it('never merges across outcomes: reasons are only shared where every compared row has them', () => {
const g = groupReference(
referenceView(
two(
[
cmp('a', 'CIN2+', 'not_comparable', ['outcome_differs']),
cmp('b', 'cancer', 'not_comparable', ['no_reference']),
],
[],
),
),
);
expect(g.common).toEqual([]);
expect(g.models.flatMap((m) => m.rows.flatMap((r) => r.reasons))).toEqual([
'outcome_differs',
'no_reference',
]);
});
it('a comparable row keeps its difference and a missing interval stays missing', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN3+',
'comparable',
[],
[
part('institutional', { valueDecimal: 0.01 }),
part('difference-pp', { valueDecimal: 0.9 }),
],
),
],
[],
),
),
);
expect(g.models[0].rows[0]).toMatchObject({
status: 'comparable',
differencePp: 0.9,
low: undefined,
});
});
it('without a model it says so once, with its reasons', () => {
const g = groupReference(
referenceView(
two(
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
),
),
);
expect(g.models).toEqual([]);
expect(g.withoutModel).toEqual(['no_institutional_model']);
});
});
+206 -70
View File
@@ -1,11 +1,11 @@
import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core';
import { Component, computed, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The states a resolution ends in, as the screens say them. */
export const STATUS_TEXT: Record<string, string> = {
resolved: 'Referencia disponible',
not_published: 'Riesgo no publicado en las tablas',
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',
@@ -44,7 +44,7 @@ export const REASON_TEXT: Record<string, string> = {
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 este riesgo en blanco.',
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.',
@@ -54,7 +54,7 @@ export const REASON_TEXT: Record<string, string> = {
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 un riesgo a este horizonte.',
no_reference: 'Las tablas no dan una probabilidad a este horizonte.',
};
const KEY_TEXT: Record<string, string> = {
@@ -205,6 +205,86 @@ export function referenceView(answer: Parameters): ReferenceView {
return view;
}
/** Outcome names as the screens say them; presentation only: the API's identifiers stay as they are
* (an outcome this map does not know is shown as the API gave it). */
export const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3 o más grave (CIN3+)',
'CIN2+': 'CIN2 o más grave (CIN2+)',
cancer: 'Cáncer',
'CIN2+ within one year': 'CIN2+ en un año',
'not stated as a histology outcome': 'No expresado como desenlace histológico',
};
export const outcomeText = (outcome?: string) => (outcome ? (OUTCOME_TEXT[outcome] ?? outcome) : '');
export interface ModelRow extends Omit<ComparisonView, 'reasons'> {
years: number;
label: string;
/** the reasons of this horizon that its model's other horizons do not share */
reasons: string[];
}
export interface ModelBlock {
model?: string;
title?: string;
outcome?: string;
/** reasons shared by every non-comparable horizon of this model, said once */
reasons: string[];
rows: ModelRow[];
}
export interface Grouped {
/** the reference by horizon: one table, whatever the models */
reference: { years: number; label: string; published: boolean; reference?: number }[];
/** reasons shared by every non-comparable comparison of every model, said once */
common: string[];
models: ModelBlock[];
/** no institutional model evaluated her: said once, with its reasons */
withoutModel: string[];
}
const shared = (lists: string[][]) =>
lists.length > 1 ? lists[0].filter((r) => lists.every((l) => l.includes(r))) : [];
/** Groups only what is equivalent: the reference once per horizon; a reason that every non-comparable
* comparison of a model (or of all models) gives, once; everything else stays where it is. Nothing is
* dropped, and a difference is never made: it is only the API's, on a comparable row. */
export function groupReference(v: ReferenceView): Grouped {
const reference = v.horizons.map((h) => ({
years: h.years,
label: h.label,
published: h.published,
reference: h.reference,
}));
const byModel = new Map<string, ModelBlock>();
const withoutModel: string[] = [];
for (const h of v.horizons)
for (const c of h.comparisons) {
if (!c.model) {
for (const r of c.reasons) if (!withoutModel.includes(r)) withoutModel.push(r);
continue;
}
const block = byModel.get(c.model) ?? {
model: c.model,
title: c.title,
outcome: c.outcome,
reasons: [],
rows: [],
};
byModel.set(c.model, block);
block.rows.push({ ...c, years: h.years, label: h.label });
}
const models = [...byModel.values()];
const notComparable = (b: ModelBlock) => b.rows.filter((r) => r.status !== 'comparable');
const common = shared(models.flatMap(notComparable).map((r) => r.reasons));
const everyModel = models.length > 1 ? common : [];
for (const b of models) {
const own = shared(notComparable(b).map((r) => r.reasons.filter((x) => !everyModel.includes(x))));
b.reasons = own;
for (const r of b.rows)
if (r.status !== 'comparable')
r.reasons = r.reasons.filter((x) => !everyModel.includes(x) && !own.includes(x));
}
return { reference, common: everyModel, models, withoutModel };
}
const OFFICIAL: Record<string, string> = {
match: 'coincide con la tabla del NCI',
'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo',
@@ -224,9 +304,9 @@ const OFFICIAL: Record<string, string> = {
<section
class="reference"
data-section="referencia-nci"
aria-label="Comparación de riesgos de referencia"
aria-label="Comparación de probabilidades de referencia"
>
<h3>Comparación de riesgos de referencia</h3>
<h3>Comparación de probabilidades de referencia</h3>
<dl class="meta">
<div>
<dt>Estado</dt>
@@ -238,10 +318,12 @@ const OFFICIAL: Record<string, string> = {
<dd>{{ s.label }}</dd>
</div>
}
<div>
<dt>Desenlace</dt>
<dd>CIN3 o más grave (CIN3+)</dd>
</div>
@if (v.source?.outcome; as out) {
<div>
<dt>Desenlace de la referencia</dt>
<dd [attr.data-outcome]="out">{{ outcomeText(out) }}</dd>
</div>
}
@if (v.evaluationDate ?? v.index?.sampleDate; as day) {
<div>
<dt>Fecha de evaluación</dt>
@@ -269,70 +351,114 @@ const OFFICIAL: Record<string, string> = {
</ul>
}
@if (v.horizons.length) {
<table class="plain" aria-label="Comparación por horizonte">
@let g = grouped();
<table class="plain" aria-label="Referencia NCI por horizonte">
<thead>
<tr>
<th>Horizonte</th>
<th>Modelo institucional</th>
<th>Referencia NCI</th>
<th>Diferencia (puntos porcentuales)</th>
</tr>
</thead>
<tbody>
@for (h of v.horizons; track h.years) {
@for (c of h.comparisons.length ? h.comparisons : [none]; track $index) {
<tr [attr.data-years]="h.years">
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
<td class="model" data-label="Modelo institucional">
@if (c.model) {
<strong>{{ c.title }}</strong>
<span class="muted">{{ c.outcome }}</span>
}
@if (c.institutional !== undefined) {
{{ c.institutional * 100 | number: '1.2-2' }} %
@if (c.low !== undefined && c.high !== undefined) {
<span class="muted"
>(IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{
c.high * 100 | number: '1.2-2'
}}
%)</span
>
}
} @else {
<span>No disponible</span>
}
</td>
<td class="nowrap" data-label="Referencia NCI">
@if (h.reference !== undefined) {
<strong>{{ h.reference * 100 | number: '1.2-2' }} %</strong>
} @else {
<span>No publicado</span>
}
</td>
<td data-label="Diferencia (puntos porcentuales)">
@if (c.status === 'comparable' && c.differencePp !== undefined) {
<strong
>{{ c.differencePp > 0 ? '+' : ''
}}{{ c.differencePp | number: '1.2-2' }}</strong
>
} @else {
<span>No comparable</span>
@if (c.reasons.length) {
<ul class="why">
@for (r of c.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
}
</td>
</tr>
}
@for (h of g.reference; track h.years) {
<tr [attr.data-years]="h.years">
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
<td class="nowrap" data-label="Referencia NCI">
@if (h.reference !== undefined) {
<strong>{{ h.reference * 100 | number: '1.2-2' }} %</strong>
} @else {
<span>No publicado</span>
}
</td>
</tr>
}
</tbody>
</table>
<h4>Modelos institucionales</h4>
@if (g.withoutModel.length || !g.models.length) {
<p class="nomodel">
<strong>No disponible</strong>
</p>
<ul class="why" aria-label="Motivo">
@for (r of g.withoutModel; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (g.common.length) {
<p class="muted">Motivos que comparten todas las comparaciones no válidas:</p>
<ul class="why" aria-label="Motivos comunes">
@for (r of g.common; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@for (m of g.models; track m.model) {
<section class="model" [attr.data-model]="m.model" [attr.aria-label]="m.title">
<h5>
{{ m.title }}
<span class="muted" [attr.data-outcome]="m.outcome">{{ outcomeText(m.outcome) }}</span>
</h5>
@if (m.reasons.length) {
<p class="muted">No comparable en estos horizontes:</p>
<ul class="why" aria-label="Motivos del modelo">
@for (r of m.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
<table class="plain" [attr.aria-label]="'Comparación de ' + m.title">
<thead>
<tr>
<th>Horizonte</th>
<th>Modelo institucional</th>
<th>Diferencia (puntos porcentuales)</th>
</tr>
</thead>
<tbody>
@for (c of m.rows; track c.years) {
<tr [attr.data-years]="c.years">
<td class="nowrap" data-label="Horizonte">{{ c.label }}</td>
<td data-label="Modelo institucional">
@if (c.institutional !== undefined) {
{{ c.institutional * 100 | number: '1.2-2' }} %
@if (c.low !== undefined && c.high !== undefined) {
<span class="muted"
>(IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{
c.high * 100 | number: '1.2-2'
}}
%)</span
>
}
} @else {
<span>No disponible</span>
}
</td>
<td data-label="Diferencia (puntos porcentuales)">
@if (c.status === 'comparable' && c.differencePp !== undefined) {
<strong
>{{ c.differencePp > 0 ? '+' : ''
}}{{ c.differencePp | number: '1.2-2' }}</strong
>
} @else {
<span>No comparable</span>
@if (c.reasons.length) {
<ul class="why">
@for (r of c.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
}
</td>
</tr>
}
</tbody>
</table>
</section>
}
<p class="muted note">
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos
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>
}
@@ -406,6 +532,7 @@ const OFFICIAL: Record<string, string> = {
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th,
td {
@@ -413,9 +540,18 @@ const OFFICIAL: Record<string, string> = {
text-align: left;
vertical-align: top;
}
.model strong,
.model .muted {
display: block;
.model {
border-top: 1px solid #dce3e7;
margin-top: 8px;
padding-top: 4px;
}
h4,
h5 {
margin: 12px 0 4px;
}
h5 .muted {
font-weight: 400;
margin-left: 8px;
}
.why {
margin: 4px 0;
@@ -463,10 +599,10 @@ const OFFICIAL: Record<string, string> = {
})
export class ReferenceRisk {
readonly view = input.required<ReferenceView>();
protected readonly none: ComparisonView = {
status: 'not_comparable',
reasons: ['no_institutional_model'],
};
protected readonly grouped = computed(() => groupReference(this.view()));
protected outcomeText(outcome?: string) {
return outcomeText(outcome);
}
protected statusText(status: string) {
return STATUS_TEXT[status] ?? status;
}
+2 -2
View File
@@ -18,7 +18,7 @@ describe('the institutional curves', () => {
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(['Riesgo LIEAG+', 'Riesgo cáncer']);
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
@@ -94,7 +94,7 @@ describe('the institutional curves', () => {
model('Vacío v1', []),
]),
).toEqual([
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
'Probabilidad LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
]);
});
});
+4 -1
View File
@@ -16,7 +16,10 @@ export interface CurveModel {
const percent = (n: number) =>
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 });
const title = (m: CurveModel) => m.text.replace(/ v\d+$/, '');
const title = (m: CurveModel) =>
m.text
.replace(/ v\d+$/, '')
.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'));
const interval = (p: CurvePrediction) => p.low !== undefined && p.high !== undefined;
/** The institutional models' risk by horizon: one series per model, drawn only at the horizons it
+49 -7
View File
@@ -1,4 +1,4 @@
import { horizon, riskGroups, riskScales } from './risk-scales';
import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
@@ -35,9 +35,9 @@ describe('the risk scales', () => {
{ text: 'Recurrencia v2', index: '2026-03-01', predictions: [at(5, 0.98)] },
{ text: 'Otro', index: '2026-03-02', predictions: [at(3, 0.3)] }, // no horizon of its own
]);
expect(groups.map((g) => g.title)).toEqual(['Supervivencia v3', 'Recurrencia v2', 'Otro']);
expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años'];
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]);
@@ -48,15 +48,57 @@ describe('the risk scales', () => {
expect(rest).toEqual([]);
expect(none.title).toBeUndefined();
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
['Riesgo inmediato (al índice)', undefined],
['Riesgo a 5 años', undefined],
['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, riesgo inmediato',
'M, riesgo a 5 años',
'M, probabilidad inmediata',
'M, probabilidad a 5 años',
]);
});
});
describe('which models feed the risk scales', () => {
it('excludes survival and recurrence estimates, which are not risks of the scales outcome', () => {
expect(['cacu.cin2_pim', 'cacu.cancer_pim', 'cacu.cin2_logistic'].every(isRiskModel)).toBe(
true,
);
expect(isRiskModel('cacu.survival')).toBe(false);
expect(isRiskModel('cama.recurrence')).toBe(false);
});
it('with no risk model both horizons are unavailable (nothing is converted from a survival)', () => {
const risk = [
{
text: 'm',
index: '2026-01-01',
predictions: [{ years: 5, p: 0.7 }],
model: 'cacu.survival',
},
].filter((m) => isRiskModel(m.model));
expect(riskGroups(risk).flatMap((g) => g.scales.map((s) => s.risk))).toEqual([
undefined,
undefined,
]);
});
});
describe('survival scales', () => {
it('complements mortality and reverses interval bounds at every published horizon', () => {
const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
expect(g.survival).toBe(true);
expect(g.index).toBe('2026-01-01');
expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
});
it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
.toEqual(inputs);
expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
.toBeUndefined();
});
});
+195 -17
View File
@@ -12,11 +12,16 @@ export interface RiskScale {
risk?: Prediction;
}
/** Whether a model's estimate is a risk of the outcome the scales and curves draw. Survival (S(t)) and
* recurrence-free survival are estimates of another outcome, shown in their own analysis: they are
* never drawn on these scales, and no conversion (1 − S) is made. */
export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(model);
/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) =>
[0, 5].map((years) => ({
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`,
label: `${m.text.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'))}, probabilidad ${years ? 'a 5 años' : 'inmediata'}`,
risk: m.predictions.find((p) => p.years === years),
})),
);
@@ -41,24 +46,92 @@ export function horizon(predictions: Prediction[], years: number): Prediction |
export interface RiskGroup {
/** the model's own title and the day it was scored (none: no model has scored her) */
title?: string;
scenario?: string;
index?: string;
survival?: boolean;
inputs?: Record<string, unknown>;
/** the model and version that scored her, and the day it did */
model?: string;
evaluated?: string;
scales: { label: string; risk?: Prediction }[];
}
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(
models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
text?: string;
evaluated?: string;
}[],
): RiskGroup[] {
return models
.map((m) => ({
title: 'Supervivencia',
index: m.index,
survival: true,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '),
scales: m.predictions.flatMap((p) => {
const v = horizon(m.predictions, p.years);
return v
? [
{
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
}))
.filter((g) => g.scales.length);
}
const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'],
[0, 'Probabilidad inmediata (al índice)'],
[5, 'Probabilidad a 5 años'],
];
/** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */
export function titleParts(text: string): { title: string; scenario?: string } {
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
return {
title: title.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad')),
scenario,
};
}
/** The scales the page draws: both horizons of every model, or, with no model, both horizons
* unavailable. */
export function riskGroups(
models: { text: string; index: string; predictions: Prediction[] }[],
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) => ({ title: m.text, index: m.index, scales: scales(m.predictions) }))
? models.map((m) => ({
...titleParts(m.text),
index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions),
}))
: [{ scales: scales([]) }];
}
@@ -69,12 +142,9 @@ export function riskGroups(
selector: 'app-risk-scales',
imports: [DecimalPipe],
template: `
@if (groups().length) {
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
}
@for (g of groups(); track $index) {
@if (g.title) {
<h3>{{ g.title }}{{ g.index ? ' · fecha índice ' + g.index : '' }}</h3>
<h3>{{ g.title }}</h3>
}
@for (s of g.scales; track s.label) {
<div class="risk-scale" [attr.data-scale]="s.label">
@@ -82,18 +152,24 @@ export function riskGroups(
<strong>{{ s.label }}</strong>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{
r.high * 100 | number: '1.1-2'
}}
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }}
%
}
} @else {
· No disponible
}
</p>
<div class="risk-plot" [class.unavailable]="!s.risk">
<div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
<span
class="risk-interval"
[style.left.%]="r.low * 100"
[style.width.%]="(r.high - r.low) * 100"
aria-hidden="true"
></span>
}
<span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
<strong
class="risk-value"
@@ -107,12 +183,60 @@ export function riskGroups(
</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: `
.note {
margin: 0 0 8px;
}
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
@@ -121,7 +245,7 @@ export function riskGroups(
margin: 0;
}
.risk-plot {
padding-top: 24px;
padding-top: 30px;
position: relative;
}
.risk-line {
@@ -143,6 +267,35 @@ export function riskGroups(
#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;
@@ -169,4 +322,29 @@ export function riskGroups(
})
export class RiskScales {
readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries;
protected readonly inputName = (name: string) =>
(
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: '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+',
);
});
});
+117
View File
@@ -0,0 +1,117 @@
import { Component, computed, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
import { CurveChooser } from './curve-chooser';
import { curveFigure } from './risk-curve';
export interface SeriesPoint {
years: number;
p: number;
low?: number;
high?: number;
}
/** One series of `$risk-series`: a source, an outcome and her variables. */
export interface Series {
id: string;
source: string;
outcome: string;
label: string;
resolved: boolean;
reasons: string[];
assumptions: string[];
points: SeriesPoint[];
}
const OUTCOME_TEXT: Record<string, string> = {
'CIN2+': 'LIEAG+ (CIN2+)',
'CIN3+': 'CIN3+',
cancer: 'Cáncer',
};
export const seriesName = (s: Series) => {
const outcome = OUTCOME_TEXT[s.outcome] ?? s.outcome;
if (s.source === 'NCI (tabla de ingreso)')
return `NCI, ingreso a ${outcome.replace(' (CIN2+)', '').replace(/^Cáncer$/, 'cáncer')}`;
// the platform's own models are the hospital's: its name, and the outcome without its synonym
return s.source === 'Institucional'
? `ISSSTELEON, ${outcome.replace(' (CIN2+)', '')}`
: `${s.source} · ${outcome}`;
};
/** The series of the answer. A value absent from it stays absent. */
export function parseSeries(answer: Parameters): Series[] {
const all = (parts: ParametersParameter[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const one = (parts: ParametersParameter[] | undefined, name: string) => all(parts, name)[0];
return all(answer.parameter, 'series').map(({ part }) => ({
id: one(part, 'id')?.valueString ?? '',
source: one(part, 'source')?.valueString ?? '',
outcome: one(part, 'outcome')?.valueString ?? '',
label: one(part, 'label')?.valueString ?? '',
resolved: one(part, 'status')?.valueCode === 'resolved',
reasons: all(part, 'reason').map((r) => r.valueCode ?? ''),
assumptions: all(part, 'assumption').map((a) => a.valueString ?? ''),
points: all(part, 'point').map(({ part: at }) => ({
years: one(at, 'years')?.valueInteger ?? 0,
p: one(at, 'probability')?.valueDecimal ?? 0,
low: one(at, 'low')?.valueDecimal,
high: one(at, 'high')?.valueDecimal,
})),
}));
}
/** The chosen series as curves. Series are shown side by side; no difference is computed. */
@Component({
selector: 'app-risk-series',
imports: [CurveChooser],
template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
@if (available().length) {
<app-curve-chooser [choices]="choices()" [draw]="draw()" [notes]="assumptions()" />
} @else {
<p class="muted">No disponible: datos insuficientes.</p>
}
`,
styles: `
:host {
display: block;
}
`,
})
export class RiskSeries {
readonly series = input.required<Series[]>();
protected readonly available = computed(() => this.series().filter((s) => s.points.length));
/** the platform's own series are drawn until the user says otherwise */
protected readonly choices = computed(() =>
this.available().map((s) => ({
id: s.id,
name: seriesName(s),
on: s.source === 'Institucional',
})),
);
private readonly among = computed(() => {
const all = this.available();
return (ids: Set<string>) => all.filter((s) => ids.has(s.id));
});
/** what the chosen series assume, each said once */
protected readonly assumptions = computed(() => {
const chosen = this.among();
return (ids: Set<string>) => [...new Set(chosen(ids).flatMap((s) => s.assumptions))];
});
protected readonly draw = computed(() => {
const chosen = this.among();
return (ids: Set<string>) => {
const shown = chosen(ids).map((s) => ({
model: s.id,
text: seriesName(s),
index: '',
predictions: s.points,
}));
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
const figure = curveFigure(shown, top);
// sources do not share an index date: the axis says only the horizon
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure;
};
});
}
+1 -1
View File
@@ -113,7 +113,7 @@ export function interval(from?: string, to?: string, inferred = false): string {
<span>{{
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
}}</span>
@if (s.origin) {
@if (s.origin && s.origin !== 'Formulario de citología') {
<span class="origin">Procedencia: {{ s.origin }}</span>
}
<span class="interval">Desde anterior: {{ s.previous }}</span>
@@ -0,0 +1,49 @@
import { combinationOf, noCurveText, survivalFigure } from './survival-combination';
describe('combinationOf', () => {
const values = { age_group: '<30', cytology: 'NA', hpv: 'positive' };
const report = { km_combinaciones: [{ valores: values, n: 9, fallecidos: 6 }] };
it('takes only the entry with all her values, a missing one as NA', () => {
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'positive' })?.n).toBe(9);
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'negative' })).toBe(
undefined,
);
expect(combinationOf(report, { age_group: '<30' })).toBe(undefined);
expect(combinationOf({}, values)).toBe(undefined);
});
it('tells an old report apart from a combination with too few deaths', () => {
expect(noCurveText({}, undefined)).toContain('no publica esta curva');
expect(
noCurveText(
{ ...report, min_fallecidos_escenario: 5 },
{ valores: values, n: 9, fallecidos: 2 },
),
).toContain('n = 9, fallecidos = 2; mínimo requerido: 5');
});
it('draws every fit the report has, and the Kaplan-Meier alone in an older report', () => {
const km = { months: [0, 1], S: [1, 0.9], low: [1, 0.8], high: [1, 0.95] };
const old = { valores: values, n: 9, fallecidos: 6, km };
expect(survivalFigure(old).data.map((t) => (t as { name?: string }).name)).toContain(
'Kaplan-Meier',
);
const fit = { t: [0, 1], S: [1, 0.9] };
const full = {
...old,
weibull: fit,
weibull_fractional: fit,
points: { COMB: { S: [0.9] } },
horizons_months: [12],
};
const names = survivalFigure(full).data.map((t) => (t as { name?: string }).name);
expect(names).toEqual(
expect.arrayContaining([
'Weibull',
'Weibull fraccional',
'LR + HBN combinado (IC 95 % bootstrap)',
]),
);
});
});
+74
View File
@@ -0,0 +1,74 @@
import { scenarioFigure } from '../gobernanza/figures';
import { Figure, PALETTE } from '../plot';
/** All the fits the report has for her values, drawn as a clinical scenario's are. */
export function survivalFigure(c: Combination): Figure {
return c.weibull && c.weibull_fractional && c.points && c.horizons_months
? scenarioFigure('', c, c.horizons_months, 'Supervivencia S(t)').figure
: combinationFigure(c.km!);
}
/** One entry of the survival report's `km_combinaciones`: the patients who share every value. */
export interface Combination {
valores: Record<string, string>;
n: number;
fallecidos: number;
km?: { months: number[]; S: number[]; low: number[]; high: number[] };
/** the other fits; a report from before they were published has the Kaplan-Meier only */
weibull?: { t: number[]; S: number[] };
weibull_fractional?: { t: number[]; S: number[] };
points?: { COMB: { S: number[]; low?: number[]; high?: number[] } };
horizons_months?: number[];
}
/** The entry with exactly her values (a missing one is the report's "NA"); never a partial match. */
export function combinationOf(
report: Record<string, unknown> | null | undefined,
inputs: Record<string, unknown>,
): Combination | undefined {
const all = report?.['km_combinaciones'];
return (Array.isArray(all) ? (all as Combination[]) : []).find((c) => {
const keys = Object.keys(c.valores);
return (
keys.length === Object.keys(inputs).length &&
keys.every((k) => k in inputs && c.valores[k] === String(inputs[k] ?? 'NA'))
);
});
}
/** Why there is no curve for her: these are not the same thing, so each is said apart. (A patient
* outside the survival scenario has no survival section at all.) */
export function noCurveText(
report: Record<string, unknown> | null | undefined,
found: Combination | undefined,
): string {
if (!Array.isArray(report?.['km_combinaciones']))
return 'No disponible: la versión del modelo que la evaluó no publica esta curva.';
const minimum = report['min_fallecidos_escenario'];
const counts = `n = ${found?.n ?? 0}, fallecidos = ${found?.fallecidos ?? 0}`;
return `No disponible: datos insuficientes para su combinación de valores (${counts}${
typeof minimum === 'number' ? `; mínimo requerido: ${minimum} fallecidos` : ''
}).`;
}
export function combinationFigure(km: NonNullable<Combination['km']>): Figure {
const line = (y: number[], more: object) => ({
type: 'scatter',
mode: 'lines',
x: km.months,
y,
line: { shape: 'hv', color: PALETTE[0], width: 0 },
...more,
});
return {
data: [
line(km.low, { showlegend: false, hoverinfo: 'skip' }),
line(km.high, { name: 'IC 95 %', fill: 'tonexty', fillcolor: 'rgba(23, 50, 77, 0.15)' }),
line(km.S, { name: 'Kaplan-Meier', line: { shape: 'hv', color: PALETTE[0], width: 2 } }),
],
layout: {
xaxis: { title: { text: 'Meses desde el índice' } },
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [0, 1.02], tickformat: '.0%' },
},
} as Figure;
}
+102
View File
@@ -0,0 +1,102 @@
import { scenarioFigure } from '../gobernanza/figures';
import { insufficientText, sortUndrawn } from './survival-scenarios';
const base = (over: object = {}) => ({
km: {
months: [0, 12, 24, 36],
S: [1, 0.9, 0.8, 0.7],
low: [1, 0.8, 0.7, 0.55],
high: [1, 0.95, 0.9, 0.82],
},
weibull: { t: [0, 36], S: [1, 0.7] },
weibull_fractional: { t: [0, 36], S: [1, 0.72] },
points: { COMB: { S: [0.9, 0.7], low: [0.8, 0.55], high: [0.95, 0.82] } },
...over,
});
const draw = (e: object) => scenarioFigure('t', e, [12, 36], 'S(t)').figure.data as any[];
const bands = (d: any[]) => d.filter((t) => t.fill === 'toself');
const model = (d: any[]) => d.find((t) => t.name?.startsWith('LR + HBN'));
describe('survival curves with absent values', () => {
it('complete data draw one band and symmetric-free error bars, as before', () => {
const d = draw(base());
expect(bands(d).length).toBe(1);
expect(bands(d)[0].x.length).toBe(8);
expect(model(d).error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.05, 0.12]);
expect(model(d).error_y.arrayminus.map((v: number) => +v.toFixed(2))).toEqual([0.1, 0.15]);
});
it('a band is drawn only where both limits exist, never from an absent one', () => {
const km = {
months: [0, 12, 24, 36, 48],
S: [1, 0.9, 0.8, 0.7, 0.6],
low: [1, 0.8, null, 0.55, 0.4],
high: [1, 0.95, null, 0.82, 0.7],
};
const d = draw(base({ km }));
expect(bands(d).map((b) => b.x.length)).toEqual([4, 4]); // [0,12] and [36,48]; each polygon out and back
for (const b of bands(d)) expect(b.y.every((v: unknown) => typeof v === 'number')).toBe(true);
const none = draw(
base({
km: { ...km, low: [null, null, null, null, null], high: [null, null, null, null, null] },
}),
);
expect(bands(none).length).toBe(0); // no limits: no band at all
expect(none.find((t) => t.name?.startsWith('Kaplan')).y).toEqual([1, 0.9, 0.8, 0.7, 0.6]); // the curve stays
});
it('a point without its limits has no bar; zero is a value and unavailable is not drawn', () => {
const d = draw(
base({ points: { COMB: { S: [0, null], low: [null, null], high: [null, null] } } }),
);
const m = model(d);
expect(m.y).toEqual([0, null]); // 0 % is drawn at 0, an absent value is a gap
expect(m.error_y).toBeUndefined(); // no invented limits
expect(model(draw(base({ points: { COMB: { S: [0, null] } } }))).error_y).toBeUndefined();
const half = model(
draw(base({ points: { COMB: { S: [0.9, 0.7], low: [0.8, null], high: [0.95, null] } } })),
);
expect(half.error_y.array).toEqual([expect.closeTo(0.05, 5), null]);
expect(half.error_y.arrayminus).toEqual([expect.closeTo(0.1, 5), null]);
});
});
describe('scenarios without a curve', () => {
const report = {
escenarios_sin_curvas: [
{ escenario: 'VPH negativo', n: 9, fallecidos: 2 },
{ escenario: 'Citología · ASC-H', n: 0, fallecidos: 0 },
],
min_fallecidos_escenario: 5,
};
it('those the report lists as lacking deaths keep its numbers and the minimum', () => {
expect(sortUndrawn(report, ['VPH negativo', 'Citología · ASC-H']).insufficient).toEqual([
{ name: 'VPH negativo', n: 9, deaths: 2, minimum: 5 },
{ name: 'Citología · ASC-H', n: 0, deaths: 0, minimum: 5 }, // zero deaths is a count, not a gap
]);
});
it('one the report does not mention is absent, never "insufficient"', () => {
expect(sortUndrawn(report, ['VPH negativo', 'Edad · 45-54']).missing).toEqual(['Edad · 45-54']);
expect(sortUndrawn({}, ['a'])).toEqual({ insufficient: [], missing: ['a'] });
expect(sortUndrawn(null, ['a'])).toEqual({ insufficient: [], missing: ['a'] });
expect(sortUndrawn({ escenarios_sin_curvas: 'x' }, ['a']).missing).toEqual(['a']);
});
it('a listing without counts is still insufficient, without inventing numbers', () => {
expect(
sortUndrawn({ escenarios_sin_curvas: [{ escenario: 'a' }] }, ['a']).insufficient,
).toEqual([{ name: 'a', n: undefined, deaths: undefined, minimum: undefined }]);
});
});
describe('the insufficient-data text', () => {
it("says the report's numbers and leaves out the ones it did not give", () => {
expect(insufficientText({ name: 'a', n: 9, deaths: 2, minimum: 5 })).toBe(
'Datos insuficientes para trazar la curva (n = 9, fallecidos = 2; mínimo requerido: 5 fallecidos).',
);
expect(insufficientText({ name: 'a', n: 0, deaths: 0 })).toBe(
'Datos insuficientes para trazar la curva (n = 0, fallecidos = 0).',
);
expect(insufficientText({ name: 'a', n: null, deaths: 0, minimum: 5 })).toBe(
'Datos insuficientes para trazar la curva (fallecidos = 0; mínimo requerido: 5 fallecidos).',
);
expect(insufficientText({ name: 'a' })).toBe('Datos insuficientes para trazar la curva.');
});
});
+51
View File
@@ -0,0 +1,51 @@
/** A scenario the report says has too few deaths for a curve, with its counts and the minimum. */
export interface Insufficient {
name: string;
n?: number | null;
deaths?: number | null;
minimum?: number;
}
/** Her scenarios without a curve, apart: those the report lists as lacking deaths (with the numbers it
* gives) and those it does not mention at all. */
export function sortUndrawn(
report: Record<string, unknown> | null | undefined,
undrawn: string[],
): { insufficient: Insufficient[]; missing: string[] } {
const listed = (
Array.isArray(report?.['escenarios_sin_curvas']) ? report['escenarios_sin_curvas'] : []
) as {
escenario?: string;
n?: number | null;
fallecidos?: number | null;
}[];
const minimum =
typeof report?.['min_fallecidos_escenario'] === 'number'
? report['min_fallecidos_escenario']
: undefined;
const insufficient: Insufficient[] = [];
const missing: string[] = [];
for (const name of undrawn) {
const found = listed.find((s) => s.escenario === name);
if (found) insufficient.push({ name, n: found.n, deaths: found.fallecidos, minimum });
else missing.push(name);
}
return { insufficient, missing };
}
/** What the section says of a scenario the report lists as lacking deaths; the numbers are the
* report's and a missing one is left out, never replaced. */
export function insufficientText(u: Insufficient): string {
const fmt = (v: number) => v.toLocaleString('es-MX');
const counts = [
typeof u.n === 'number' ? `n = ${fmt(u.n)}` : '',
typeof u.deaths === 'number' ? `fallecidos = ${fmt(u.deaths)}` : '',
]
.filter(Boolean)
.join(', ');
const details = [
counts,
u.minimum !== undefined ? `mínimo requerido: ${fmt(u.minimum)} fallecidos` : '',
].filter(Boolean);
return `Datos insuficientes para trazar la curva${details.length ? ` (${details.join('; ')})` : ''}.`;
}
+6 -1
View File
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
export class Plot implements OnDestroy {
readonly figure = input.required<Figure>();
readonly height = input(320);
/** Plotly's buttons over the chart; a record's curves go without them */
readonly toolbar = input(true);
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() {
effect(() => {
const { data, layout } = this.figure();
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG);
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
...CONFIG,
...(this.toolbar() ? {} : { displayModeBar: false }),
});
});
}
+1
View File
@@ -28,6 +28,7 @@ type Entity = Rejection['entity'];
type Row = Record<string, unknown>;
const ENTITIES: Record<Entity, string> = {
cacu_eligibility_evidence: 'Evidencia de elegibilidad CaCu',
cervical_cytology: 'Citología cervical',
cervical_biopsy: 'Biopsia cervical',
clinical_note: 'Nota médica',