Compare commits

...

27 Commits

Author SHA1 Message Date
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
53 changed files with 2620 additions and 539 deletions
+12 -12
View File
@@ -9,7 +9,7 @@ test.beforeEach(async ({ page }) => {
const ROUND = { name: 'Por detección inicial y subsecuente' }; 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_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 = { const TITLES = {
cytology: 'Distribución de resultados citológicos', cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo', genotype: 'Resultados de VPH por genotipo',
@@ -28,9 +28,7 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
const headings = await tab const headings = await tab
.locator('h2, app-readings h3') .locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([ expect(headings.slice(headings.indexOf('Indicadores clínicos'))).toEqual([
'Indicadores de oportunidad',
'Días de la ruta del tamizaje',
'Indicadores clínicos', 'Indicadores clínicos',
'Resultados de citología, VPH y biopsia', 'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos', 'Distribución de resultados citológicos',
@@ -38,9 +36,11 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
'Resultados de biopsia cervical', 'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica', 'Tasa de confirmación histopatológica',
'Tasa de confirmación histopatológica de referencia a 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(); const route = tab.locator('app-readings').filter({ has: page.getByRole('heading', { name: 'Tiempos de tamizaje' }) });
for (const mode of ['Por pasos', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) { for (const mode of ['Por ventana de tiempo', 'Diagnóstico precolposcópico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click(); await route.getByRole('radio', { name: mode }).click();
await expect( await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')), route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
@@ -107,12 +107,12 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
await expect( await expect(
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }), tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible(); ).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click(); await expect(tab.getByRole('radio', { name: 'Solicitudes' })).toHaveCount(0);
}); });
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => { test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const list = page.locator('table.worklist tbody tr'); const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5); await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click(); await list.first().getByRole('button', { name: 'Detalle' }).click();
@@ -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). */ /** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first(); 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. */ * each category (the first group's rows), in hex. */
const traces = (readings: Locator) => const traces = (readings: Locator) =>
readings.evaluate((el) => { readings.evaluate((el) => {
@@ -202,7 +202,7 @@ const traces = (readings: Locator) =>
return { return {
y: groups.map( y: groups.map(
(g) => (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)), x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries( colours: Object.fromEntries(
@@ -277,7 +277,7 @@ for (const card of ['cytology', 'genotype'] as const) {
const { card: of, view } = await withRounds(page, 'no-initial'); const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name); await view(ROUND.name);
const found = await traces(of(TITLES[card])); 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); expect(found.x[0]).toBe(0);
}); });
@@ -307,7 +307,7 @@ test('rondas (simulado): the genotype card never shows the incomplete positives,
'VPH 16', 'VPH 16',
'VPH 18', 'VPH 18',
'VPH 16 y 18', 'VPH 16 y 18',
'Positivo', 'Positivo sin genotipo',
]); ]);
for (const name of VIEWS.slice(1)) { for (const name of VIEWS.slice(1)) {
await view(name); 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);
});
+2 -2
View File
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
/** The record of the first patient of the risk list, as an address. */ /** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> { async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const link = page.locator('table.worklist tbody tr a').first(); const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 }); await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!; const url = (await link.getAttribute('href'))!;
@@ -1587,7 +1587,7 @@ test('elegibilidad (simulado): a new patient never inherits the previous risk ex
await open(page, firstUrl); await open(page, firstUrl);
await expect(reason).toBeVisible(); await expect(reason).toBeVisible();
await page.getByRole('link', { name: 'Regresar' }).click(); await page.getByRole('link', { name: 'Regresar' }).click();
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click(); await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click();
await expect(historial(page)).toBeVisible({ timeout: 120_000 }); await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible(); await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
+32 -17
View File
@@ -58,14 +58,14 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
); );
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Histórico' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9); await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const bundle = await (await list).json(); const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource; const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10); const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
@@ -85,13 +85,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama'); await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr'); const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS'); await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea'); await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
expect(problems).toEqual([]); expect(problems).toEqual([]);
}); });
@@ -208,8 +208,8 @@ const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) { for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => { test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Seguimiento', exact: true })).toHaveCount(1); await expect(page.getByRole('tab', { name: 'Análisis de Riesgo', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Histórico', exact: true })).toHaveCount(1); await expect(page.getByRole('tab', { name: 'Trazabilidad', exact: true })).toHaveCount(1);
const labels = await page.getByRole('tab').allTextContents(); const labels = await page.getByRole('tab').allTextContents();
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length); expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
}); });
@@ -226,22 +226,17 @@ for (const domain of ['cama', 'tea']) {
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico', (i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
); );
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos'); 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 // The histopathology figures are two cards: the result by BI-RADS and the confirmation.
// 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;
const results = all.findIndex( 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 = [ 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 { kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
]; ];
const old = const old =
domain === 'cama' 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; : all;
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores'); const tab = page.locator('app-tab-indicadores');
@@ -251,9 +246,29 @@ for (const domain of ['cama', 'tea']) {
.locator('h2, h3') .locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad'); const from = headings.indexOf('Indicadores de oportunidad');
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( expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)), old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
); );
}
// Each figure drawn is one of the old kinds (a figure with no data in the period is named). // Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab const drawn = await tab
.locator('.js-plotly-plot') .locator('.js-plotly-plot')
@@ -278,7 +293,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
['h2', 'h3', 'plot'].includes(i.kind), ['h2', 'h3', 'plot'].includes(i.kind),
); );
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Histórico' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad'); const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
+292
View File
@@ -42,8 +42,10 @@
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5", "@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"vitest": "^5.0.0" "vitest": "^5.0.0"
@@ -2013,6 +2015,283 @@
"win32" "win32"
] ]
}, },
"node_modules/@napi-rs/canvas": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz",
"integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==",
"dev": true,
"license": "MIT",
"optional": true,
"workspaces": [
"e2e/*"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/canvas-android-arm64": "1.2.1",
"@napi-rs/canvas-darwin-arm64": "1.2.1",
"@napi-rs/canvas-darwin-x64": "1.2.1",
"@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1",
"@napi-rs/canvas-linux-arm64-gnu": "1.2.1",
"@napi-rs/canvas-linux-arm64-musl": "1.2.1",
"@napi-rs/canvas-linux-riscv64-gnu": "1.2.1",
"@napi-rs/canvas-linux-x64-gnu": "1.2.1",
"@napi-rs/canvas-linux-x64-musl": "1.2.1",
"@napi-rs/canvas-win32-arm64-msvc": "1.2.1",
"@napi-rs/canvas-win32-x64-msvc": "1.2.1"
}
},
"node_modules/@napi-rs/canvas-android-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz",
"integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz",
"integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-x64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz",
"integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz",
"integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz",
"integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz",
"integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz",
"integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==",
"cpu": [
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz",
"integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz",
"integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz",
"integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz",
"integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/nice": { "node_modules/@napi-rs/nice": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz",
@@ -6077,6 +6356,19 @@
"url": "https://github.com/fb55/entities?sponsor=1" "url": "https://github.com/fb55/entities?sponsor=1"
} }
}, },
"node_modules/pdfjs-dist": {
"version": "6.5.438",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
"integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=22.13.0 || >=24"
},
"optionalDependencies": {
"@napi-rs/canvas": "^1.0.13"
}
},
"node_modules/pdfkit": { "node_modules/pdfkit": {
"version": "0.20.2", "version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz", "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
+2
View File
@@ -46,8 +46,10 @@
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5", "@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"vitest": "^5.0.0" "vitest": "^5.0.0"
+153 -11
View File
@@ -3,6 +3,64 @@ import { scenarioBars } from './figures';
import { Reading } from './measures'; import { Reading } from './measures';
describe('bars', () => { describe('bars', () => {
it('shows histologic types by BI-RADS while deriving malignancy from biopsy classification', () => {
const type: Reading = {
populations: {},
strata: {
category: { '8500/3': { 'initial-population': 1 }, no_data: { 'initial-population': 1 } },
birads: { '4A': { 'initial-population': 2 } },
'birads-category': {
'4A|8500/3': { 'initial-population': 1 },
'4A|no_data': { 'initial-population': 1 },
},
},
};
const classification: Reading = {
populations: {},
strata: {
'birads-category': {
'4A|benign': { 'initial-population': 1 },
'4A|invasive': { 'initial-population': 1 },
},
},
};
const mode: Mode = {
kind: 'outcomes',
label: 'Por categoría BI-RADS',
measure: 'types',
stratum: 'birads',
rows: [{ code: '4A', label: '4A', color: '#000' }],
results: [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#aaa' },
{ code: 'no_data', label: 'Sin dato', color: '#bbb' },
],
malignant: ['in_situ', 'invasive'],
dynamicResults: true,
malignancyMeasure: 'grades',
};
const table = bars(mode, (key) => (key === 'types' ? type : classification))!;
expect(table.head).toEqual(['Pacientes', 'Carcinoma ductal infiltrante', 'Sin biopsia', 'Sin dato', '% maligno']);
expect(table.rows[0].cells).toEqual(['2', '1', '0', '1', '1/2 (50.0 %)']);
expect(bars(mode, (key) => (key === 'types' ? type : undefined))!.rows[0].cells.at(-1)).toBe(
'No disponible',
);
});
it('lists histologic codes from gold and preserves missing types in the denominator', () => {
const r: Reading = {
populations: { 'initial-population': 4 },
strata: {
category: { '8500/3': { 'initial-population': 1 }, no_data: { 'initial-population': 3 } },
},
};
const table = bars(
{ kind: 'counts', label: 'Tipos histológicos', measure: 'M', catalog: [], unit: 'Biopsias' },
() => r,
)!;
expect(table.rows.map((row) => [row.label, ...row.cells])).toEqual([
['Carcinoma ductal infiltrante', '1', '25.0 %'],
['Sin dato', '3', '75.0 %'],
]);
});
it('list every category, so the shares add up', () => { it('list every category, so the shares add up', () => {
const r: Reading = { const r: Reading = {
populations: {}, populations: {},
@@ -17,6 +75,41 @@ describe('bars', () => {
['1', '25.0 %'], ['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', () => { it('a group with no patients has no rate', () => {
const r: Reading = { const r: Reading = {
populations: {}, populations: {},
@@ -47,7 +140,7 @@ describe('bars', () => {
const t = bars(mode, () => r)!; const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([ expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial', 'Detección inicial',
'Detección subsecuente', 'Con detección anterior',
'Sin dato', 'Sin dato',
]); ]);
expect(t.rows.map((x) => x.cells)).toEqual([ expect(t.rows.map((x) => x.cells)).toEqual([
@@ -145,7 +238,7 @@ describe('bars', () => {
c === 'initial' c === 'initial'
? 'Detección inicial' ? 'Detección inicial'
: c === 'subsequent' : c === 'subsequent'
? 'Detección subsecuente' ? 'Con detección anterior'
: 'Sin dato', : 'Sin dato',
['initial', 'subsequent', 'no_data'], ['initial', 'subsequent', 'no_data'],
{ fill: true }, { fill: true },
@@ -157,15 +250,15 @@ describe('bars', () => {
); );
const y = (f.data[0] as any).y; const y = (f.data[0] as any).y;
expect(y).toEqual([ expect(y).toEqual([
'Detección inicial<br>n = 0', 'Detección inicial<br>Pacientes: 0',
'Detección subsecuente<br>n = 8', 'Con detección anterior<br>Pacientes: 8',
'Sin dato<br>n = 2', 'Sin dato<br>Pacientes: 2',
]); ]);
expect((f.data[0] as any).x).toEqual([0, 75, 100]); expect((f.data[0] as any).x).toEqual([0, 75, 100]);
}); });
it('leaves out a group that does not reconcile', () => { it('leaves out a group that does not reconcile', () => {
const f = draw(reading({ 'subsequent|NILM': 6 }, 10)); 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', () => { describe('shared views of cytology and HPV by genotype', () => {
const HPV = [ const HPV = [
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' }, { 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 => ({ const reading = (cells: Record<string, number>): Reading => ({
populations: { 'initial-population': Object.values(cells).reduce((a, b) => a + b, 0) }, 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', () => { it('does not list a hidden category but keeps it in the total and the percentages', () => {
const t = bars(counts, () => reading({}))!; 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([ expect(t.rows.map((x) => x.cells)).toEqual([
['5', '50.0 %'], ['5', '50.0 %'],
['2', '20.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((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).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([ expect(g.groups.map((x) => [x.label, x.total])).toEqual([
['Detección inicial', 4], ['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([ expect(g.groups[0].rows.map((r) => [r.label, r.text, r.percent, r.color])).toEqual([
['Normal', '3/4 · 75.0 %', 75, '#408651'], ['Normal', '3/4 · 75.0 %', 75, '#408651'],
@@ -300,7 +393,7 @@ describe('independent bars by group', () => {
['0/0 · —', undefined], ['0/0 · —', undefined],
['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 }), () => const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5), 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']); 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],
]);
});
});
+184 -41
View File
@@ -1,4 +1,5 @@
import { CIE10 } from './cie10'; import { CIE10 } from './cie10';
import { chainStarts } from './durations';
import { NEUTRAL_DARK } from './cacu-palette'; import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures'; import { name, Reading } from './measures';
@@ -16,6 +17,11 @@ export type Mode = {
kind: 'counts'; kind: 'counts';
measure: string; measure: string;
catalog: Category[]; 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; hidden?: Hidden;
/** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */ /** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
percent?: boolean; percent?: boolean;
@@ -27,6 +33,7 @@ export type Mode = {
order: string[]; order: string[];
complete?: boolean; complete?: boolean;
colors?: Colors; colors?: Colors;
percentLabel?: string;
} }
| { | {
kind: 'positives'; kind: 'positives';
@@ -35,28 +42,54 @@ export type Mode = {
order: string[]; order: string[];
complete?: boolean; complete?: boolean;
colors?: Colors; colors?: Colors;
percentLabel?: string;
}
| {
kind: 'signs';
measure: string;
strata: string[];
colors?: Colors;
percentLabel?: string;
} }
| { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
| { | {
kind: 'grouped'; kind: 'grouped';
measure: string; measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */ /** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[]; catalog: Category[];
aggregate?: { label: string; color: string; codes: string[] };
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */ /** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
stratum: string; stratum: string;
order: string[]; order: string[];
/** what the records are called ("pacientes", "reportes") */ /** what the records are called ("pacientes", "reportes") */
unit: string; 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`) */ /** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
complete?: boolean; complete?: boolean;
/** each group's denominator is all its records, not only those of the catalog's categories */ /** each group's denominator is all its records, not only those of the catalog's categories */
ofAll?: boolean; ofAll?: boolean;
hidden?: Hidden; hidden?: Hidden;
} }
| { kind: 'days'; steps: { 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 } | { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */ /** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] } | {
kind: 'split';
measure: string;
yes: string;
no: string;
colors?: [string, string];
unit?: string;
percentLabel?: string;
}
/** Each row's units by result (a bar in segments), and the share of the row's units with a /** 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 */ * 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[]; rows: Category[];
results: Category[]; results: Category[];
malignant: string[]; malignant: string[];
dynamicResults?: boolean;
malignancyMeasure?: string;
} }
| { | {
kind: 'figure'; 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. */ /** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
export interface GroupRow { export interface GroupRow {
sub?: boolean;
label: string; label: string;
color: string; color: string;
count: number; 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. */ /** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar { export interface Bar {
/** one of the categories the aggregate row above adds up */
sub?: boolean;
label: string; label: string;
/** why the row has no figures: no patients in the group, or not available */ /** why the row has no figures: no patients in the group, or not available */
hint?: string; hint?: string;
color?: string; color?: string;
/** where the bar starts, in % of the scale */
offset?: number;
width: number; width: number;
marks: number[]; marks: number[];
cells: string[]; cells: string[];
@@ -146,10 +186,8 @@ export interface Bars {
export const NOT_AVAILABLE = 'No disponible'; export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo'; export const NO_PATIENTS = 'Sin pacientes en el periodo';
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 = 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; 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. */ /** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined { export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) { switch (mode.kind) {
case 'ratio': {
const r = of(mode.measure);
const n = r?.populations['numerator'] ?? 0;
const total = r?.populations['denominator'] ?? 0;
if (r?.score === undefined || !total) return undefined;
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return {
head: ['n/N', 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': { case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {}; const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0); const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
@@ -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)); const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return { return {
head: ['n', '%'], head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: all.map(({ code, label, color }) => { rows: all.flatMap(({ code, label, color }, index) => {
const n = size(cells[code]); const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)]; 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), note: hiddenNote(mode, of),
}; };
@@ -240,6 +311,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
cells[c]['denominator'] ?? 0, cells[c]['denominator'] ?? 0,
mode.colors?.[c], mode.colors?.[c],
]), ]),
mode.percentLabel,
); );
if (!patients(r) || !Object.keys(cells).length) return undefined; if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) => const sound = (c: string) =>
@@ -256,6 +328,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
ok, ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined), (c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors, mode.colors,
mode.percentLabel,
); );
} }
case 'positives': { case 'positives': {
@@ -270,6 +343,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const positive = size(cells[`${c}|positive`]); const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]]; return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
}), }),
mode.percentLabel,
); );
if (!patients(r) || !found.size) return undefined; if (!patients(r) || !found.size) return undefined;
const ok = reconciles( const ok = reconciles(
@@ -285,6 +359,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
return [positive, positive + size(cells[`${c}|negative`])]; return [positive, positive + size(cells[`${c}|negative`])];
}, },
mode.colors, mode.colors,
mode.percentLabel,
); );
} }
case 'signs': { case 'signs': {
@@ -296,6 +371,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const positive = size(strata[s]['positive']); const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]]; return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}), }),
mode.percentLabel,
); );
} }
case 'days': 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 }; return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}), }),
mode.tint, mode.tint,
mode.staggered,
); );
case 'days-by': { case 'days-by': {
const r = of(mode.measure); const r = of(mode.measure);
@@ -328,7 +405,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
[mode.no, denominator - numerator], [mode.no, denominator - numerator],
]; ];
return { return {
head: ['n', '%'], head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: parts.map(([label, n], i) => ({ rows: parts.map(([label, n], i) => ({
label, label,
color: mode.colors?.[i], 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 units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {}; const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined; 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 { return {
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'], head: ['Pacientes', ...results.map((x) => x.label), '% maligno'],
legend: mode.results.map(({ label, color }) => ({ label, color })), legend: results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => { rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]); const n = size(units[code]);
const by = mode.results.map((x) => size(cells[`${code}|${x.code}`])); const by = results.map((x) => size(cells[`${code}|${x.code}`]));
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0); const den = grades.reduce((t, grade) => t + size(malignancyCells[`${code}|${grade}`]), 0);
const bad = by.reduce( const bad = mode.malignant.reduce(
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0), (t, grade) => t + size(malignancyCells[`${code}|${grade}`]),
0, 0,
); );
return { return {
@@ -360,7 +454,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
width: 100, width: 100,
marks: [], marks: [],
none: n ? undefined : 'Sin pacientes en el periodo', 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, width: n ? (100 * by[i]) / n : 0,
color: x.color, color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`, title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
@@ -369,9 +463,11 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
`${n}`, `${n}`,
...by.map((k) => (n ? `${k}` : '—')), ...by.map((k) => (n ? `${k}` : '—')),
n n
? den ? !hasMalignancy
? 'No disponible'
: den
? `${bad}/${den} (${pct(bad, den)})` ? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')] : size(malignancyCells[`${code}|no_data`])
? 'Sin biopsias clasificables' ? 'Sin biopsias clasificables'
: 'Sin biopsias' : '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 /** 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 * 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`). */ * 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 cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))]; const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
if (!patients(r) || !found.length) return undefined; 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( const reconciled = reconciles(
Object.values(cells).map((c) => c['initial-population']), Object.values(cells).map((c) => c['initial-population']),
patients(r), patients(r),
@@ -408,28 +520,53 @@ export function grouped(
]; ];
const total = (g: string) => const total = (g: string) =>
mode.ofAll mode.ofAll
? Object.entries(cells) ? cellsOf(g).reduce((t, [, c]) => t + size(c), 0)
.filter(([k]) => k.split('|')[0] === g)
.reduce((t, [, c]) => t + size(c), 0)
: mode.catalog.reduce((t, c) => t + n(g, c.code), 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); const den = total(code);
return { return {
code, 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, total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`, 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 count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined; const percent = den ? (100 * count) / den : undefined;
return { const row = {
label: c.label, label: c.label,
color: c.color, color: c.color,
count, count,
of: den, of: den,
percent, percent,
sub: !!mode.aggregate?.codes.includes(c.code),
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`, 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,8 +579,6 @@ export function grouped(
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.' ? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
: none && unclassified : none && unclassified
? NO_ROUND ? NO_ROUND
: unclassified && classified.some((g) => !g.total)
? EMPTY_ROUND
: undefined; : undefined;
note = [sentence, note].filter(Boolean).join(' ') || undefined; note = [sentence, note].filter(Boolean).join(' ') || undefined;
} }
@@ -459,6 +594,7 @@ function complete(
reconciled: boolean, reconciled: boolean,
counts: (code: string) => [number, number] | undefined, counts: (code: string) => [number, number] | undefined,
colors: Colors = {}, colors: Colors = {},
percentLabel = 'Porcentaje',
): Bars { ): Bars {
const extra = listed.filter((c) => !order.includes(c)); const extra = listed.filter((c) => !order.includes(c));
const rows: Bar[] = [...order, ...extra].map((code) => { 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 classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0)); const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length; const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0;
return { return {
head: ['n/N', '%'], head: ['n/N', percentLabel],
rows, rows,
note: !reconciled note: !reconciled
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.' ? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
: none && listed.includes('no_data') : none && listed.includes('no_data')
? NO_ROUND ? 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; if (!rows.length) return undefined;
return { return {
head: ['n/N', '%'], head: ['n/N', percentLabel],
rows: rows.map(([label, n, total, color]) => ({ rows: rows.map(([label, n, total, color]) => ({
label, label,
color, color,
@@ -517,21 +652,29 @@ type Score = { score?: number; low?: number; high?: number };
function medians( function medians(
rows: { label: string; n: number; score?: Score }[], rows: { label: string; n: number; score?: Score }[],
tint?: Tint, tint?: Tint,
staggered?: boolean,
): Bars | undefined { ): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return 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; const at = (v: number) => (100 * v) / top;
return { return {
head: ['Mediana', 'n', 'Q1–Q3'], head: ['Mediana', 'Observaciones', 'Q1–Q3'],
markColor: tint?.mark, 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}`, '—'] }; if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : []; const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return { return {
label, label,
color: tint?.bar, color: tint?.bar,
offset: staggered ? at(starts[i]) : undefined,
width: at(s.score), 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('–') || '—'], 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', 'ASC-US': '#2778B8',
LSIL: '#B19525', LSIL: '#B19525',
'ASC-H': '#7955B1', 'ASC-H': '#7955B1',
CIN2: '#E07A9C',
HSIL: '#CE4778', HSIL: '#CE4778',
CIN3: '#BC4163',
CIS: '#AA394D', CIS: '#AA394D',
no_data: NEUTRAL, no_data: NEUTRAL,
}; };
@@ -43,7 +45,9 @@ export const HPV_COLORS: Record<string, string> = {
export const BIOPSY_COLORS: Record<string, string> = { export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651', normal: '#408651',
LSIL: '#B19525', LSIL: '#B19525',
CIN2: '#E07A9C',
HSIL: '#CE4778', HSIL: '#CE4778',
CIN3: '#BC4163',
CIS: '#AA394D', CIS: '#AA394D',
carcinoma: '#8D4C79', carcinoma: '#8D4C79',
cin1_plus: '#B19525', 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'; import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({ const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
@@ -53,3 +53,10 @@ describe('durationRows', () => {
expect(durationMax([])).toBe(0); 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 { export interface RouteStep {
label: string; label: string;
measure?: 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. /** One row of a duration table: the median days, how many measurements and the quartiles.
@@ -17,6 +19,25 @@ export interface DurationRow {
observations?: number; observations?: number;
low?: number; low?: number;
high?: 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 /** 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, read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean, published: (measure: string) => boolean,
): DurationRow[] { ): DurationRow[] {
return steps.map(({ label, measure }) => { return steps.map(({ label, measure, after }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' }; if (!measure || !published(measure)) return { label, after, status: 'unpublished' };
const r = read(measure); const r = read(measure);
if (r?.score === undefined) return { label, status: 'empty' }; if (r?.score === undefined) return { label, after, status: 'empty' };
return { return {
label, label,
after,
status: 'value', status: 'value',
median: r.score, median: r.score,
observations: r.populations['measure-observation'], 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 => 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), : catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
); );
const y = order 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); : scenarios.map(label);
return { return {
data: catalog.categories.map((c) => ({ data: catalog.categories.map((c) => ({
@@ -304,9 +304,11 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
line: { color: '#FFFFFF', width: 2 }, line: { color: '#FFFFFF', width: 2 },
}, },
// an empty slice says nothing (its label would sit on its neighbours') // an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')), texttemplate: values.map((v) =>
v ? `%{label}<br>%{percent} del total de ${center}` : '',
),
textposition: 'outside', textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>', hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`,
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { 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 type { Sheet } from '../export';
import { STATES } from '../paciente/stages'; import { STATES } from '../paciente/stages';
import type { Row } from './follow-up'; import type { CamaRow, Row } from './follow-up';
import { name } from './measures'; import { name } from './measures';
const NONE = 'No disponible'; 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 type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up'; import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures'; import { historyPeriods, periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
it('starts the window the day after the same day months before (core.follow_up)', () => { it('starts the window the day after the same day months before (core.follow_up)', () => {
@@ -36,6 +36,16 @@ describe('follow-up list', () => {
expect(currentRisk(risks, 'cin2', 3)).toBeUndefined(); expect(currentRisk(risks, 'cin2', 3)).toBeUndefined();
}); });
it('ends history at the selected complete period for months and semesters', () => {
const monthly = historyPeriods('month', '2025-03');
expect(monthly.slice(-3)).toEqual(['2025-01', '2025-02', '2025-03']);
expect(monthly).toHaveLength(72);
const firstSemester = historyPeriods('semester', '2025-S1');
expect(firstSemester.slice(-3)).toEqual(['2024-S1', '2024-S2', '2025-S1']);
const secondSemester = historyPeriods('semester', '2025-S2');
expect(secondSemester.slice(-2)).toEqual(['2025-S1', '2025-S2']);
});
it('lists periods most recent first', () => { it('lists periods most recent first', () => {
expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']); expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']);
expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([ expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([
+5 -5
View File
@@ -36,28 +36,28 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else { } @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms"> <mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'"> <mat-tab label="Indicadores">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" /> <app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab> </mat-tab>
<mat-tab label="Histórico"> <mat-tab label="Trazabilidad">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" /> <app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
<mat-tab label="Seguimiento"> <mat-tab label="Análisis de Riesgo">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" /> <app-tab-riesgos [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'tea') { } @else if (domain() === 'tea') {
<mat-tab label="Seguimiento"> <mat-tab label="Análisis de Riesgo">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos-tea [domain]="domain()" /> <app-tab-riesgos-tea [domain]="domain()" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'cama') { } @else if (domain() === 'cama') {
<mat-tab label="Seguimiento"> <mat-tab label="Análisis de Riesgo">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" /> <app-tab-seguimiento [domain]="domain()" />
</ng-template> </ng-template>
+2 -3
View File
@@ -19,8 +19,8 @@ export const LAYOUTS: Record<string, Layout> = {
], ],
route: [ route: [
{ {
label: 'Días de toma de citología a resultado', label: 'Resultado de citología',
step: 'Días de toma de citología a resultado', step: 'Toma a resultado de citología',
fromSample: 'CACU_EU_TIEMPO_REPORTE', fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE', fromStep: 'CACU_EU_TIEMPO_REPORTE',
}, },
@@ -51,7 +51,6 @@ export const LAYOUTS: Record<string, Layout> = {
'CAMA_EU38A', 'CAMA_EU38A',
'CAMA_DIAS_TOMA_DIAGNOSTICO', 'CAMA_DIAS_TOMA_DIAGNOSTICO',
'CAMA_CONFIRMACION_BIRADS45', 'CAMA_CONFIRMACION_BIRADS45',
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
], ],
route: [ route: [
{ {
+28 -3
View File
@@ -23,6 +23,13 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
return found; 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 { export function periodLabel(period: string): string {
const [year, part] = period.split('-'); const [year, part] = period.split('-');
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`; 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)', NILM: 'Normal (NILM)',
LSIL: 'LIEBG', LSIL: 'LIEBG',
HSIL: 'LIEAG', HSIL: 'LIEAG',
CIN2: 'CIN 2',
CIN3: 'CIN 3',
normal: 'Normal', normal: 'Normal',
carcinoma: 'Carcinoma', carcinoma: 'Carcinoma',
no_data: 'Sin dato', no_data: 'Sin dato',
'<25': '<25 años (sin límite inferior)',
no_biopsy: 'Sin biopsia', no_biopsy: 'Sin biopsia',
pre_colposcopy: 'Pre colposcopia', pre_colposcopy: 'Pre colposcopia',
post_colposcopy: 'Post colposcopia', post_colposcopy: 'Post colposcopia',
@@ -134,7 +144,7 @@ export const LABELS: Record<string, string> = {
bad: 'Malo', bad: 'Malo',
not_analyzed: 'Sin analizar', not_analyzed: 'Sin analizar',
initial: 'Detección inicial', initial: 'Detección inicial',
subsequent: 'Detección subsecuente', subsequent: 'Con detección anterior',
positive: 'Positivo', positive: 'Positivo',
negative: 'Negativo', negative: 'Negativo',
hpv_16: 'VPH 16', 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}`]), ['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. */ /** A follow-up priority's label. */
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' }; export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
export const STRATA: Record<string, string> = { export const STRATA: Record<string, string> = {
@@ -165,11 +190,11 @@ export const STRATA: Record<string, string> = {
cytology: 'Citología previa', cytology: 'Citología previa',
hpv: 'VPH de la citología previa', hpv: 'VPH de la citología previa',
level: 'Histología confirmada', level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente', round: 'Detección inicial o anterior',
hpv_16: 'VPH 16', hpv_16: 'VPH 16',
hpv_18: 'VPH 18', 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 { export function formatScore(measure: Measure, r: Reading | undefined): string {
if (!r || r.score === undefined) return 'Sin dato'; if (!r || r.score === undefined) return 'Sin dato';
+59 -43
View File
@@ -8,13 +8,13 @@ import {
PPV_DONUT, PPV_DONUT,
PPV_LEVEL_COLORS, PPV_LEVEL_COLORS,
QUARTILE, QUARTILE,
REQUEST_COLORS,
ROUND_COLORS, ROUND_COLORS,
} from './cacu-palette'; } from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages'; import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; 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. */ /** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = { const CYTOLOGY: Catalog = {
@@ -29,6 +29,12 @@ const CYTOLOGY: Catalog = {
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' }, { code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], 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: '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: [ categories: [
{ code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' }, { code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], 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: '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: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
{ {
code: 'carcinoma', code: 'carcinoma',
@@ -59,15 +67,8 @@ const HPV = [
{ code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] }, { code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
{ code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] }, { 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_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. */ /** The screening route's bars: a median, and the marks of its quartiles. */
const TINT = { bar: DURATION, mark: QUARTILE }; const TINT = { bar: DURATION, mark: QUARTILE };
@@ -75,16 +76,14 @@ const TINT = { bar: DURATION, mark: QUARTILE };
const ROUNDS = ['initial', 'subsequent', 'no_data']; const ROUNDS = ['initial', 'subsequent', 'no_data'];
const ROUND_CAPTION = 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), ' + '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.'; 'Un grupo sin pacientes se muestra en cero; sin porcentaje.';
/** The views the cytology and HPV-by-genotype cards share (one selector for both). */ /** The views the cytology and HPV-by-genotype cards share (one selector for both). */
const GENERAL = 'General'; const GENERAL = 'General';
const BY_AGE = 'Por grupo de edad'; const BY_AGE = 'Por grupo de edad';
const BY_STATUS = 'Por estatus de seguimiento'; const BY_ROUND = 'Por detección inicial y anterior';
const BY_ROUND = 'Por detección inicial y subsecuente';
const AGE_GROUPS = ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data']; 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). */ /** HPV categories the cards do not draw (their reports stay in the total and the percentages). */
const HPV_HIDDEN = { const HPV_HIDDEN = {
codes: ['positive_incomplete', 'inconsistent', 'no_result'], codes: ['positive_incomplete', 'inconsistent', 'no_result'],
@@ -96,29 +95,38 @@ const groupViews = (
measure: string, measure: string,
catalog: { code: string; label: string; color: string }[], catalog: { code: string; label: string; color: string }[],
unit: string, unit: string,
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {}, more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string }; aggregate?: typeof ABNORMAL } = {},
): Mode[] => ): Mode[] =>
[ [
{ label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS }, { 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 }, { label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
].map((v) => ({ ].map((v) => ({
kind: 'grouped' as const, kind: 'grouped' as const,
measure, measure,
catalog, catalog,
unit, 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, ...v,
...more, ...more,
})); }));
/** A PPV's card: the whole, and by each of its stratifiers. */ /** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({ const ppv = (
measure: string,
title: string,
note: string,
percentLabel: string,
...more: Mode[]
): ReadingsCard => ({
kind: 'readings', kind: 'readings',
title, title,
headline: measure, headline: measure,
footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`, note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [ modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT }, { kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT, percentLabel },
{ {
kind: 'shares', kind: 'shares',
label: 'Citología previa', label: 'Citología previa',
@@ -127,6 +135,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
stratum: 'cytology', stratum: 'cytology',
colors: PPV_CYTOLOGY_COLORS, colors: PPV_CYTOLOGY_COLORS,
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'], order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
percentLabel: 'Porcentaje de pacientes con esta citología previa',
}, },
{ {
kind: 'shares', kind: 'shares',
@@ -136,6 +145,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
stratum: 'hpv', stratum: 'hpv',
colors: HPV_COLORS, colors: HPV_COLORS,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'], order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
percentLabel: 'Porcentaje de pacientes de cada grupo de VPH previo',
}, },
{ {
kind: 'shares', kind: 'shares',
@@ -144,16 +154,18 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
stratum: 'level', stratum: 'level',
colors: PPV_LEVEL_COLORS, colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'], order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
percentLabel: 'Porcentaje de pacientes de cada nivel de histología',
}, },
{ {
kind: 'shares', kind: 'shares',
label: 'Por detección inicial y subsecuente', label: 'Por detección inicial y anterior',
caption: ROUND_CAPTION, caption: ROUND_CAPTION,
measure, measure,
stratum: 'round', stratum: 'round',
colors: ROUND_COLORS, colors: ROUND_COLORS,
order: ROUNDS, order: ROUNDS,
complete: true, complete: true,
percentLabel: 'Porcentaje de pacientes de cada ronda',
}, },
...more, ...more,
], ],
@@ -174,34 +186,29 @@ export const CACU: Page = {
}, },
{ {
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Días de toma de citología a resultado', title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Días de tamizaje a primer diagnóstico',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Días de tamizaje a diagnóstico tras biopsia', title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Días de tamizaje a tratamiento', title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Días de diagnóstico a tratamiento', title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
], ],
opportunity: [ opportunity: [
{ {
kind: 'readings', kind: 'readings',
title: 'Días de la ruta del tamizaje', title: 'Tiempos de tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.', note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [ modes: [
{ {
@@ -209,7 +216,7 @@ export const CACU: Page = {
tint: TINT, tint: TINT,
label: 'Acumulado desde la toma', label: 'Acumulado desde la toma',
steps: [ steps: [
{ label: 'Días de toma de citología a resultado', measure: 'CACU_EU_TIEMPO_REPORTE' }, { label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' }, { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' }, { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ {
@@ -221,11 +228,13 @@ export const CACU: Page = {
{ {
kind: 'days', kind: 'days',
tint: TINT, tint: TINT,
label: 'Por pasos', label: 'Por ventana de tiempo',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.', staggered: true,
caption:
'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [ steps: [
{ {
label: 'Días de toma de citología a resultado', label: 'Toma a resultado de citología',
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
}, },
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' }, { label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
@@ -236,7 +245,7 @@ export const CACU: Page = {
{ {
kind: 'days', kind: 'days',
tint: TINT, tint: TINT,
label: 'Primer diagnóstico', label: 'Diagnóstico precolposcópico',
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }], steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
}, },
{ {
@@ -258,7 +267,7 @@ export const CACU: Page = {
kind: 'columns', kind: 'columns',
title: 'Resultados de citología, VPH y biopsia', title: 'Resultados de citología, VPH y biopsia',
viewsLabel: 'Lectura de la distribución citológica y del VPH por genotipo', 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: [ sections: [
{ {
kind: 'readings', kind: 'readings',
@@ -266,8 +275,16 @@ export const CACU: Page = {
title: 'Distribución de resultados citológicos', title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.', note: 'Pacientes, por su última muestra válida del periodo.',
modes: [ 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 }),
], ],
}, },
{ {
@@ -281,6 +298,8 @@ export const CACU: Page = {
label: GENERAL, label: GENERAL,
measure: 'CACU_VPH_GENOTIPO', measure: 'CACU_VPH_GENOTIPO',
catalog: HPV, catalog: HPV,
unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de VPH',
hidden: HPV_HIDDEN, hidden: HPV_HIDDEN,
}, },
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', { ...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
@@ -299,6 +318,8 @@ export const CACU: Page = {
label: 'General', label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS', measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories, catalog: BIOPSY.categories,
unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de biopsia',
}, },
], ],
}, },
@@ -314,6 +335,7 @@ export const CACU: Page = {
'CACU_VPP_COLPOSCOPIA', 'CACU_VPP_COLPOSCOPIA',
'Tasa de confirmación histopatológica de referencia a colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.', 'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
'Porcentaje de pacientes',
), ),
}, },
{ {
@@ -322,13 +344,7 @@ export const CACU: Page = {
'CACU_VPP_BIOPSIA', 'CACU_VPP_BIOPSIA',
'Tasa de confirmación histopatológica de referencia a biopsia', 'Tasa de confirmación histopatológica de referencia a biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.', 'Pacientes con biopsia reportada, por fecha de solicitud.',
{ 'Porcentaje de biopsias reportadas',
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
},
), ),
}, },
], ],
+59 -38
View File
@@ -26,6 +26,8 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** say the headline under the figure instead of above it */
footnote?: boolean;
/** what the headline proportion counts, in the plural (default: pacientes) */ /** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string; unit?: string;
note?: string; note?: string;
@@ -122,7 +124,6 @@ const CAMA_DAYS = {
value: '{median} días (mediana)', value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.', 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. */ /** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = { const BIRADS: Catalog = {
@@ -248,6 +249,7 @@ export const PAGES: Record<string, Page> = {
}, },
cama: { cama: {
anchor: 'CAMA_BIRADS456_PACIENTE', anchor: 'CAMA_BIRADS456_PACIENTE',
// every single-number card, together at the start, in the order asked for
kpis: [ kpis: [
{ {
measure: 'CAMA_BIRADS456_PACIENTE', measure: 'CAMA_BIRADS456_PACIENTE',
@@ -255,37 +257,41 @@ export const PAGES: Record<string, Page> = {
value: '{n} pacientes', value: '{n} pacientes',
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.', 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', measure: 'CAMA_EU38A',
title: 'Días de toma de mastografía a interpretación radiológica', title: 'Tiempo de toma de mastografía a interpretación radiológica',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Días de interpretación radiológica a diagnóstico', title: 'Tiempo de interpretación radiológica a diagnóstico',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
title: 'Días de diagnóstico a tratamiento', measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
value: 'Indicador no disponible', title: 'Tiempo de interpretación radiológica a resultado de biopsia',
note: PENDING, ...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: [ opportunity: [
{ {
kind: 'route', kind: 'route',
title: 'Días 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 // from the mammography: only the two measures that start at it
sample: [ sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' }, { label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Diagnóstico (días de tamizaje a diagnóstico)', label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
}, },
], ],
@@ -295,11 +301,16 @@ export const PAGES: Record<string, Page> = {
label: 'Interpretación radiológica a diagnóstico', label: 'Interpretación radiológica a diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', 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', label: 'Interpretación radiológica a resultado de biopsia',
measure: 'CAMA_DIAS_RESULTADO_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', kind: 'readings',
title: 'Resultado histopatológico por categoría BI-RADS', 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. El porcentaje maligno se calcula solo sobre las pacientes con biopsia con grado.', 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: [ modes: [
{ {
kind: 'outcomes', kind: 'outcomes',
label: 'Por categoría BI-RADS', label: 'Por categoría BI-RADS',
heading: 'Resultados por paciente', heading: 'Resultados por paciente',
caption: NO_BIOPSY_MEANS, caption: NO_BIOPSY_MEANS,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
stratum: 'birads', stratum: 'birads',
rows: BIRADS.categories, rows: BIRADS.categories,
results: [...BIOPSY_GRADES, ...NO_RESULT], results: NO_RESULT,
malignant: ['in_situ', 'invasive'], malignant: ['in_situ', 'invasive'],
dynamicResults: true,
malignancyMeasure: 'CAMA_HISTOPATOLOGIA_BIRADS',
}, },
{ {
kind: 'counts', kind: 'counts',
label: 'Todas las categorías', label: 'Todas las categorías',
heading: 'Resultados por paciente', heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`, measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', catalog: [],
catalog: [...BIOPSY_GRADES, ...NO_RESULT], unit: 'Pacientes',
percent: true, percent: true,
percentLabel: 'Porcentaje de pacientes',
}, },
], ],
}, },
@@ -356,21 +370,22 @@ export const PAGES: Record<string, Page> = {
card: true, card: true,
choices: [ choices: [
{ {
label: 'Resultado de biopsias', label: 'Tipos histológicos',
section: { section: {
kind: 'readings', kind: 'readings',
title: 'Resultado de biopsias', title: 'Tipos histológicos',
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
unit: 'biopsias', 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: [ modes: [
{ {
kind: 'counts', kind: 'counts',
label: 'Biopsias reportadas', label: 'Tipos histológicos',
heading: 'Biopsias reportadas', heading: 'Tipo histológico',
measure: 'CAMA_BIOPSIAS', measure: 'CAMA_TIPO_HISTOLOGICO',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]], catalog: [],
unit: 'Biopsias',
percent: true, percent: true,
percentLabel: 'Porcentaje de reportes de biopsia',
}, },
], ],
}, },
@@ -382,7 +397,7 @@ export const PAGES: Record<string, Page> = {
title: 'Mastografías con biopsia', title: 'Mastografías con biopsia',
headline: 'CAMA_CONFIRMACION_BIRADS45', headline: 'CAMA_CONFIRMACION_BIRADS45',
unit: 'mastografías', 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: [ modes: [
{ {
kind: 'split', kind: 'split',
@@ -391,6 +406,8 @@ export const PAGES: Record<string, Page> = {
yes: 'Con reporte de biopsia', yes: 'Con reporte de biopsia',
no: 'Sin reporte de biopsia', no: 'Sin reporte de biopsia',
colors: [INSTITUTIONAL, NEUTRAL], colors: [INSTITUTIONAL, NEUTRAL],
unit: 'Mastografías',
percentLabel: 'Porcentaje de mastografías',
}, },
], ],
}, },
@@ -468,7 +485,9 @@ export const HISTORY: Record<string, History> = {
[ [
['normal', 'Normal', '#9DBFE3'], ['normal', 'Normal', '#9DBFE3'],
['LSIL', 'LIEBG (CIN 1)', '#69C242'], ['LSIL', 'LIEBG (CIN 1)', '#69C242'],
['CIN2', 'CIN 2', '#E07A9C'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'], ['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
['CIN3', 'CIN 3', '#A8325A'],
['CIS', 'Carcinoma in situ', '#9C42C2'], ['CIS', 'Carcinoma in situ', '#9C42C2'],
['carcinoma', 'Carcinoma invasor', '#5C42C2'], ['carcinoma', 'Carcinoma invasor', '#5C42C2'],
['no_biopsy', 'Sin biopsia aún', GREY], ['no_biopsy', 'Sin biopsia aún', GREY],
@@ -476,27 +495,27 @@ export const HISTORY: Record<string, History> = {
], ],
), ),
{ {
title: 'Días de toma de citología a resultado', title: 'Días de la toma de la citología a su resultado',
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Días de tamizaje a primer diagnóstico', title: 'Tiempo de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Días de tamizaje a diagnóstico tras biopsia', title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Días de tamizaje a tratamiento', title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Días de diagnóstico a tratamiento', title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
@@ -511,6 +530,7 @@ export const HISTORY: Record<string, History> = {
cama: { cama: {
line: '#9C42C2', line: '#9C42C2',
panels: [ 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', title: 'Días de la toma de la mastografía a su resultado',
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
@@ -522,10 +542,11 @@ export const HISTORY: Record<string, History> = {
kind: 'median', kind: 'median',
}, },
{ {
title: 'Días de tamizaje a diagnóstico', title: 'Tiempo de tamizaje a diagnóstico',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
{ title: 'Tasa de detección histopatológica', measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', kind: 'percent' },
stack( stack(
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6', 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
'CAMA_BIRADS456_MASTOGRAFIA', 'CAMA_BIRADS456_MASTOGRAFIA',
@@ -546,7 +567,7 @@ export const HISTORY: Record<string, History> = {
['no_data', 'Sin dato', GREY], ['no_data', 'Sin dato', GREY],
]), ]),
{ {
title: 'Tasa de confirmación histopatológica', title: 'Confirmación histopatológica',
measure: 'CAMA_CONFIRMACION_BIRADS45', measure: 'CAMA_CONFIRMACION_BIRADS45',
kind: 'percent', kind: 'percent',
}, },
+18 -3
View File
@@ -54,13 +54,13 @@ import { Reading } from './measures';
@for (group of g.groups; track group.code) { @for (group of g.groups; track group.code) {
<section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label"> <section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label">
<h4> <h4>
{{ group.label }} <span class="n">n = {{ group.total }}</span> {{ group.label }} <span class="n">{{ countUnit() }}: {{ group.total }}</span>
@if (group.hint) { @if (group.hint) {
<span class="hint">{{ group.hint }}</span> <span class="hint">{{ group.hint }}</span>
} }
</h4> </h4>
@for (row of group.rows; track row.label) { @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="name">{{ row.label }}</span>
<span class="track" aria-hidden="true"> <span class="track" aria-hidden="true">
<span <span
@@ -94,7 +94,7 @@ import { Reading } from './measures';
</thead> </thead>
<tbody> <tbody>
@for (row of t.rows; track row.label) { @for (row of t.rows; track row.label) {
<tr> <tr [class.sub]="row.sub">
<th scope="row"> <th scope="row">
{{ row.label }} {{ row.label }}
@if (row.hint) { @if (row.hint) {
@@ -116,6 +116,7 @@ import { Reading } from './measures';
} @else { } @else {
<span <span
class="bar" class="bar"
[style.margin-left.%]="row.offset"
[style.width.%]="row.width" [style.width.%]="row.width"
[style.background]="row.color" [style.background]="row.color"
></span> ></span>
@@ -146,8 +147,15 @@ import { Reading } from './measures';
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`, `,
styles: ` styles: `
tr.sub th,
.row.sub .name {
padding-left: 1.25rem;
}
:host { :host {
display: block; display: block;
min-width: 0; min-width: 0;
@@ -347,6 +355,8 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** a line under the figure */
readonly foot = input('');
/** the card around it names it already (tabs inside one card) */ /** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false); readonly hideTitle = input(false);
readonly camaStyle = input(false); readonly camaStyle = input(false);
@@ -359,6 +369,11 @@ export class Readings {
readonly draw = input.required<(mode: Mode) => Figure | undefined>(); readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal(''); 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( protected readonly mode = computed(
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0], () => 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 { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading'; 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 /** 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 * 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()) { @if (loading()) {
<app-loading what="los tiempos" [figure]="true" /> <app-loading what="los tiempos" [figure]="true" />
} @else { } @else {
@let rows = mode() === 'sample' ? sample() : step(); @let rows = mode() === 'sample' ? sample() : chain(step());
@let max = scale(rows); @let max = scale(rows);
<p class="state"> <p class="state">
@if (mode() === 'sample') { @if (mode() === 'sample') {
Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se
calcula por separado. calcula por separado.
} @else { } @else {
Cada barra es la mediana de su paso, desde cero y por separado; los pasos pueden Esquema: cada barra es la mediana de su paso y empieza donde termina el paso del que
corresponder a poblaciones diferentes, por lo que las medianas no se suman. parte. Los pasos pueden corresponder a poblaciones diferentes, por lo que las
medianas no se suman.
} }
Las marcas indican el primer y tercer cuartil. Las marcas indican el primer y tercer cuartil.
@if (max) { @if (max) {
@@ -62,16 +63,17 @@ import { DurationRow, durationMax } from './durations';
<span class="track" aria-hidden="true"> <span class="track" aria-hidden="true">
<span <span
class="bar" class="bar"
[style.margin-left.%]="max ? (100 * (row.start ?? 0)) / max : 0"
[style.width.%]="max ? (100 * row.median!) / max : 0" [style.width.%]="max ? (100 * row.median!) / max : 0"
></span> ></span>
@if (row.low !== undefined && row.high !== undefined) { @if (row.low !== undefined && row.high !== undefined) {
<span <span
class="mark" class="mark"
[style.left.%]="max ? (100 * row.low) / max : 0" [style.left.%]="max ? (100 * ((row.start ?? 0) + row.low)) / max : 0"
></span> ></span>
<span <span
class="mark" class="mark"
[style.left.%]="max ? (100 * row.high) / max : 0" [style.left.%]="max ? (100 * ((row.start ?? 0) + row.high)) / max : 0"
></span> ></span>
} }
</span> </span>
@@ -180,4 +182,5 @@ export class RouteCard {
protected readonly mode = signal<'sample' | 'step'>('step'); protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax; 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 <app-readings
[title]="s.title" [title]="s.title"
[camaStyle]="hasCamaHeading(s)" [camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)" [headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''" [note]="s.note ?? ''"
[modes]="s.modes" [modes]="s.modes"
[view]="view()" [view]="view()"
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
[title]="c.section.title" [title]="c.section.title"
[hideTitle]="true" [hideTitle]="true"
[camaStyle]="true" [camaStyle]="true"
[headline]="headlineOf(c.section)" [headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''" [note]="c.section.note ?? ''"
[modes]="c.section.modes" [modes]="c.section.modes"
[loading]="of().loading" [loading]="of().loading"
@@ -162,6 +164,12 @@ export class ReadingsSection {
const words = detail(measure, r, s.unit); const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
} }
/** The headline of a card that says it under its figure, as one line separated by commas. */
protected footOf(s: ReadingsCard): string {
return s.footnote
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
: '';
}
protected readonly draw = computed(() => (mode: Mode) => { protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined; if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure); const r = this.of().reading(mode.measure);
+66 -19
View File
@@ -40,13 +40,77 @@
} }
@if (page(); as pg) { @if (page(); as pg) {
@if (applied(); as period) { @if (applied(); as period) {
@if (domain() === 'cama') {
<section class="card opportunity" aria-labelledby="opportunity-title"> <section class="card opportunity" aria-labelledby="opportunity-title">
<div class="section-head"> <div class="section-head">
<h2 id="opportunity-title">Indicadores de oportunidad</h2> <h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span> <span class="period">Periodo {{ period }}</span>
</div> </div>
<div class="kpis"> <div class="kpis" style="--kpi-cols-md: 3; --kpi-cols-lg: 3">
@for (k of pg.kpis; track k.title) { @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 }"
/>
}
</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 class="card opportunity" aria-labelledby="opportunity-title">
<div class="section-head">
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span>
</div>
<div
class="kpis"
[style.--kpi-cols-md]="pg.kpis.length < 3 ? pg.kpis.length : 3"
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
>
@for (k of pg.kpis; track k.title) {
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
}
</div>
@for (section of pg.opportunity ?? []; track $index) {
<ng-container
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
/>
}
</section>
@if (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>
}
}
}
<ng-template #kpiView let-k>
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null"> <mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content> <mat-card-content>
<h3 class="kpi-title">{{ k.title }}</h3> <h3 class="kpi-title">{{ k.title }}</h3>
@@ -64,24 +128,7 @@
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} </ng-template>
</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>
}
<ng-template #sectionView let-section let-period="period"> <ng-template #sectionView let-section let-period="period">
@switch (section.kind) { @switch (section.kind) {
+2 -2
View File
@@ -42,13 +42,13 @@ h2 {
@media (min-width: 1000px) { @media (min-width: 1000px) {
.kpis { .kpis {
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(var(--kpi-cols-md, 3), 1fr);
} }
} }
@media (min-width: 1350px) { @media (min-width: 1350px) {
.kpis { .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>
<td> <td>
{{ row.age ?? 'No disponible' }} {{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup }}</small> <small>Grupo: {{ name(row.ageGroup) }}</small>
</td> </td>
<td>{{ name(row.status) }}</td> <td>{{ name(row.status) }}</td>
<td> <td>
+19 -15
View File
@@ -16,8 +16,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { saveExcel, savePdf } from '../export';
import { Stages } from '../paciente/stages'; import { Stages } from '../paciente/stages';
import { saveFollowUp } from './follow-up-export';
import { cytologyResult, followUpSheet } from './follow-up-sheet'; import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up'; import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search'; import { PatientSearch, patientSearch } from './patient-search';
@@ -140,24 +140,28 @@ export class TabRiesgos {
/** The whole list, not the page shown, as a file. */ /** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> { protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true); this.saving.set(true);
this.saveError.set(''); this.saveError.set('');
try { try {
const cutoff = this.applied(); await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) => {
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 }; const cutoffYear = Number(query.cutoff.slice(0, 4));
const pages = await this.fhir.all(this.domain(), 'Patient', asked); // bornFor encodes the minimum with le and the maximum with gt at one year earlier.
const start = windowStart(cutoff, this.window()); const lower = query.birthdates.find((value) => value.startsWith('le'));
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon())); const upper = query.birthdates.find((value) => value.startsWith('gt'));
const sheet = followUpSheet(all, [ const minimum = lower ? `${cutoffYear - Number(lower.slice(2, 6))}` : 'Sin límite';
['Ventana consultada', `${start} al ${cutoff}`], const maximum = upper ? `${cutoffYear - Number(upper.slice(2, 6)) - 1}` : 'Sin límite';
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'], const all = pages.flatMap((p) => rows(p, query.start, query.cutoff, query.horizon));
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`], return followUpSheet(all, [
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`], ['Ventana consultada', query.window],
['Búsqueda', this.search() || 'Ninguna'], ['Estatus de seguimiento', query.status],
['Horizonte de la probabilidad (años)', `${this.horizon()}`], ['Edad mínima', minimum],
['Edad máxima', maximum],
['Búsqueda', query.search],
['Horizonte de la probabilidad (años)', `${query.horizon}`],
]); ]);
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu'); });
else await savePdf([sheet], 'seguimiento-cacu', true);
} catch { } catch {
this.saveError.set('No se generó el archivo.'); this.saveError.set('No se generó el archivo.');
} finally { } finally {
+19
View File
@@ -35,7 +35,26 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form> </form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) { @if (error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
+37 -10
View File
@@ -7,6 +7,8 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { saveFollowUp } from './follow-up-export';
import { camaFollowUpSheet } from './follow-up-sheet';
import { camaRows, windowStart } from './follow-up'; import { camaRows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search'; import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading'; import { Loading } from '../loading';
@@ -46,23 +48,23 @@ export class TabSeguimiento {
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
protected readonly name = name; protected readonly name = name;
protected readonly priority = (code: string) => PRIORITY[code] ?? code; protected readonly priority = (code: string) => PRIORITY[code] ?? code;
protected readonly saving = signal(false);
protected readonly saveError = signal('');
private readonly first = resource({ /** The list as it is asked for, whatever the page. */
params: () => ({ private readonly query = computed(() => ({
domain: this.domain(),
'follow-up-window': this.window(), 'follow-up-window': this.window(),
...patientSearch(this.search()), ...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined, 'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined, 'follow-up-status': this.status() || undefined,
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', {
...params,
_revinclude: ['DiagnosticReport:subject'], _revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result', '_include:iterate': 'DiagnosticReport:result',
}); }));
private readonly first = resource({
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', { ...query, _count: size });
}, },
}); });
protected readonly loading = signal(false); protected readonly loading = signal(false);
@@ -95,6 +97,31 @@ export class TabSeguimiento {
this.first.reload(); 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 { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
@@ -0,0 +1,51 @@
import { TestBed } from '@angular/core/testing';
import type { Measure } from 'fhir/r4';
import { Fhir } from '../fhir';
import { HISTORY } from './pages';
import { TabTrazabilidad } from './tab-trazabilidad';
describe('Trazabilidad: periodo seleccionado', () => {
for (const domain of ['cama', 'cacu']) {
it(`applies a monthly and semester period to the ${domain} queries`, async () => {
const requests: Record<string, string>[] = [];
await TestBed.configureTestingModule({
imports: [TabTrazabilidad],
providers: [
{
provide: Fhir,
useValue: {
all: async (_domain: string, _resource: string, params: Record<string, string>) => {
requests.push(params);
return [{ resourceType: 'Bundle', type: 'searchset', entry: [] }];
},
},
},
],
}).compileComponents();
const fixture = TestBed.createComponent(TabTrazabilidad);
fixture.componentRef.setInput('domain', domain);
fixture.componentRef.setInput('measures', [
{ resourceType: 'Measure', id: 'test', name: HISTORY[domain].panels[0].measure },
] as Measure[]);
fixture.detectChanges();
await fixture.whenStable();
const component = fixture.componentInstance as any;
component.chosen.set('2025-03');
fixture.detectChanges();
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2025-03');
expect(requests.at(-1)?.['as-of']).toBeUndefined();
component.setType('semester');
fixture.detectChanges();
await fixture.whenStable();
component.chosen.set('2024-S1');
fixture.detectChanges();
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2024-S1');
});
}
});
+41 -5
View File
@@ -1,11 +1,13 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4'; import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { historyFigure } from './figures'; import { historyFigure } from './figures';
import { periodLabel, periods, PeriodType, reading } from './measures'; import { historyPeriods, periodLabel, periods, PeriodType, reading } from './measures';
import { HISTORY, HistoryPanel } from './pages'; import { HISTORY, HistoryPanel } from './pages';
interface Drawn { interface Drawn {
@@ -19,18 +21,31 @@ interface Drawn {
* each measure period by period. */ * each measure period by period. */
@Component({ @Component({
selector: 'app-tab-trazabilidad', selector: 'app-tab-trazabilidad',
imports: [Loading, MatButtonToggleModule, Plot], imports: [Loading, MatButtonModule, MatButtonToggleModule, MatSelectModule, Plot],
template: ` template: `
<section class="card filters" aria-labelledby="history-filters"> <section class="card filters" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2> <h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group <mat-button-toggle-group
[value]="type()" [value]="type()"
(change)="type.set($event.value)" (change)="setType($event.value)"
aria-label="Intervalo de análisis" aria-label="Intervalo de análisis"
> >
<mat-button-toggle value="month">Mensual</mat-button-toggle> <mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle> <mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group> </mat-button-toggle-group>
@if (domain() === '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> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="el histórico" text="Cargando histórico…" /> <app-loading what="el histórico" text="Cargando histórico…" />
@@ -71,6 +86,12 @@ interface Drawn {
padding: 16px 20px; padding: 16px 20px;
margin-bottom: 16px; margin-bottom: 16px;
} }
.filters {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px;
}
.filters-title { .filters-title {
font-size: 16px; font-size: 16px;
font-weight: 500; font-weight: 500;
@@ -95,13 +116,28 @@ export class TabTrazabilidad {
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('month'); protected readonly type = signal<PeriodType>('month');
protected readonly options = computed(() => periods(this.type()));
protected readonly 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({ 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 }) => { loader: async ({ params }) => {
const history = HISTORY[params.domain]; const history = HISTORY[params.domain];
if (!history) return []; if (!history) return [];
const asked = periods(params.type).reverse(); const asked = historyPeriods(params.type, params.period);
return Promise.all( return Promise.all(
history.panels.map(async (panel) => { history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure); const measure = params.measures.find((m) => m.name === panel.measure);
@@ -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);
}
}
+2 -1
View File
@@ -22,7 +22,8 @@ export const CRITERION_TEXT: Record<string, string> = {
outcome_by_index: 'Resultado CIN2+ hasta la visita índice', outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
cancer_history: 'Antecedente de cáncer cervicouterino', cancer_history: 'Antecedente de cáncer cervicouterino',
prior_treatment: 'Tratamiento previo a la visita índice', prior_treatment: 'Tratamiento previo a la visita índice',
no_referral: 'Sin resultado que sustente la referencia a colposcopia', 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_cotest: 'Sin cotest de citología y VPH en la visita índice',
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido', no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice', outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
+85 -17
View File
@@ -5,9 +5,21 @@
@if (error()) { @if (error()) {
<p class="muted" role="alert">No se encontró la paciente.</p> <p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) { } @else if (patient(); as p) {
<div class="record-head">
<h1> <h1>
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code> {{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1> </h1>
@if (cama()) {
<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"> <dl class="summary">
<div> <div>
<dt>CURP</dt> <dt>CURP</dt>
@@ -139,7 +151,7 @@
<td> <td>
{{ h.text }} {{ h.text }}
@if (h.code && h.code !== h.text) { @if (h.code && h.code !== h.text) {
<span class="muted">({{ h.code }})</span> <span class="muted">(CIE-10: {{ h.code }})</span>
} }
</td> </td>
</tr> </tr>
@@ -246,8 +258,14 @@
</mat-card> </mat-card>
} }
@if (
riskExclusion() || withheld() || groups().length || domain() !== 'cacu' || riskModels().length
) {
<mat-card appearance="outlined" class="wide" data-section="riesgos"> <mat-card appearance="outlined" class="wide" data-section="riesgos">
<mat-card-content> <mat-card-content>
@if (withheld(); as why) {
<p role="status" data-state="withheld">{{ why }}</p>
}
@if (riskExclusion(); as reason) { @if (riskExclusion(); as reason) {
<p role="status">{{ reason }}</p> <p role="status">{{ reason }}</p>
} @else { } @else {
@@ -297,7 +315,7 @@
@if (riskSeries.value()?.length) { @if (riskSeries.value()?.length) {
<app-risk-series [series]="riskSeries.value()!" /> <app-risk-series [series]="riskSeries.value()!" />
} @else { } @else {
<app-plot [figure]="curve()" [height]="300" /> <app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
} }
</details> </details>
} }
@@ -306,6 +324,7 @@
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
}
@if (domain() === 'tea') { @if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea"> <mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -557,19 +576,73 @@
<mat-card appearance="outlined" class="wide" data-section="supervivencia"> <mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header> <mat-card-header>
<mat-card-title>{{ <mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia por escenario clínico' : 'Riesgo de muerte' domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
}}</mat-card-title> }}</mat-card-title>
</mat-card-header> </mat-card-header>
<mat-card-content> <mat-card-content>
@if (domain() !== 'cacu') {
<h3>Análisis de supervivencia</h3> <h3>Análisis de supervivencia</h3>
}
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
<p class="muted" data-note="grupo"> <app-risk-scales [groups]="survivalScales()" />
Las curvas son estimaciones del grupo de pacientes del escenario clínico @for (g of survivalScales(); track $index) {
correspondiente (S(t), probabilidad de supervivencia); no son predicciones <details data-section="valores-supervivencia">
individuales. <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> </p>
} }
@if (survival.isLoading()) { } @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" /> <app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) { } @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3> <h3>Escenario clínico de la paciente</h3>
@@ -579,12 +652,14 @@
} }
</ul> </ul>
@if (s.methods.length) { @if (s.methods.length) {
<h3>Métodos</h3> <details>
<summary>Métodos</summary>
<ul class="scenarios methods"> <ul class="scenarios methods">
@for (name of s.methods; track name) { @for (name of s.methods; track name) {
<li>{{ name }}</li> <li>{{ name }}</li>
} }
</ul> </ul>
</details>
} }
@for (f of s.figures; track f.title) { @for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4> <h4>{{ f.title }}</h4>
@@ -608,14 +683,7 @@
} @else if (survival.error()) { } @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else { } @else {
<p class="muted" data-state="sin-informe"> <p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
@if (domain() === 'cacu') {
No disponible: no hay un informe de supervivencia para los escenarios de la
paciente.
} @else {
No disponible: datos insuficientes.
}
</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+16
View File
@@ -138,3 +138,19 @@ h1 .id {
margin: 8px 0; margin: 8px 0;
padding-left: 18px; 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;
}
+114 -6
View File
@@ -22,6 +22,7 @@ import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures'; import { scenarioFigure } from '../gobernanza/figures';
import { savePdf } from '../export'; import { savePdf } from '../export';
import { camaRecordSheets } from './cama-record-sheets';
import { recordSheets } from './record-sheets'; import { recordSheets } from './record-sheets';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import type { Parameters as FhirParameters } from 'fhir/r4'; import type { Parameters as FhirParameters } from 'fhir/r4';
@@ -32,7 +33,8 @@ import { eligibilityFailure, eligibilityView, type EligibilityState } from './el
import { ineligibility } from './ineligibility'; import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series'; import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import { isRiskModel, riskGroups, riskScales, RiskScales } from './risk-scales'; import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationOf, noCurveText, survivalFigure } from './survival-combination';
import { route, Stages } from './stages'; import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -49,6 +51,7 @@ import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot'; import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores'; import { Factores, ScenarioFactors } from './factores';
import { CurveChooser, figureChoices } from './curve-chooser';
/** An Observation's value as the screens say it, whatever its type. */ /** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string { function shown(o: Observation): string {
@@ -79,10 +82,30 @@ function methods(figures: { figure: { data: unknown[] } }[]): string[] {
return [...new Set(names.filter((n): n is string => !!n))]; return [...new Set(names.filter((n): n is string => !!n))];
} }
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [ imports: [
Factores, Factores,
CurveChooser,
Loading, Loading,
DecimalPipe, DecimalPipe,
MatButtonModule, MatButtonModule,
@@ -174,6 +197,11 @@ export class Paciente {
? `No disponible por: histerectomía registrada el ${recorded}.` ? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined; : 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;
});
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */ /** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
protected readonly stages = computed(() => { protected readonly stages = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter( const cytologies = (this.data.value()?.reports ?? []).filter(
@@ -183,14 +211,42 @@ export class Paciente {
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined; return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
}); });
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */ /** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => isRiskModel(m.model))); protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly scales = computed(() => protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [], this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
); );
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */ /** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
* survival only there is nothing to draw here: its scales are in the survival section. */
protected readonly groups = computed(() => protected readonly groups = computed(() =>
this.domain() === 'cacu' ? riskGroups(this.riskModels()) : [], this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
? riskGroups(this.riskModels())
: [],
); );
protected readonly survivalScales = computed(() =>
this.domain() === 'cacu'
? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
: [],
);
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
* the model version that scored her. */
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
},
loader: async ({ params: { version, inputs } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: 'cacu' as Domain,
name: 'survival',
version,
report: 'interpretability',
});
const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km
? { n: found.n, fallecidos: found.fallecidos, curves: figureChoices(survivalFigure(found)) }
: { missing: noCurveText(report as Record<string, unknown>, found) };
},
});
/** CaCu, experimental: the series her record can compare; none while the API has it off. */ /** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({ protected readonly riskSeries = resource({
params: () => params: () =>
@@ -242,11 +298,15 @@ export class Paciente {
); );
protected readonly saving = signal(false); protected readonly saving = signal(false);
protected readonly saveError = signal(''); 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> { protected async save(): Promise<void> {
this.saving.set(true); this.saving.set(true);
this.saveError.set(''); this.saveError.set('');
try { try {
if (this.domain() === 'cama') {
await this.saveCama();
return;
}
const { name: who, curp, numbers } = this.identity(); const { name: who, curp, numbers } = this.identity();
const facts: [string, string | undefined][] = [ const facts: [string, string | undefined][] = [
['Nombre', who], ['Nombre', who],
@@ -257,7 +317,7 @@ export class Paciente {
['Estatus de seguimiento', this.status()], ['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()], ['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( const sheets = recordSheets(
facts, facts,
this.stages() ?? [], this.stages() ?? [],
@@ -273,6 +333,51 @@ export class Paciente {
this.saving.set(false); 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(() => { protected readonly tests = computed(() => {
const d = this.data.value(); const d = this.data.value();
if (!d) return []; if (!d) return [];
@@ -341,6 +446,9 @@ export class Paciente {
text: r.method?.text ?? '', text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '', index: r.occurrenceDateTime ?? '',
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in // the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? []) scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico') .filter((e) => e.url === EXT + 'escenario-clinico')
+1 -1
View File
@@ -51,7 +51,7 @@ describe('the PDF of a record', () => {
'Historial médico', 'Historial médico',
'Antecedentes y evaluación ginecológica', 'Antecedentes y evaluación ginecológica',
'Pruebas y resultados', 'Pruebas y resultados',
'Riesgos', 'Probabilidades',
]); ]);
}); });
it('writes each stage with its state, its day or its request, and where it comes from', () => { 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', title: 'Probabilidades',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'], head: ['Estimación', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [ rows: scales.map(({ label, risk }) => [
label, label,
risk ? percent(risk.p) : NONE, risk ? percent(risk.p) : NONE,
+6 -6
View File
@@ -5,7 +5,7 @@ import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The states a resolution ends in, as the screens say them. */ /** The states a resolution ends in, as the screens say them. */
export const STATUS_TEXT: Record<string, string> = { export const STATUS_TEXT: Record<string, string> = {
resolved: 'Referencia disponible', 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', missing_data: 'Falta un dato clínico',
history_not_demonstrable: 'Antecedente no demostrable', history_not_demonstrable: 'Antecedente no demostrable',
not_applicable: 'Escenario no aplicable', 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.', 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.', 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.', 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.', no_row_for_the_combination: 'Las tablas no publican esa combinación.',
several_rows: 'Más de una fila podría corresponder.', several_rows: 'Más de una fila podría corresponder.',
no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.', 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.', index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.',
population_not_verified: population_not_verified:
'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.', '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> = { const KEY_TEXT: Record<string, string> = {
@@ -304,9 +304,9 @@ const OFFICIAL: Record<string, string> = {
<section <section
class="reference" class="reference"
data-section="referencia-nci" 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"> <dl class="meta">
<div> <div>
<dt>Estado</dt> <dt>Estado</dt>
@@ -458,7 +458,7 @@ const OFFICIAL: Record<string, string> = {
</section> </section>
} }
<p class="muted note"> <p class="muted note">
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos La diferencia es la probabilidad institucional menos la probabilidad NCI y solo se calcula si ambos
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados). estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
</p> </p>
} }
+2 -2
View File
@@ -18,7 +18,7 @@ describe('the institutional curves', () => {
model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]), model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]),
]); ]);
const lines = found.filter((t) => !t.name?.startsWith('IC')); 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].x).toEqual([1, 3, 5]);
expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]); expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]);
expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere expect(lines[1].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', []), model('Vacío v1', []),
]), ]),
).toEqual([ ).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) => const percent = (n: number) =>
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 }); (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; 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 /** The institutional models' risk by horizon: one series per model, drawn only at the horizons it
+24 -6
View File
@@ -1,4 +1,4 @@
import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales'; import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high }); const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
@@ -37,7 +37,7 @@ describe('the risk scales', () => {
]); ]);
expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']); expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']); expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años']; const labels = ['Probabilidad inmediata (al índice)', 'Probabilidad a 5 años'];
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels); for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]); expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]);
expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]); expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]);
@@ -48,15 +48,15 @@ describe('the risk scales', () => {
expect(rest).toEqual([]); expect(rest).toEqual([]);
expect(none.title).toBeUndefined(); expect(none.title).toBeUndefined();
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([ expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
['Riesgo inmediato (al índice)', undefined], ['Probabilidad inmediata (al índice)', undefined],
['Riesgo a 5 años', undefined], ['Probabilidad a 5 años', undefined],
]); ]);
}); });
it('the PDF keeps its flat list, with no scale for a page with no model', () => { it('the PDF keeps its flat list, with no scale for a page with no model', () => {
expect(riskScales([])).toEqual([]); expect(riskScales([])).toEqual([]);
expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([ expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([
'M, riesgo inmediato', 'M, probabilidad inmediata',
'M, riesgo a 5 años', 'M, probabilidad a 5 años',
]); ]);
}); });
}); });
@@ -84,3 +84,21 @@ describe('which models feed the risk scales', () => {
]); ]);
}); });
}); });
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();
});
});
+141 -12
View File
@@ -21,7 +21,7 @@ export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(mo
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] { export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) => return models.flatMap((m) =>
[0, 5].map((years) => ({ [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), risk: m.predictions.find((p) => p.years === years),
})), })),
); );
@@ -48,24 +48,78 @@ export interface RiskGroup {
title?: string; title?: string;
scenario?: string; scenario?: string;
index?: string; index?: string;
survival?: boolean;
inputs?: Record<string, unknown>;
/** the model and version that scored her, and the day it did */
model?: string;
evaluated?: string;
scales: { label: string; risk?: Prediction }[]; scales: { label: string; risk?: Prediction }[];
} }
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(
models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
text?: string;
evaluated?: string;
}[],
): RiskGroup[] {
return models
.map((m) => ({
title: 'Supervivencia',
index: m.index,
survival: true,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '),
scales: m.predictions.flatMap((p) => {
const v = horizon(m.predictions, p.years);
return v
? [
{
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
}))
.filter((g) => g.scales.length);
}
const HORIZONS: [number, string][] = [ const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'], [0, 'Probabilidad inmediata (al índice)'],
[5, 'Riesgo a 5 años'], [5, 'Probabilidad a 5 años'],
]; ];
/** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */ /** 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 } { export function titleParts(text: string): { title: string; scenario?: string } {
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!; const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
return { title, scenario }; 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 /** The scales the page draws: both horizons of every model, or, with no model, both horizons
* unavailable. */ * unavailable. */
export function riskGroups( export function riskGroups(
models: { text: string; index: string; predictions: Prediction[] }[], models: {
text: string;
index: string;
predictions: Prediction[];
inputs?: Record<string, unknown>;
evaluated?: string;
}[],
): RiskGroup[] { ): RiskGroup[] {
const scales = (predictions: Prediction[]) => const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) })); HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
@@ -73,6 +127,9 @@ export function riskGroups(
? models.map((m) => ({ ? models.map((m) => ({
...titleParts(m.text), ...titleParts(m.text),
index: m.index, index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions), scales: scales(m.predictions),
})) }))
: [{ scales: scales([]) }]; : [{ scales: scales([]) }];
@@ -85,9 +142,6 @@ export function riskGroups(
selector: 'app-risk-scales', selector: 'app-risk-scales',
imports: [DecimalPipe], imports: [DecimalPipe],
template: ` template: `
@if (groups().length) {
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
}
@for (g of groups(); track $index) { @for (g of groups(); track $index) {
@if (g.title) { @if (g.title) {
<h3>{{ g.title }}</h3> <h3>{{ g.title }}</h3>
@@ -105,7 +159,7 @@ export function riskGroups(
· No disponible · No disponible
} }
</p> </p>
<div class="risk-plot" [class.unavailable]="!s.risk"> <div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="risk-line" aria-hidden="true"></div> <div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) { @if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) { @if (r.low !== undefined && r.high !== undefined) {
@@ -134,12 +188,55 @@ export function riskGroups(
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }} {{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p> </p>
} }
@if (g.title && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (item of entries(g.inputs); track item[0]) {
<div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</section>
}
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (item of entries(g.inputs ?? {}); track item[0]) {
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
} }
`, `,
styles: ` styles: `
.note {
margin: 0 0 8px;
}
.risk-scale { .risk-scale {
margin: 8px 0 14px; margin: 8px 0 14px;
max-width: 740px; max-width: 740px;
@@ -170,6 +267,15 @@ export function riskGroups(
#fff 25% #fff 25%
); );
} }
.survival .risk-line {
background: linear-gradient(
to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
}
.risk-interval { .risk-interval {
border-left: 2px solid #17324d; border-left: 2px solid #17324d;
border-right: 2px solid #17324d; border-right: 2px solid #17324d;
@@ -216,4 +322,27 @@ export function riskGroups(
}) })
export class RiskScales { export class RiskScales {
readonly groups = input.required<RiskGroup[]>(); readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries;
protected readonly inputName = (name: string) =>
(
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
} }
+4 -1
View File
@@ -24,6 +24,9 @@ describe('risk series', () => {
], ],
}); });
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]); expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('Institucional · LIEAG+ (CIN2+)'); expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
'NCI, ingreso a LIEAG+',
);
}); });
}); });
+36 -124
View File
@@ -1,12 +1,7 @@
import { DecimalPipe } from '@angular/common'; import { Component, computed, input } from '@angular/core';
import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
import { Plot } from '../plot'; import { CurveChooser } from './curve-chooser';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import { REASON_TEXT } from './reference-risk';
export interface SeriesPoint { export interface SeriesPoint {
years: number; years: number;
@@ -32,12 +27,16 @@ const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3+', 'CIN3+': 'CIN3+',
cancer: 'Cáncer', cancer: 'Cáncer',
}; };
const REASONS: Record<string, string> = {
...REASON_TEXT,
history_is_registered: 'Tiene antecedentes registrados: no corresponde la tabla de ingreso.',
};
export const seriesName = (s: Series) => `${s.source} · ${OUTCOME_TEXT[s.outcome] ?? s.outcome}`; 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. */ /** The series of the answer. A value absent from it stays absent. */
export function parseSeries(answer: Parameters): Series[] { export function parseSeries(answer: Parameters): Series[] {
@@ -61,126 +60,48 @@ export function parseSeries(answer: Parameters): Series[] {
})); }));
} }
/** The chosen series as bars at one horizon and as curves. Series are shown side by side; no /** The chosen series as curves. Series are shown side by side; no difference is computed. */
* difference between them is computed. */
@Component({ @Component({
selector: 'app-risk-series', selector: 'app-risk-series',
imports: [DecimalPipe, MatCheckboxModule, MatFormFieldModule, MatSelectModule, Plot], imports: [CurveChooser],
template: ` template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p> <p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
<div class="choices"> @if (available().length) {
@for (s of available(); track s.id) { <app-curve-chooser [choices]="choices()" [draw]="draw()" [notes]="assumptions()" />
<mat-checkbox [checked]="chosen().has(s.id)" (change)="toggle(s.id)">
{{ name(s) }}
</mat-checkbox>
}
</div>
@if (selected().length) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Horizonte</mat-label>
<mat-select [value]="horizon()" (selectionChange)="picked.set($event.value)">
@for (h of horizons(); track h) {
<mat-option [value]="h">{{ h === 0 ? 'Al índice' : h + ' años' }}</mat-option>
}
</mat-select>
</mat-form-field>
<ul class="bars">
@for (b of bars(); track b.series.id) {
<li>
<span>{{ name(b.series) }}</span>
<small class="muted">{{ b.series.label }}</small>
@if (b.point; as p) {
<span class="track"><span class="fill" [style.width.%]="p.p * 100"></span></span>
<span>
{{ p.p * 100 | number: '1.1-2' }} %
@if (p.low !== undefined && p.high !== undefined) {
(IC 95 %: {{ p.low * 100 | number: '1.1-2' }}–{{
p.high * 100 | number: '1.1-2'
}})
} @else { } @else {
(IC 95 % no publicado) <p class="muted">No disponible: datos insuficientes.</p>
}
</span>
} @else {
<span class="muted">No disponible en este horizonte.</span>
}
@for (a of b.series.assumptions; track a) {
<small class="muted">{{ a }}</small>
}
</li>
}
</ul>
<app-plot [figure]="figure()" [height]="340" />
}
@for (s of unavailable(); track s.id) {
<p class="muted">{{ name(s) }}: no disponible. {{ why(s) }}</p>
} }
`, `,
styles: ` styles: `
:host { :host {
display: block; display: block;
} }
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
.bars {
list-style: none;
padding: 0;
}
.bars li {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
.track {
background: var(--color-action-hover, #f1f6f6);
height: 10px;
}
.fill {
background: #4269a0;
display: block;
height: 100%;
}
`, `,
}) })
export class RiskSeries { export class RiskSeries {
readonly series = input.required<Series[]>(); readonly series = input.required<Series[]>();
protected readonly name = seriesName;
protected readonly available = computed(() => this.series().filter((s) => s.points.length)); protected readonly available = computed(() => this.series().filter((s) => s.points.length));
protected readonly unavailable = computed(() => this.series().filter((s) => !s.points.length)); /** the platform's own series are drawn until the user says otherwise */
/** what the user toggled away from the default (the institutional series) */ protected readonly choices = computed(() =>
private readonly toggled = signal(new Set<string>()); this.available().map((s) => ({
protected readonly chosen = computed( id: s.id,
() => name: seriesName(s),
new Set( on: s.source === 'Institucional',
this.available()
.filter((s) => (s.source === 'Institucional') !== this.toggled().has(s.id))
.map((s) => s.id),
),
);
protected readonly selected = computed(() =>
this.available().filter((s) => this.chosen().has(s.id)),
);
protected readonly horizons = computed(() =>
[...new Set(this.selected().flatMap((s) => s.points.map((p) => p.years)))].sort(
(a, b) => a - b,
),
);
protected readonly picked = signal(5);
protected readonly horizon = computed(() =>
this.horizons().includes(this.picked()) ? this.picked() : this.horizons().at(-1)!,
);
protected readonly bars = computed(() =>
this.selected().map((series) => ({
series,
point: series.points.find((p) => p.years === this.horizon()),
})), })),
); );
protected readonly figure = computed(() => { private readonly among = computed(() => {
const shown = this.selected().map((s) => ({ 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, model: s.id,
text: seriesName(s), text: seriesName(s),
index: '', index: '',
@@ -191,15 +112,6 @@ export class RiskSeries {
// sources do not share an index date: the axis says only the horizon // sources do not share an index date: the axis says only the horizon
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' }; figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure; return figure;
};
}); });
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
protected why(s: Series) {
return s.reasons.map((r) => REASONS[r] ?? r).join(' ');
}
} }
@@ -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;
}
+6 -1
View File
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
export class Plot implements OnDestroy { export class Plot implements OnDestroy {
readonly figure = input.required<Figure>(); readonly figure = input.required<Figure>();
readonly height = input(320); readonly height = input(320);
/** Plotly's buttons over the chart; a record's curves go without them */
readonly toolbar = input(true);
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host'); private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() { constructor() {
effect(() => { effect(() => {
const { data, layout } = this.figure(); const { data, layout } = this.figure();
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG); void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
...CONFIG,
...(this.toolbar() ? {} : { displayModeBar: false }),
});
}); });
} }