Compare commits

...

20 Commits

Author SHA1 Message Date
edgar 0fe772ed6f Describir los motivos de exclusión de la referencia 2026-12-03 17:12:03 -06:00
Angel Capetillo Zavala 63f6e16d19 Clarify CaCu and CaMa chart labels 2026-12-03 15:18:22 -06:00
Angel Capetillo Zavala d38c795c8a Hide the CaMa diagnosis-to-treatment card until the indicator is defined
The card read "Indicador no disponible" and the route listed a step with no
measure. Both are removed from the CaMa summary, and the opportunity grid sizes
its columns to the cards it has so the remaining ones fill the row.
2026-12-03 11:00:55 -06:00
Angel Capetillo Zavala 3bff3d5e3f Añadir exportaciones de CaMa y conservar los filtros aplicados 2026-12-03 10:23:42 -06:00
edgar 4ec071332d Usar un solo selector de curvas para riesgo y supervivencia 2026-12-03 07:31:12 -06:00
edgar 5a82dc780e Elegir los ajustes de supervivencia que se comparan 2026-12-03 07:30:01 -06:00
edgar db74a19439 Dibujar todos los ajustes de supervivencia en la ficha 2026-12-03 07:28:48 -06:00
edgar 24415b79b6 Quitar la barra de Plotly en las curvas de la ficha 2026-12-03 00:24:50 -06:00
edgar b43c89befd Decir una sola vez el supuesto de la referencia NCI 2026-12-03 00:18:28 -06:00
edgar 9c17a383d1 Usar barras comunes en confirmación y renombrar la serie de ingreso del NCI 2026-12-03 00:06:32 -06:00
edgar 8e16de33b7 Mostrar tabla de valores de supervivencia 2026-12-02 23:44:28 -06:00
edgar 5d660b7043 Mostrar confirmación con intervalo en barra y ajustar etiquetas de la ficha 2026-12-02 23:43:18 -06:00
edgar a3a100450b Mostrar supervivencia con su curva de combinación y métodos por estimación 2026-12-02 23:20:51 -06:00
edgar a92515eb4d Mostrar factores usados en cada estimación 2026-12-02 23:13:59 -06:00
edgar 5f92c49ed4 Mostrar escalas de supervivencia publicadas 2026-12-02 23:00:06 -06:00
edgar a22ce12067 Mostrar solo curvas de probabilidad disponibles 2026-12-02 22:53:44 -06:00
edgar a19874438b Ajustar resumen y ocultar series no disponibles 2026-12-02 22:50:30 -06:00
edgar c08a0b8874 Ajustar pestañas y etiquetas de días 2026-12-02 21:54:54 -06:00
edgar 5201340a13 Aclarar etiquetas de días en indicadores CaCu 2026-12-02 21:50:01 -06:00
edgar cca9517b7c Conservar la exclusión por histerectomía cuando la API no la reporta 2026-12-02 20:26:14 -06:00
41 changed files with 1973 additions and 360 deletions
+11 -11
View File
@@ -14,8 +14,8 @@ const TITLES = {
cytology: 'Distribución de resultados citológicos', cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo', genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical', biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Valor predictivo positivo de la colposcopía', colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia', ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
}; };
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({ test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
@@ -30,17 +30,17 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([ expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad', 'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje', 'Tiempos de tamizaje',
'Indicadores clínicos', 'Indicadores clínicos',
'Resultados de citología, VPH y biopsia', 'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos', 'Distribución de resultados citológicos',
'Resultados de VPH por genotipo', 'Resultados de VPH por genotipo',
'Resultados de biopsia cervical', 'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica', 'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía', 'Tasa de confirmación histopatológica de referencia a colposcopía',
]); ]);
const route = tab.locator('app-readings').first(); const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) { for (const mode of ['Por ventana de tiempo', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click(); await route.getByRole('radio', { name: mode }).click();
await expect( await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')), route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
@@ -105,14 +105,14 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
.getByRole('radio', ROUND) .getByRole('radio', ROUND)
.click(); .click();
await expect( await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }), tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible(); ).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click(); await tab.getByRole('radio', { name: 'Solicitudes' }).click();
}); });
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => { test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: '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: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const link = page.locator('table.worklist tbody tr a').first(); 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: 'Análisis de riesgos' }).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();
+14 -4
View File
@@ -65,7 +65,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: '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: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.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([]);
}); });
@@ -205,6 +205,16 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>'); const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Análisis de Riesgo', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Trazabilidad', exact: true })).toHaveCount(1);
const labels = await page.getByRole('tab').allTextContents();
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
});
}
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one. // CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) { for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
@@ -242,7 +252,7 @@ for (const domain of ['cama', 'tea']) {
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad'); const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual( expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
); );
// Each figure drawn is one of the old kinds (a figure with no data in the period is named). // Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab const drawn = await tab
+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"
+7 -7
View File
@@ -157,15 +157,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', 'Detección subsecuente<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(['Detección subsecuente<br>Pacientes: 6']);
}); });
}); });
}); });
@@ -173,7 +173,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 +198,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 +247,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']);
}); });
}); });
+60 -8
View File
@@ -16,6 +16,10 @@ export type Mode = {
kind: 'counts'; kind: 'counts';
measure: string; measure: string;
catalog: Category[]; catalog: Category[];
/** 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 +31,7 @@ export type Mode = {
order: string[]; order: string[];
complete?: boolean; complete?: boolean;
colors?: Colors; colors?: Colors;
percentLabel?: string;
} }
| { | {
kind: 'positives'; kind: 'positives';
@@ -35,8 +40,15 @@ 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;
@@ -47,6 +59,8 @@ export type Mode = {
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 */
@@ -54,9 +68,19 @@ export type Mode = {
hidden?: Hidden; hidden?: Hidden;
} }
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint } | { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
| { kind: 'ratio'; measure: string; colors?: Colors; 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 */
| { | {
@@ -204,6 +228,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,7 +261,7 @@ 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.map(({ code, label, color }) => {
const n = size(cells[code]); const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)]; const cols = [`${n}`, pct(n, total)];
@@ -240,6 +283,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 +300,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 +315,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 +331,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 +343,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':
@@ -328,7 +376,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],
@@ -459,6 +507,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) => {
@@ -486,7 +535,7 @@ function complete(
const none = empty.length === classified.length; const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0; 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.'
@@ -499,10 +548,13 @@ function complete(
}; };
} }
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,
@@ -522,7 +574,7 @@ function medians(
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1; const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 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 }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] }; if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
@@ -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');
});
});
+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,
]),
};
}
+3 -3
View File
@@ -36,7 +36,7 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <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="Trazabilidad"> <mat-tab label="Trazabilidad">
@@ -45,7 +45,7 @@ import { Loading } from '../loading';
</ng-template> </ng-template>
</mat-tab> </mat-tab>
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
<mat-tab label="Análisis de riesgos"> <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>
@@ -57,7 +57,7 @@ import { Loading } from '../loading';
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'cama') { } @else if (domain() === 'cama') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="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 -2
View File
@@ -19,8 +19,8 @@ export const LAYOUTS: Record<string, Layout> = {
], ],
route: [ route: [
{ {
label: 'Resultado de citología', label: 'Días de toma de citología a resultado',
step: 'Toma a resultado de citología', step: 'Días de toma de citología a resultado',
fromSample: 'CACU_EU_TIEMPO_REPORTE', fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE', fromStep: 'CACU_EU_TIEMPO_REPORTE',
}, },
+1
View File
@@ -106,6 +106,7 @@ export const LABELS: Record<string, string> = {
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',
+58 -20
View File
@@ -59,7 +59,7 @@ 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 = [ const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] }, { code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] },
@@ -107,18 +107,28 @@ const groupViews = (
measure, measure,
catalog, catalog,
unit, unit,
caption: more.ofAll
? '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 +137,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 +147,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,6 +156,7 @@ 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',
@@ -154,6 +167,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
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 +188,29 @@ export const CACU: Page = {
}, },
{ {
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado', title: 'Días de toma de citología a resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo 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: 'Tiempo de tamizaje a diagnóstico tras biopsia', title: 'Días de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
...CACU_DAYS, ...CACU_DAYS,
}, },
], ],
opportunity: [ opportunity: [
{ {
kind: 'readings', kind: 'readings',
title: 'Tiempos de la ruta del tamizaje', title: '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,19 +218,25 @@ export const CACU: Page = {
tint: TINT, tint: TINT,
label: 'Acumulado desde la toma', label: 'Acumulado desde la toma',
steps: [ steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, { label: 'Días de toma de citología a resultado', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' }, { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' }, { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico tras biopsia', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA' }, {
label: 'Diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
], ],
}, },
{ {
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.', caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [ steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, {
label: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
},
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' }, { label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' }, { label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' }, { label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
@@ -237,7 +252,12 @@ export const CACU: Page = {
kind: 'days', kind: 'days',
tint: TINT, tint: TINT,
label: 'Diagnóstico tras biopsia', label: 'Diagnóstico tras biopsia',
steps: [{ label: 'Toma a diagnóstico tras biopsia', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA' }], steps: [
{
label: 'Toma a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
}, },
], ],
}, },
@@ -255,7 +275,14 @@ 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 }, {
kind: 'counts',
label: GENERAL,
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
unit: 'Pacientes',
percentLabel: 'Porcentaje de pacientes',
},
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'), ...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'),
], ],
}, },
@@ -270,9 +297,14 @@ 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', { ofAll: true, hidden: HPV_HIDDEN }), ...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
ofAll: true,
hidden: HPV_HIDDEN,
}),
], ],
}, },
{ {
@@ -285,6 +317,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',
}, },
], ],
}, },
@@ -300,6 +334,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',
), ),
}, },
{ {
@@ -308,12 +343,15 @@ 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', kind: 'counts',
label: 'Solicitudes', label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.', caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS, catalog: REQUESTS,
unit: 'Solicitudes',
percentLabel: 'Porcentaje de solicitudes',
}, },
), ),
}, },
+15 -16
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 = {
@@ -263,29 +264,24 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica', title: 'Días de toma de mastografía a interpretación radiológica',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico', title: 'Días de interpretación radiológica a diagnóstico',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: PENDING,
},
], ],
opportunity: [ opportunity: [
{ {
kind: 'route', kind: 'route',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a diagnóstico',
// from the mammography: only the two measures that start at it // from the mammography: only the two measures that start at it
sample: [ sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' }, { label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)', label: 'Diagnóstico (días de tamizaje a diagnóstico)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
}, },
], ],
@@ -299,7 +295,6 @@ export const PAGES: Record<string, Page> = {
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',
}, },
{ label: 'Diagnóstico a tratamiento' },
], ],
}, },
], ],
@@ -347,6 +342,7 @@ export const PAGES: Record<string, Page> = {
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: [...BIOPSY_GRADES, ...NO_RESULT], catalog: [...BIOPSY_GRADES, ...NO_RESULT],
percent: true, percent: true,
percentLabel: 'Porcentaje de pacientes',
}, },
], ],
}, },
@@ -371,6 +367,7 @@ export const PAGES: Record<string, Page> = {
measure: 'CAMA_BIOPSIAS', measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]], catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
percent: true, percent: true,
percentLabel: 'Porcentaje de reportes de biopsia',
}, },
], ],
}, },
@@ -391,6 +388,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',
}, },
], ],
}, },
@@ -476,27 +475,27 @@ export const HISTORY: Record<string, History> = {
], ],
), ),
{ {
title: 'Días de la toma de la citología a su resultado', title: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a primer diagnóstico', title: 'Días de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a diagnóstico tras biopsia', title: 'Días 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: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
+11 -1
View File
@@ -54,7 +54,7 @@ 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>
} }
@@ -146,6 +146,9 @@ import { Reading } from './measures';
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`, `,
styles: ` styles: `
:host { :host {
@@ -347,6 +350,8 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** a line under the figure */
readonly foot = input('');
/** the card around it names it already (tabs inside one card) */ /** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false); readonly hideTitle = input(false);
readonly camaStyle = input(false); readonly camaStyle = input(false);
@@ -359,6 +364,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],
); );
+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);
+5 -1
View File
@@ -45,7 +45,11 @@
<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]="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) { @for (k of pg.kpis; track k.title) {
<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>
+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>
+20 -16
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],
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu'); ['Búsqueda', query.search],
else await savePdf([sheet], 'seguimiento-cacu', true); ['Horizonte de la probabilidad (años)', `${query.horizon}`],
]);
});
} catch { } catch {
this.saveError.set('No se generó el archivo.'); this.saveError.set('No se generó el archivo.');
} finally { } finally {
+19
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">
+41 -14
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('');
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({ private readonly first = resource({
params: () => ({ params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
domain: this.domain(), loader: ({ params: { domain, query, size } }) => {
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined); this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', { return this.fhir.search(domain, 'Patient', { ...query, _count: size });
...params,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
}, },
}); });
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);
} }
+2 -2
View File
@@ -33,10 +33,10 @@ interface Drawn {
</mat-button-toggle-group> </mat-button-toggle-group>
</section> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" /> <app-loading what="el histórico" text="Cargando histórico…" />
} @else if (series.error()) { } @else if (series.error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
No se pudo cargar la trazabilidad. No se pudo cargar el histórico.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button> <button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p> </p>
} @else { } @else {
@@ -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',
+148 -85
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) {
<h1> <div class="record-head">
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code> <h1>
</h1> {{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1>
@if (cama()) {
<div class="head-actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
}
</div>
@if (cama() && saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<dl class="summary"> <dl class="summary">
<div> <div>
<dt>CURP</dt> <dt>CURP</dt>
@@ -246,66 +258,68 @@
</mat-card> </mat-card>
} }
<mat-card appearance="outlined" class="wide" data-section="riesgos"> @if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) {
<mat-card-content> <mat-card appearance="outlined" class="wide" data-section="riesgos">
@if (riskExclusion(); as reason) { <mat-card-content>
<p role="status">{{ reason }}</p> @if (riskExclusion(); as reason) {
} @else { <p role="status">{{ reason }}</p>
<app-risk-scales [groups]="groups()" /> } @else {
} <app-risk-scales [groups]="groups()" />
@if (riskModels().length) { }
<details data-section="modelos"> @if (riskModels().length) {
<summary>Modelos y valores</summary> <details data-section="modelos">
<table class="plain"> <summary>Modelos y valores</summary>
<thead> <table class="plain">
<tr> <thead>
<th>Modelo</th> <tr>
<th>Fecha índice</th> <th>Modelo</th>
<th>Horizonte</th> <th>Fecha índice</th>
<th>Probabilidad</th> <th>Horizonte</th>
<th>IC 95 %</th> <th>Probabilidad</th>
</tr> <th>IC 95 %</th>
</thead> </tr>
<tbody> </thead>
@for (m of riskModels(); track m.model) { <tbody>
@for (p of m.predictions; track p.years) { @for (m of riskModels(); track m.model) {
<tr> @for (p of m.predictions; track p.years) {
<td>{{ $first ? m.text : '' }}</td> <tr>
<td>{{ $first ? m.index : '' }}</td> <td>{{ $first ? m.text : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td> <td>{{ $first ? m.index : '' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td> <td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td> <td>{{ p.p * 100 | number: '1.1-2' }} %</td>
@if (p.low !== undefined) { <td>
{{ p.low * 100 | number: '1.1-2' }}–{{ @if (p.low !== undefined) {
p.high! * 100 | number: '1.1-2' {{ p.low * 100 | number: '1.1-2' }}–{{
}} p.high! * 100 | number: '1.1-2'
% }}
} @else { %
— } @else {
} —
</td> }
</tr> </td>
</tr>
}
} }
} </tbody>
</tbody> </table>
</table> </details>
</details> }
} @if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) { <details class="curves" open data-section="curvas">
<details class="curves" open data-section="curvas"> <summary>Curvas de probabilidad con su intervalo</summary>
<summary>Curvas de probabilidad con su intervalo</summary> @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" [toolbar]="false" />
<app-plot [figure]="curve()" [height]="300" /> }
} </details>
</details> }
} @if (!riskModels().length && !riskExclusion()) {
@if (!riskModels().length && !riskExclusion()) { <p class="muted">Sin evaluación de un modelo en producción.</p>
<p class="muted">Sin evaluación de un modelo en producción.</p> }
} </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 +571,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>
<h3>Análisis de supervivencia</h3> @if (domain() !== 'cacu') {
@if (domain() === 'cacu') { <h3>Análisis de supervivencia</h3>
<p class="muted" data-note="grupo">
Las curvas son estimaciones del grupo de pacientes del escenario clínico
correspondiente (S(t), probabilidad de supervivencia); no son predicciones
individuales.
</p>
} }
@if (survival.isLoading()) { @if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
@for (g of survivalScales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
v.risk!.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
</tbody>
</table>
</details>
}
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.curves) {
<p class="muted">
Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 %
Greenwood; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p>
<app-curve-chooser [choices]="c.curves.choices" [draw]="c.curves.draw" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" /> <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 +647,14 @@
} }
</ul> </ul>
@if (s.methods.length) { @if (s.methods.length) {
<h3>Métodos</h3> <details>
<ul class="scenarios methods"> <summary>Métodos</summary>
@for (name of s.methods; track name) { <ul class="scenarios methods">
<li>{{ name }}</li> @for (name of s.methods; track name) {
} <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 +678,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 -12
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,
@@ -158,18 +181,17 @@ export class Paciente {
}); });
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv')); protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff())); protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** Why she has no risk estimate; nothing when she is eligible. Only while the backend gives /** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
* no decision (failure, gold not updated) is the hysterectomy of her record held against it. */ * hysterectomy of her record is still held against her when the backend does not report it,
* as with evidence loaded without the day it was available. */
protected readonly riskExclusion = computed(() => { protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined; if (this.domain() !== 'cacu') return undefined;
const patient = this.patient(); const patient = this.patient();
const sample = this.citologia()?.slice(0, 10); const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff(); const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const state = this.eligibility(); const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
if (state.kind === 'evaluated' || state.kind === 'none') { const reported = ineligibility(this.eligibility(), status, index);
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? ''; if (reported) return reported;
return ineligibility(state, status, index);
}
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate; const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index return recorded && recorded <= index
? `No disponible por: histerectomía registrada el ${recorded}.` ? `No disponible por: histerectomía registrada el ${recorded}.`
@@ -184,14 +206,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: () =>
@@ -243,11 +293,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],
@@ -274,6 +328,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 [];
@@ -342,6 +441,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')
+19 -1
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 });
@@ -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();
});
});
+134 -8
View File
@@ -48,9 +48,54 @@ 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, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'], [5, 'Riesgo a 5 años'],
@@ -65,7 +110,13 @@ export function titleParts(text: string): { title: string; scenario?: string } {
/** 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 +124,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 +139,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 +156,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 +185,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 +264,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 +319,27 @@ export function riskGroups(
}) })
export class RiskScales { export class RiskScales {
readonly groups = input.required<RiskGroup[]>(); readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries;
protected readonly inputName = (name: string) =>
(
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
} }
+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+',
);
}); });
}); });
+47 -135
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,145 +60,58 @@ 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)"> } @else {
{{ name(s) }} <p class="muted">No disponible: datos insuficientes.</p>
</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 {
(IC 95 % no publicado)
}
</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();
model: s.id, return (ids: Set<string>) => all.filter((s) => ids.has(s.id));
text: seriesName(s), });
index: '', /** what the chosen series assume, each said once */
predictions: s.points, protected readonly assumptions = computed(() => {
})); const chosen = this.among();
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); return (ids: Set<string>) => [...new Set(chosen(ids).flatMap((s) => s.assumptions))];
const figure = curveFigure(shown, top); });
// sources do not share an index date: the axis says only the horizon protected readonly draw = computed(() => {
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' }; const chosen = this.among();
return figure; return (ids: Set<string>) => {
const shown = chosen(ids).map((s) => ({
model: s.id,
text: seriesName(s),
index: '',
predictions: s.points,
}));
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
const figure = curveFigure(shown, top);
// sources do not share an index date: the axis says only the horizon
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure;
};
}); });
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 }),
});
}); });
} }