Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f92bcd80b9 | |||
| 4789282e17 | |||
| 22edb0bf42 | |||
| c128448317 | |||
| c28cf31e2a | |||
| f6dffb6dc2 | |||
| 1820b8ce2b | |||
| 1abfc27013 | |||
| e31c128991 | |||
| 972bdf0d8a | |||
| 7167426283 | |||
| cbc41ca365 | |||
| 94c3bb6d82 | |||
| 72aa91af04 | |||
| 2a84eb56ca | |||
| 84769cb0f4 | |||
| cbcb524902 | |||
| 0fe772ed6f | |||
| 63f6e16d19 | |||
| d38c795c8a | |||
| 3bff3d5e3f | |||
| 4ec071332d | |||
| 5a82dc780e | |||
| db74a19439 | |||
| 24415b79b6 | |||
| b43c89befd | |||
| 9c17a383d1 | |||
| 8e16de33b7 | |||
| 5d660b7043 | |||
| a3a100450b | |||
| a92515eb4d | |||
| 5f92c49ed4 |
+12
-12
@@ -9,7 +9,7 @@ test.beforeEach(async ({ page }) => {
|
||||
|
||||
const ROUND = { name: 'Por detección inicial y subsecuente' };
|
||||
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
|
||||
const VIEWS = ['General', 'Por grupo de edad', 'Por estatus de seguimiento', ROUND.name];
|
||||
const VIEWS = ['General', 'Por grupo de edad', ROUND.name];
|
||||
const TITLES = {
|
||||
cytology: 'Distribución de resultados citológicos',
|
||||
genotype: 'Resultados de VPH por genotipo',
|
||||
@@ -28,9 +28,7 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
|
||||
const headings = await tab
|
||||
.locator('h2, app-readings h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
|
||||
'Indicadores de oportunidad',
|
||||
'Días de la ruta del tamizaje',
|
||||
expect(headings.slice(headings.indexOf('Indicadores clínicos'))).toEqual([
|
||||
'Indicadores clínicos',
|
||||
'Resultados de citología, VPH y biopsia',
|
||||
'Distribución de resultados citológicos',
|
||||
@@ -38,9 +36,11 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
|
||||
'Resultados de biopsia cervical',
|
||||
'Tasa de confirmación histopatológica',
|
||||
'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||
'Indicadores de oportunidad',
|
||||
'Tiempos de tamizaje',
|
||||
]);
|
||||
const route = tab.locator('app-readings').first();
|
||||
for (const mode of ['Por pasos', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
|
||||
const route = tab.locator('app-readings').filter({ has: page.getByRole('heading', { name: 'Tiempos de tamizaje' }) });
|
||||
for (const mode of ['Por ventana de tiempo', 'Diagnóstico precolposcópico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
|
||||
await route.getByRole('radio', { name: mode }).click();
|
||||
await expect(
|
||||
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
|
||||
@@ -107,12 +107,12 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
|
||||
await expect(
|
||||
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
|
||||
).toBeVisible();
|
||||
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
|
||||
await expect(tab.getByRole('radio', { name: 'Solicitudes' })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
|
||||
await page.goto('/indicadores/cacu');
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
const list = page.locator('table.worklist tbody tr');
|
||||
await expect(list.first().locator('app-stages li')).toHaveCount(5);
|
||||
await list.first().getByRole('button', { name: 'Detalle' }).click();
|
||||
@@ -187,7 +187,7 @@ async function withRounds(page: Page, how: Simulation) {
|
||||
}
|
||||
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
|
||||
const plotOf = (readings: Locator) => readings.locator('.group').first();
|
||||
/** The groups of a card as the page draws them: "label<br>n = N", the width of the first bar and the colour of
|
||||
/** The groups of a card as the page draws them: "label<br>unit: N", the width of the first bar and the colour of
|
||||
* each category (the first group's rows), in hex. */
|
||||
const traces = (readings: Locator) =>
|
||||
readings.evaluate((el) => {
|
||||
@@ -202,7 +202,7 @@ const traces = (readings: Locator) =>
|
||||
return {
|
||||
y: groups.map(
|
||||
(g) =>
|
||||
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>n = ${g.querySelector('.n')!.textContent!.replace('n = ', '').trim()}`,
|
||||
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>${g.querySelector('.n')!.textContent!.trim()}`,
|
||||
),
|
||||
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
|
||||
colours: Object.fromEntries(
|
||||
@@ -277,7 +277,7 @@ for (const card of ['cytology', 'genotype'] as const) {
|
||||
const { card: of, view } = await withRounds(page, 'no-initial');
|
||||
await view(ROUND.name);
|
||||
const found = await traces(of(TITLES[card]));
|
||||
expect(found.y[0]).toBe('Detección inicial<br>n = 0');
|
||||
expect(found.y[0]).toBe('Detección inicial<br>Pacientes: 0');
|
||||
expect(found.x[0]).toBe(0);
|
||||
});
|
||||
|
||||
@@ -307,7 +307,7 @@ test('rondas (simulado): the genotype card never shows the incomplete positives,
|
||||
'VPH 16',
|
||||
'VPH 18',
|
||||
'VPH 16 y 18',
|
||||
'Positivo',
|
||||
'Positivo sin genotipo',
|
||||
]);
|
||||
for (const name of VIEWS.slice(1)) {
|
||||
await view(name);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
|
||||
/** The record of the first patient of the risk list, as an address. */
|
||||
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
|
||||
await page.goto('/indicadores/cacu');
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
const link = page.locator('table.worklist tbody tr a').first();
|
||||
await link.waitFor({ timeout: 120_000 });
|
||||
const url = (await link.getAttribute('href'))!;
|
||||
@@ -1467,9 +1467,7 @@ test('elegibilidad: the risk section shows the published post-treatment exclusio
|
||||
expect(patientId, 'a synthetic patient with a published post-treatment exclusion').toBeDefined();
|
||||
await open(page, `/indicadores/cacu/pacientes/${patientId}`);
|
||||
const box = riskBox(page);
|
||||
await expect(box.getByRole('status')).toHaveText(
|
||||
'No disponible por: Sin biopsia previa al tratamiento en el periodo requerido.',
|
||||
);
|
||||
await expect(box.getByRole('status')).toHaveText(/paciente ya tratada\.$/);
|
||||
await expect(box.locator('app-risk-scales')).toHaveCount(0);
|
||||
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
|
||||
});
|
||||
@@ -1587,7 +1585,7 @@ test('elegibilidad (simulado): a new patient never inherits the previous risk ex
|
||||
await open(page, firstUrl);
|
||||
await expect(reason).toBeVisible();
|
||||
await page.getByRole('link', { name: 'Regresar' }).click();
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click();
|
||||
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
|
||||
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
|
||||
|
||||
+35
-20
@@ -58,14 +58,14 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
);
|
||||
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
|
||||
|
||||
await page.getByRole('tab', { name: 'Histórico' }).click();
|
||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
||||
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
|
||||
|
||||
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
||||
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
|
||||
|
||||
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
const bundle = await (await list).json();
|
||||
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
|
||||
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
|
||||
@@ -84,14 +84,14 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
).not.toContainText('Sin estudios');
|
||||
|
||||
await page.goto('/indicadores/cama');
|
||||
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
|
||||
await page.getByRole('option', { name: '12 meses' }).click();
|
||||
const camaRows = page.locator('table.worklist tbody tr');
|
||||
await expect(camaRows.first()).toContainText('BI-RADS');
|
||||
await page.goto('/indicadores/tea');
|
||||
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -208,8 +208,8 @@ const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
|
||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
|
||||
await page.goto(`/indicadores/${domain}`);
|
||||
await expect(page.getByRole('tab', { name: 'Seguimiento', exact: true })).toHaveCount(1);
|
||||
await expect(page.getByRole('tab', { name: 'Histórico', exact: true })).toHaveCount(1);
|
||||
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);
|
||||
});
|
||||
@@ -226,22 +226,17 @@ for (const domain of ['cama', 'tea']) {
|
||||
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
|
||||
);
|
||||
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
|
||||
// Lote 2: the detection rate has its own title, and the histopathology figures are two
|
||||
// cards (the result by BI-RADS; the confirmation in two readings).
|
||||
const detection = (i: { text?: string }) =>
|
||||
i.text === 'Tasa de confirmación histopatológica'
|
||||
? { ...i, text: 'Tasa de detección histopatológica' }
|
||||
: i;
|
||||
// The histopathology figures are two cards: the result by BI-RADS and the confirmation.
|
||||
const results = all.findIndex(
|
||||
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
|
||||
(i) => i.text === 'Tipo histológico por categoría BI-RADS',
|
||||
);
|
||||
const cards = [
|
||||
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
|
||||
{ kind: 'h3', text: 'Tipo histológico por categoría BI-RADS' },
|
||||
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
|
||||
];
|
||||
const old =
|
||||
domain === 'cama'
|
||||
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
|
||||
? [...all.slice(0, route + 1), ...all.slice(clinical, results), ...cards]
|
||||
: all;
|
||||
await page.goto(`/indicadores/${domain}`);
|
||||
const tab = page.locator('app-tab-indicadores');
|
||||
@@ -251,9 +246,29 @@ for (const domain of ['cama', 'tea']) {
|
||||
.locator('h2, h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
const from = headings.indexOf('Indicadores de oportunidad');
|
||||
expect(headings.slice(from).map(period)).toEqual(
|
||||
old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
|
||||
);
|
||||
if (domain === 'cama') {
|
||||
const ordered = [
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 o 6',
|
||||
'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
'Tiempo de interpretación radiológica a diagnóstico',
|
||||
'Tiempo de interpretación radiológica a resultado de biopsia',
|
||||
'Tiempo de diagnóstico a tratamiento',
|
||||
'Tiempo de tamizaje a diagnóstico',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'Tipo histológico por categoría BI-RADS',
|
||||
'Confirmación histopatológica',
|
||||
];
|
||||
let last = -1;
|
||||
for (const title of ordered) {
|
||||
const next = headings.findIndex((h, index) => index > last && h.startsWith(title));
|
||||
expect(next, title).toBeGreaterThan(last);
|
||||
last = next;
|
||||
}
|
||||
} else {
|
||||
expect(headings.slice(from).map(period)).toEqual(
|
||||
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
|
||||
);
|
||||
}
|
||||
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
|
||||
const drawn = await tab
|
||||
.locator('.js-plotly-plot')
|
||||
@@ -278,7 +293,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
['h2', 'h3', 'plot'].includes(i.kind),
|
||||
);
|
||||
await page.goto(`/indicadores/${domain}`);
|
||||
await page.getByRole('tab', { name: 'Histórico' }).click();
|
||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
||||
const tab = page.locator('app-tab-trazabilidad');
|
||||
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
|
||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
||||
|
||||
Generated
+292
@@ -42,8 +42,10 @@
|
||||
"@types/fhir": "0.0.44",
|
||||
"@types/pdfmake": "0.3.5",
|
||||
"@types/plotly.js": "3.0.15",
|
||||
"fflate": "0.8.3",
|
||||
"jsdom": "^31.0.0",
|
||||
"ng-openapi-gen": "^1.1.0",
|
||||
"pdfjs-dist": "6.5.438",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "~6.0.2",
|
||||
"vitest": "^5.0.0"
|
||||
@@ -2013,6 +2015,283 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@napi-rs/canvas": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz",
|
||||
"integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"workspaces": [
|
||||
"e2e/*"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@napi-rs/canvas-android-arm64": "1.2.1",
|
||||
"@napi-rs/canvas-darwin-arm64": "1.2.1",
|
||||
"@napi-rs/canvas-darwin-x64": "1.2.1",
|
||||
"@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1",
|
||||
"@napi-rs/canvas-linux-arm64-gnu": "1.2.1",
|
||||
"@napi-rs/canvas-linux-arm64-musl": "1.2.1",
|
||||
"@napi-rs/canvas-linux-riscv64-gnu": "1.2.1",
|
||||
"@napi-rs/canvas-linux-x64-gnu": "1.2.1",
|
||||
"@napi-rs/canvas-linux-x64-musl": "1.2.1",
|
||||
"@napi-rs/canvas-win32-arm64-msvc": "1.2.1",
|
||||
"@napi-rs/canvas-win32-x64-msvc": "1.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-android-arm64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz",
|
||||
"integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-darwin-arm64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz",
|
||||
"integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-darwin-x64": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz",
|
||||
"integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz",
|
||||
"integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz",
|
||||
"integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz",
|
||||
"integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-x64-musl": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz",
|
||||
"integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz",
|
||||
"integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz",
|
||||
"integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/nice": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz",
|
||||
@@ -6077,6 +6356,19 @@
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/pdfjs-dist": {
|
||||
"version": "6.5.438",
|
||||
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
|
||||
"integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=22.13.0 || >=24"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@napi-rs/canvas": "^1.0.13"
|
||||
}
|
||||
},
|
||||
"node_modules/pdfkit": {
|
||||
"version": "0.20.2",
|
||||
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
|
||||
|
||||
@@ -46,8 +46,10 @@
|
||||
"@types/fhir": "0.0.44",
|
||||
"@types/pdfmake": "0.3.5",
|
||||
"@types/plotly.js": "3.0.15",
|
||||
"fflate": "0.8.3",
|
||||
"jsdom": "^31.0.0",
|
||||
"ng-openapi-gen": "^1.1.0",
|
||||
"pdfjs-dist": "6.5.438",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "~6.0.2",
|
||||
"vitest": "^5.0.0"
|
||||
|
||||
@@ -3,6 +3,64 @@ import { scenarioBars } from './figures';
|
||||
import { Reading } from './measures';
|
||||
|
||||
describe('bars', () => {
|
||||
it('shows histologic types by BI-RADS while deriving malignancy from biopsy classification', () => {
|
||||
const type: Reading = {
|
||||
populations: {},
|
||||
strata: {
|
||||
category: { '8500/3': { 'initial-population': 1 }, no_data: { 'initial-population': 1 } },
|
||||
birads: { '4A': { 'initial-population': 2 } },
|
||||
'birads-category': {
|
||||
'4A|8500/3': { 'initial-population': 1 },
|
||||
'4A|no_data': { 'initial-population': 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
const classification: Reading = {
|
||||
populations: {},
|
||||
strata: {
|
||||
'birads-category': {
|
||||
'4A|benign': { 'initial-population': 1 },
|
||||
'4A|invasive': { 'initial-population': 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
const mode: Mode = {
|
||||
kind: 'outcomes',
|
||||
label: 'Por categoría BI-RADS',
|
||||
measure: 'types',
|
||||
stratum: 'birads',
|
||||
rows: [{ code: '4A', label: '4A', color: '#000' }],
|
||||
results: [
|
||||
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#aaa' },
|
||||
{ code: 'no_data', label: 'Sin dato', color: '#bbb' },
|
||||
],
|
||||
malignant: ['in_situ', 'invasive'],
|
||||
dynamicResults: true,
|
||||
malignancyMeasure: 'grades',
|
||||
};
|
||||
const table = bars(mode, (key) => (key === 'types' ? type : classification))!;
|
||||
expect(table.head).toEqual(['Pacientes', 'Carcinoma ductal infiltrante', 'Sin biopsia', 'Sin dato', '% maligno']);
|
||||
expect(table.rows[0].cells).toEqual(['2', '1', '0', '1', '1/2 (50.0 %)']);
|
||||
expect(bars(mode, (key) => (key === 'types' ? type : undefined))!.rows[0].cells.at(-1)).toBe(
|
||||
'No disponible',
|
||||
);
|
||||
});
|
||||
it('lists histologic codes from gold and preserves missing types in the denominator', () => {
|
||||
const r: Reading = {
|
||||
populations: { 'initial-population': 4 },
|
||||
strata: {
|
||||
category: { '8500/3': { 'initial-population': 1 }, no_data: { 'initial-population': 3 } },
|
||||
},
|
||||
};
|
||||
const table = bars(
|
||||
{ kind: 'counts', label: 'Tipos histológicos', measure: 'M', catalog: [], unit: 'Biopsias' },
|
||||
() => r,
|
||||
)!;
|
||||
expect(table.rows.map((row) => [row.label, ...row.cells])).toEqual([
|
||||
['Carcinoma ductal infiltrante', '1', '25.0 %'],
|
||||
['Sin dato', '3', '75.0 %'],
|
||||
]);
|
||||
});
|
||||
it('list every category, so the shares add up', () => {
|
||||
const r: Reading = {
|
||||
populations: {},
|
||||
@@ -17,6 +75,41 @@ describe('bars', () => {
|
||||
['1', '25.0 %'],
|
||||
]);
|
||||
});
|
||||
it('aggregates only named abnormal cytology results without changing the denominator', () => {
|
||||
const cell = (n: number) => ({ 'initial-population': n });
|
||||
const r: Reading = {
|
||||
populations: { 'initial-population': 10 },
|
||||
strata: {
|
||||
category: { NILM: cell(4), LSIL: cell(2), HSIL: cell(1), no_data: cell(3) },
|
||||
'age_group-category': {
|
||||
'25-34|NILM': cell(4),
|
||||
'25-34|LSIL': cell(2),
|
||||
'25-34|HSIL': cell(1),
|
||||
'25-34|no_data': cell(3),
|
||||
},
|
||||
},
|
||||
};
|
||||
const catalog = ['NILM', 'LSIL', 'HSIL'].map((code) => ({ code, label: code, color: '#000' }));
|
||||
const aggregate = { label: 'Anormal', color: '#f00', codes: ['LSIL', 'HSIL'] };
|
||||
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, () => r)!;
|
||||
expect(t.rows[1].cells).toEqual(['3', '30.0 %']);
|
||||
expect(t.rows.map((row) => !!row.sub)).toEqual([false, false, true, true, false].slice(0, t.rows.length));
|
||||
const g = grouped(
|
||||
{
|
||||
kind: 'grouped',
|
||||
label: 'x',
|
||||
measure: 'M',
|
||||
catalog,
|
||||
aggregate,
|
||||
stratum: 'age_group',
|
||||
order: ['25-34'],
|
||||
unit: 'pacientes',
|
||||
ofAll: true,
|
||||
},
|
||||
() => r,
|
||||
)!;
|
||||
expect(g.groups[0].rows[1].text).toBe('3/10 · 30.0 %');
|
||||
});
|
||||
it('a group with no patients has no rate', () => {
|
||||
const r: Reading = {
|
||||
populations: {},
|
||||
@@ -47,7 +140,7 @@ describe('bars', () => {
|
||||
const t = bars(mode, () => r)!;
|
||||
expect(t.rows.map((x) => x.label)).toEqual([
|
||||
'Detección inicial',
|
||||
'Detección subsecuente',
|
||||
'Con detección anterior',
|
||||
'Sin dato',
|
||||
]);
|
||||
expect(t.rows.map((x) => x.cells)).toEqual([
|
||||
@@ -145,7 +238,7 @@ describe('bars', () => {
|
||||
c === 'initial'
|
||||
? 'Detección inicial'
|
||||
: c === 'subsequent'
|
||||
? 'Detección subsecuente'
|
||||
? 'Con detección anterior'
|
||||
: 'Sin dato',
|
||||
['initial', 'subsequent', 'no_data'],
|
||||
{ fill: true },
|
||||
@@ -157,15 +250,15 @@ describe('bars', () => {
|
||||
);
|
||||
const y = (f.data[0] as any).y;
|
||||
expect(y).toEqual([
|
||||
'Detección inicial<br>n = 0',
|
||||
'Detección subsecuente<br>n = 8',
|
||||
'Sin dato<br>n = 2',
|
||||
'Detección inicial<br>Pacientes: 0',
|
||||
'Con detección anterior<br>Pacientes: 8',
|
||||
'Sin dato<br>Pacientes: 2',
|
||||
]);
|
||||
expect((f.data[0] as any).x).toEqual([0, 75, 100]);
|
||||
});
|
||||
it('leaves out a group that does not reconcile', () => {
|
||||
const f = draw(reading({ 'subsequent|NILM': 6 }, 10));
|
||||
expect((f.data[0] as any).y).toEqual(['Detección subsecuente<br>n = 6']);
|
||||
expect((f.data[0] as any).y).toEqual(['Con detección anterior<br>Pacientes: 6']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -173,7 +266,7 @@ describe('bars', () => {
|
||||
describe('shared views of cytology and HPV by genotype', () => {
|
||||
const HPV = [
|
||||
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' },
|
||||
{ code: 'positive_other', label: 'Positivo', color: '#A8C243', group: '' },
|
||||
{ code: 'positive_other', label: 'Positivo sin genotipo', color: '#A8C243', group: '' },
|
||||
];
|
||||
const reading = (cells: Record<string, number>): Reading => ({
|
||||
populations: { 'initial-population': Object.values(cells).reduce((a, b) => a + b, 0) },
|
||||
@@ -198,7 +291,7 @@ describe('shared views of cytology and HPV by genotype', () => {
|
||||
|
||||
it('does not list a hidden category but keeps it in the total and the percentages', () => {
|
||||
const t = bars(counts, () => reading({}))!;
|
||||
expect(t.rows.map((x) => x.label)).toEqual(['Negativo', 'Positivo']);
|
||||
expect(t.rows.map((x) => x.label)).toEqual(['Negativo', 'Positivo sin genotipo']);
|
||||
expect(t.rows.map((x) => x.cells)).toEqual([
|
||||
['5', '50.0 %'],
|
||||
['2', '20.0 %'],
|
||||
@@ -247,7 +340,7 @@ describe('shared views of cytology and HPV by genotype', () => {
|
||||
});
|
||||
expect((own.data[0] as any).x).toEqual([80]); // 4 of the 5 the catalog draws
|
||||
expect((all.data[0] as any).x).toEqual([40]); // 4 of the group's 10 reports
|
||||
expect((all.data[0] as any).y).toEqual(['25-34<br>n = 10']);
|
||||
expect((all.data[0] as any).y).toEqual(['25-34<br>Reportes: 10']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -282,7 +375,7 @@ describe('independent bars by group', () => {
|
||||
)!;
|
||||
expect(g.groups.map((x) => [x.label, x.total])).toEqual([
|
||||
['Detección inicial', 4],
|
||||
['Detección subsecuente', 6],
|
||||
['Con detección anterior', 6],
|
||||
]);
|
||||
expect(g.groups[0].rows.map((r) => [r.label, r.text, r.percent, r.color])).toEqual([
|
||||
['Normal', '3/4 · 75.0 %', 75, '#408651'],
|
||||
@@ -300,7 +393,7 @@ describe('independent bars by group', () => {
|
||||
['0/0 · —', undefined],
|
||||
['0/0 · —', undefined],
|
||||
]);
|
||||
expect(empty.note).toContain('una categoría en cero significa');
|
||||
expect(empty.note).toBeUndefined();
|
||||
const unreconciled = grouped(mode({ complete: true }), () =>
|
||||
reading({ 'subsequent|NILM': 2 }, 5),
|
||||
)!;
|
||||
@@ -415,3 +508,52 @@ describe('independent bars by group', () => {
|
||||
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the subsequent round by last screening', () => {
|
||||
it('chains the steps of a time window, quartiles moving with their bar', () => {
|
||||
const median = (score: number, low: number, high: number): Reading => ({
|
||||
populations: { 'measure-observation': 1 },
|
||||
strata: {},
|
||||
score,
|
||||
low,
|
||||
high,
|
||||
});
|
||||
const steps = [
|
||||
{ label: 'a', measure: 'A' },
|
||||
{ label: 'b', measure: 'B' },
|
||||
];
|
||||
const table = bars({ kind: 'days', label: 'x', steps, staggered: true }, (m) =>
|
||||
m === 'A' ? median(10, 5, 10) : median(20, 10, 30),
|
||||
)!;
|
||||
expect(table.rows.map((r) => [r.offset, r.width, r.marks])).toEqual([
|
||||
[0, 25, [12.5, 25]],
|
||||
[25, 50, [50, 100]],
|
||||
]);
|
||||
});
|
||||
it('splits the subsequent round by last screening, drawing only those with an answer', () => {
|
||||
const one = { 'initial-population': 1 };
|
||||
const r: Reading = {
|
||||
populations: { 'initial-population': 3 },
|
||||
strata: {
|
||||
'round-category': { 'initial|a': one, 'subsequent|a': { 'initial-population': 2 } },
|
||||
'subsequent_history-category': { 'within_1_year|a': one, 'no_data|a': one },
|
||||
},
|
||||
};
|
||||
const mode: Mode = {
|
||||
kind: 'grouped',
|
||||
label: 'x',
|
||||
measure: 'M',
|
||||
stratum: 'round',
|
||||
order: ['initial', 'subsequent'],
|
||||
unit: 'pacientes',
|
||||
catalog: [{ code: 'a', label: 'A', color: '#000' }],
|
||||
};
|
||||
const { groups } = grouped(mode, () => r)!;
|
||||
expect(groups.map((g) => [g.code, g.total])).toEqual([
|
||||
['initial', 1],
|
||||
['within_1_year', 1],
|
||||
['2_years', 0],
|
||||
['3_or_more_years', 0],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
+189
-46
@@ -1,4 +1,5 @@
|
||||
import { CIE10 } from './cie10';
|
||||
import { chainStarts } from './durations';
|
||||
import { NEUTRAL_DARK } from './cacu-palette';
|
||||
import { name, Reading } from './measures';
|
||||
|
||||
@@ -16,6 +17,11 @@ export type Mode = {
|
||||
kind: 'counts';
|
||||
measure: string;
|
||||
catalog: Category[];
|
||||
aggregate?: { label: string; color: string; codes: string[] };
|
||||
/** The records counted in the category distribution. */
|
||||
unit?: string;
|
||||
/** What the share in the second column is a share of. */
|
||||
percentLabel?: string;
|
||||
hidden?: Hidden;
|
||||
/** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
|
||||
percent?: boolean;
|
||||
@@ -27,6 +33,7 @@ export type Mode = {
|
||||
order: string[];
|
||||
complete?: boolean;
|
||||
colors?: Colors;
|
||||
percentLabel?: string;
|
||||
}
|
||||
| {
|
||||
kind: 'positives';
|
||||
@@ -35,28 +42,54 @@ export type Mode = {
|
||||
order: string[];
|
||||
complete?: boolean;
|
||||
colors?: Colors;
|
||||
percentLabel?: string;
|
||||
}
|
||||
| {
|
||||
kind: 'signs';
|
||||
measure: string;
|
||||
strata: string[];
|
||||
colors?: Colors;
|
||||
percentLabel?: string;
|
||||
}
|
||||
| { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
|
||||
| {
|
||||
kind: 'grouped';
|
||||
measure: string;
|
||||
/** the categories drawn in each group, in this order (each in its own colour) */
|
||||
catalog: Category[];
|
||||
aggregate?: { label: string; color: string; codes: string[] };
|
||||
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
|
||||
stratum: string;
|
||||
order: string[];
|
||||
/** what the records are called ("pacientes", "reportes") */
|
||||
unit: string;
|
||||
/** The denominator of the percentage shown with each grouped result. */
|
||||
percentLabel?: string;
|
||||
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
|
||||
complete?: boolean;
|
||||
/** each group's denominator is all its records, not only those of the catalog's categories */
|
||||
ofAll?: boolean;
|
||||
hidden?: Hidden;
|
||||
}
|
||||
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
|
||||
| {
|
||||
kind: 'days';
|
||||
steps: { label: string; measure: string }[];
|
||||
tint?: Tint;
|
||||
/** each bar starts where the previous one ends (a schematic sequence, as a Gantt chart) */
|
||||
staggered?: boolean;
|
||||
}
|
||||
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
|
||||
| { kind: 'ratio'; measure: string; colors?: Colors; percentLabel?: string }
|
||||
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
|
||||
/** A proportion as its two parts (what counted and what did not), in units, with the shares */
|
||||
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
|
||||
| {
|
||||
kind: 'split';
|
||||
measure: string;
|
||||
yes: string;
|
||||
no: string;
|
||||
colors?: [string, string];
|
||||
unit?: string;
|
||||
percentLabel?: string;
|
||||
}
|
||||
/** Each row's units by result (a bar in segments), and the share of the row's units with a
|
||||
* result that are `malignant`; a row with units and no result is not a row with none */
|
||||
| {
|
||||
@@ -66,6 +99,8 @@ export type Mode = {
|
||||
rows: Category[];
|
||||
results: Category[];
|
||||
malignant: string[];
|
||||
dynamicResults?: boolean;
|
||||
malignancyMeasure?: string;
|
||||
}
|
||||
| {
|
||||
kind: 'figure';
|
||||
@@ -95,6 +130,7 @@ export type Tint = { bar: string; mark: string };
|
||||
|
||||
/** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
|
||||
export interface GroupRow {
|
||||
sub?: boolean;
|
||||
label: string;
|
||||
color: string;
|
||||
count: number;
|
||||
@@ -121,10 +157,14 @@ export interface Groups {
|
||||
|
||||
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
|
||||
export interface Bar {
|
||||
/** one of the categories the aggregate row above adds up */
|
||||
sub?: boolean;
|
||||
label: string;
|
||||
/** why the row has no figures: no patients in the group, or not available */
|
||||
hint?: string;
|
||||
color?: string;
|
||||
/** where the bar starts, in % of the scale */
|
||||
offset?: number;
|
||||
width: number;
|
||||
marks: number[];
|
||||
cells: string[];
|
||||
@@ -146,10 +186,8 @@ export interface Bars {
|
||||
|
||||
export const NOT_AVAILABLE = 'No disponible';
|
||||
export const NO_PATIENTS = 'Sin pacientes en el periodo';
|
||||
const EMPTY_ROUND =
|
||||
'Hay pacientes sin clasificación de ronda («Sin dato»): una categoría en cero significa que no hay pacientes clasificadas en esa ronda según la información disponible.';
|
||||
const NO_ROUND =
|
||||
'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
|
||||
'Ninguna paciente del periodo tiene clasificación de detección inicial o anterior: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
|
||||
|
||||
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
|
||||
|
||||
@@ -204,6 +242,25 @@ const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
|
||||
/** The bars of a mode; none when the period has nothing to draw. */
|
||||
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
|
||||
switch (mode.kind) {
|
||||
case 'ratio': {
|
||||
const r = of(mode.measure);
|
||||
const n = r?.populations['numerator'] ?? 0;
|
||||
const total = r?.populations['denominator'] ?? 0;
|
||||
if (r?.score === undefined || !total) return undefined;
|
||||
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
|
||||
return {
|
||||
head: ['n/N', mode.percentLabel ?? 'Porcentaje', 'IC 95 %'],
|
||||
rows: [
|
||||
{
|
||||
label: 'Total',
|
||||
color: mode.colors?.['numerator'],
|
||||
width: 100 * r.score,
|
||||
marks: ends.map((v) => 100 * v),
|
||||
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
case 'counts': {
|
||||
const cells = of(mode.measure)?.strata['category'] ?? {};
|
||||
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
|
||||
@@ -218,11 +275,25 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
];
|
||||
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
|
||||
return {
|
||||
head: ['n', '%'],
|
||||
rows: all.map(({ code, label, color }) => {
|
||||
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
|
||||
rows: all.flatMap(({ code, label, color }, index) => {
|
||||
const n = size(cells[code]);
|
||||
const cols = [`${n}`, pct(n, total)];
|
||||
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
|
||||
const part = !!mode.aggregate?.codes.includes(code);
|
||||
const row = { label, color, width: (100 * n) / most, marks: [], cells: cols, sub: part };
|
||||
if (index !== 0 || !mode.aggregate) return [row];
|
||||
const a = mode.aggregate;
|
||||
const sum = a.codes.reduce((total, key) => total + size(cells[key]), 0);
|
||||
return [
|
||||
row,
|
||||
{
|
||||
label: a.label,
|
||||
color: a.color,
|
||||
width: (100 * sum) / most,
|
||||
marks: [],
|
||||
cells: [`${sum}`, pct(sum, total)],
|
||||
},
|
||||
];
|
||||
}),
|
||||
note: hiddenNote(mode, of),
|
||||
};
|
||||
@@ -240,6 +311,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
cells[c]['denominator'] ?? 0,
|
||||
mode.colors?.[c],
|
||||
]),
|
||||
mode.percentLabel,
|
||||
);
|
||||
if (!patients(r) || !Object.keys(cells).length) return undefined;
|
||||
const sound = (c: string) =>
|
||||
@@ -256,6 +328,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
ok,
|
||||
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
|
||||
mode.colors,
|
||||
mode.percentLabel,
|
||||
);
|
||||
}
|
||||
case 'positives': {
|
||||
@@ -270,6 +343,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
const positive = size(cells[`${c}|positive`]);
|
||||
return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
|
||||
}),
|
||||
mode.percentLabel,
|
||||
);
|
||||
if (!patients(r) || !found.size) return undefined;
|
||||
const ok = reconciles(
|
||||
@@ -285,6 +359,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
return [positive, positive + size(cells[`${c}|negative`])];
|
||||
},
|
||||
mode.colors,
|
||||
mode.percentLabel,
|
||||
);
|
||||
}
|
||||
case 'signs': {
|
||||
@@ -296,6 +371,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
const positive = size(strata[s]['positive']);
|
||||
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
|
||||
}),
|
||||
mode.percentLabel,
|
||||
);
|
||||
}
|
||||
case 'days':
|
||||
@@ -305,6 +381,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
|
||||
}),
|
||||
mode.tint,
|
||||
mode.staggered,
|
||||
);
|
||||
case 'days-by': {
|
||||
const r = of(mode.measure);
|
||||
@@ -328,7 +405,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
[mode.no, denominator - numerator],
|
||||
];
|
||||
return {
|
||||
head: ['n', '%'],
|
||||
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
|
||||
rows: parts.map(([label, n], i) => ({
|
||||
label,
|
||||
color: mode.colors?.[i],
|
||||
@@ -343,16 +420,33 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
const units = r?.strata[mode.stratum] ?? {};
|
||||
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
|
||||
if (!Object.keys(units).length) return undefined;
|
||||
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
|
||||
const colors = ['#5C42C2', '#C24269', '#9C42C2', '#A8C243', '#2778B8', '#B19525'];
|
||||
const actual = Object.keys(r?.strata['category'] ?? {})
|
||||
.filter((code) => !['no_biopsy', 'no_data'].includes(code))
|
||||
.sort();
|
||||
const results = mode.dynamicResults
|
||||
? [
|
||||
...actual.map((code, i) => ({
|
||||
code,
|
||||
label: name(code),
|
||||
color: colors[i % colors.length],
|
||||
})),
|
||||
...mode.results,
|
||||
]
|
||||
: mode.results;
|
||||
const malignancy = mode.malignancyMeasure ? of(mode.malignancyMeasure) : r;
|
||||
const hasMalignancy = !!malignancy?.strata[`${mode.stratum}-category`];
|
||||
const malignancyCells = malignancy?.strata[`${mode.stratum}-category`] ?? {};
|
||||
const grades = ['benign', 'in_situ', 'invasive'];
|
||||
return {
|
||||
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'],
|
||||
legend: mode.results.map(({ label, color }) => ({ label, color })),
|
||||
head: ['Pacientes', ...results.map((x) => x.label), '% maligno'],
|
||||
legend: results.map(({ label, color }) => ({ label, color })),
|
||||
rows: mode.rows.map(({ code, label }) => {
|
||||
const n = size(units[code]);
|
||||
const by = mode.results.map((x) => size(cells[`${code}|${x.code}`]));
|
||||
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0);
|
||||
const bad = by.reduce(
|
||||
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0),
|
||||
const by = results.map((x) => size(cells[`${code}|${x.code}`]));
|
||||
const den = grades.reduce((t, grade) => t + size(malignancyCells[`${code}|${grade}`]), 0);
|
||||
const bad = mode.malignant.reduce(
|
||||
(t, grade) => t + size(malignancyCells[`${code}|${grade}`]),
|
||||
0,
|
||||
);
|
||||
return {
|
||||
@@ -360,7 +454,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
width: 100,
|
||||
marks: [],
|
||||
none: n ? undefined : 'Sin pacientes en el periodo',
|
||||
segments: mode.results.map((x, i) => ({
|
||||
segments: results.map((x, i) => ({
|
||||
width: n ? (100 * by[i]) / n : 0,
|
||||
color: x.color,
|
||||
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
|
||||
@@ -369,11 +463,13 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
`${n}`,
|
||||
...by.map((k) => (n ? `${k}` : '—')),
|
||||
n
|
||||
? den
|
||||
? `${bad}/${den} (${pct(bad, den)})`
|
||||
: by[mode.results.findIndex((x) => x.code === 'no_data')]
|
||||
? 'Sin biopsias clasificables'
|
||||
: 'Sin biopsias'
|
||||
? !hasMalignancy
|
||||
? 'No disponible'
|
||||
: den
|
||||
? `${bad}/${den} (${pct(bad, den)})`
|
||||
: size(malignancyCells[`${code}|no_data`])
|
||||
? 'Sin biopsias clasificables'
|
||||
: 'Sin biopsias'
|
||||
: '—',
|
||||
],
|
||||
};
|
||||
@@ -385,6 +481,13 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
|
||||
}
|
||||
}
|
||||
|
||||
/** The subsequent round split by the form's last screening, drawn in place of that round's group. */
|
||||
const LAST_SCREENING: [string, string][] = [
|
||||
['within_1_year', 'Detección anterior hace un año o menos'],
|
||||
['2_years', 'Detección anterior hace dos años'],
|
||||
['3_or_more_years', 'Detección anterior hace tres años o más'],
|
||||
];
|
||||
|
||||
/** The groups of a grouped mode: each group (an age group, a follow-up status, a screening round) with
|
||||
* one independent bar per category over the group's own records. A group the report leaves out is
|
||||
* drawn empty only when the listed ones add up to every record of the period (`complete`). */
|
||||
@@ -397,7 +500,16 @@ export function grouped(
|
||||
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
|
||||
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
|
||||
if (!patients(r) || !found.length) return undefined;
|
||||
const n = (g: string, c: string) => size(cells[`${g}|${c}`]);
|
||||
const history =
|
||||
mode.stratum === 'round' ? (r?.strata['subsequent_history-category'] ?? {}) : {};
|
||||
const answers = LAST_SCREENING.map(([code]) => code);
|
||||
/** the cells that make up a group, with their category */
|
||||
const cellsOf = (g: string): [string, Record<string, number>][] =>
|
||||
Object.entries(answers.includes(g) ? history : cells)
|
||||
.filter(([k]) => k.split('|')[0] === g)
|
||||
.map(([k, c]) => [k.split('|')[1], c]);
|
||||
const n = (g: string, c: string) =>
|
||||
cellsOf(g).reduce((t, [category, cell]) => (category === c ? t + size(cell) : t), 0);
|
||||
const reconciled = reconciles(
|
||||
Object.values(cells).map((c) => c['initial-population']),
|
||||
patients(r),
|
||||
@@ -408,28 +520,53 @@ export function grouped(
|
||||
];
|
||||
const total = (g: string) =>
|
||||
mode.ofAll
|
||||
? Object.entries(cells)
|
||||
.filter(([k]) => k.split('|')[0] === g)
|
||||
.reduce((t, [, c]) => t + size(c), 0)
|
||||
? cellsOf(g).reduce((t, [, c]) => t + size(c), 0)
|
||||
: mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
|
||||
const groups: Group[] = codes.map((code) => {
|
||||
const at = codes.indexOf('subsequent');
|
||||
const drawn =
|
||||
mode.stratum === 'round' && at >= 0 && r?.strata['subsequent_history-category']
|
||||
? [...codes.slice(0, at), ...answers, ...codes.slice(at + 1)]
|
||||
: codes;
|
||||
const groups: Group[] = drawn.map((code) => {
|
||||
const den = total(code);
|
||||
return {
|
||||
code,
|
||||
label: name(code),
|
||||
label:
|
||||
LAST_SCREENING.find(([answer]) => answer === code)?.[1] ??
|
||||
(mode.stratum === 'age_group' &&
|
||||
code === '<25' &&
|
||||
['CACU_EU7', 'CACU_VPH_GENOTIPO'].includes(mode.measure)
|
||||
? '15-24'
|
||||
: name(code)),
|
||||
total: den,
|
||||
hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
|
||||
rows: mode.catalog.map((c) => {
|
||||
rows: mode.catalog.flatMap((c, index) => {
|
||||
const count = n(code, c.code);
|
||||
const percent = den ? (100 * count) / den : undefined;
|
||||
return {
|
||||
const row = {
|
||||
label: c.label,
|
||||
color: c.color,
|
||||
count,
|
||||
of: den,
|
||||
percent,
|
||||
sub: !!mode.aggregate?.codes.includes(c.code),
|
||||
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`,
|
||||
};
|
||||
if (index !== 0 || !mode.aggregate) return [row];
|
||||
const a = mode.aggregate;
|
||||
const sum = a.codes.reduce((total, key) => total + n(code, key), 0);
|
||||
const share = den ? (100 * sum) / den : undefined;
|
||||
return [
|
||||
row,
|
||||
{
|
||||
label: a.label,
|
||||
color: a.color,
|
||||
count: sum,
|
||||
of: den,
|
||||
percent: share,
|
||||
text: `${sum}/${den} · ${share === undefined ? '—' : share.toFixed(1) + ' %'}`,
|
||||
},
|
||||
];
|
||||
}),
|
||||
};
|
||||
});
|
||||
@@ -442,9 +579,7 @@ export function grouped(
|
||||
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
|
||||
: none && unclassified
|
||||
? NO_ROUND
|
||||
: unclassified && classified.some((g) => !g.total)
|
||||
? EMPTY_ROUND
|
||||
: undefined;
|
||||
: undefined;
|
||||
note = [sentence, note].filter(Boolean).join(' ') || undefined;
|
||||
}
|
||||
return { groups, note };
|
||||
@@ -459,6 +594,7 @@ function complete(
|
||||
reconciled: boolean,
|
||||
counts: (code: string) => [number, number] | undefined,
|
||||
colors: Colors = {},
|
||||
percentLabel = 'Porcentaje',
|
||||
): Bars {
|
||||
const extra = listed.filter((c) => !order.includes(c));
|
||||
const rows: Bar[] = [...order, ...extra].map((code) => {
|
||||
@@ -484,25 +620,24 @@ function complete(
|
||||
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
|
||||
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
|
||||
const none = empty.length === classified.length;
|
||||
const unclassified = counts('no_data')?.[1] ?? 0;
|
||||
return {
|
||||
head: ['n/N', '%'],
|
||||
head: ['n/N', percentLabel],
|
||||
rows,
|
||||
note: !reconciled
|
||||
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
|
||||
: none && listed.includes('no_data')
|
||||
? NO_ROUND
|
||||
: unclassified &&
|
||||
(empty.length || order.some((c) => !listed.includes(c) && c !== 'no_data'))
|
||||
? EMPTY_ROUND
|
||||
: undefined,
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function ratios(rows: [string, number, number, string?][]): Bars | undefined {
|
||||
function ratios(
|
||||
rows: [string, number, number, string?][],
|
||||
percentLabel = 'Porcentaje',
|
||||
): Bars | undefined {
|
||||
if (!rows.length) return undefined;
|
||||
return {
|
||||
head: ['n/N', '%'],
|
||||
head: ['n/N', percentLabel],
|
||||
rows: rows.map(([label, n, total, color]) => ({
|
||||
label,
|
||||
color,
|
||||
@@ -517,21 +652,29 @@ type Score = { score?: number; low?: number; high?: number };
|
||||
function medians(
|
||||
rows: { label: string; n: number; score?: Score }[],
|
||||
tint?: Tint,
|
||||
staggered?: boolean,
|
||||
): Bars | undefined {
|
||||
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
|
||||
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
|
||||
const starts = staggered
|
||||
? chainStarts(rows.map((r) => ({ median: r.score?.score })))
|
||||
: rows.map(() => 0);
|
||||
const ends = rows.map(
|
||||
(r, i) => starts[i] + Math.max(r.score?.score ?? 0, r.score?.high ?? 0),
|
||||
);
|
||||
const top = Math.max(...ends) || 1;
|
||||
const at = (v: number) => (100 * v) / top;
|
||||
return {
|
||||
head: ['Mediana', 'n', 'Q1–Q3'],
|
||||
head: ['Mediana', 'Observaciones', 'Q1–Q3'],
|
||||
markColor: tint?.mark,
|
||||
rows: rows.map(({ label, n, score: s }) => {
|
||||
rows: rows.map(({ label, n, score: s }, i) => {
|
||||
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
|
||||
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
|
||||
return {
|
||||
label,
|
||||
color: tint?.bar,
|
||||
offset: staggered ? at(starts[i]) : undefined,
|
||||
width: at(s.score),
|
||||
marks: spread.map(at),
|
||||
marks: spread.map((v) => at(starts[i] + v)),
|
||||
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -19,7 +19,9 @@ export const CYTOLOGY_COLORS: Record<string, string> = {
|
||||
'ASC-US': '#2778B8',
|
||||
LSIL: '#B19525',
|
||||
'ASC-H': '#7955B1',
|
||||
CIN2: '#E07A9C',
|
||||
HSIL: '#CE4778',
|
||||
CIN3: '#BC4163',
|
||||
CIS: '#AA394D',
|
||||
no_data: NEUTRAL,
|
||||
};
|
||||
@@ -43,7 +45,9 @@ export const HPV_COLORS: Record<string, string> = {
|
||||
export const BIOPSY_COLORS: Record<string, string> = {
|
||||
normal: '#408651',
|
||||
LSIL: '#B19525',
|
||||
CIN2: '#E07A9C',
|
||||
HSIL: '#CE4778',
|
||||
CIN3: '#BC4163',
|
||||
CIS: '#AA394D',
|
||||
carcinoma: '#8D4C79',
|
||||
cin1_plus: '#B19525',
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { HISTORY, PAGES } from './pages';
|
||||
|
||||
describe('tiempo de diagnóstico tras biopsia a tratamiento en CaMa', () => {
|
||||
it('conecta la tarjeta y el histórico con la medida', () => {
|
||||
const measure = 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO';
|
||||
expect(PAGES['cama'].kpis.some((card) => card.measure === measure)).toBe(true);
|
||||
expect(HISTORY['cama'].panels.some((panel) => panel.measure === measure)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { CamaRow } from './follow-up';
|
||||
import { camaFollowUpSheet } from './follow-up-sheet';
|
||||
|
||||
const row = (over: Partial<CamaRow> = {}): CamaRow =>
|
||||
({
|
||||
patient: { resourceType: 'Patient', id: 'abcdefghijklmnop' },
|
||||
status: 'pending_biopsy',
|
||||
priority: 'high',
|
||||
ageGroup: '50-59',
|
||||
mammogram: { date: '2026-10-26', birads: '4A' },
|
||||
...over,
|
||||
}) as CamaRow;
|
||||
const priority = (c: string) => ({ high: 'Alta' })[c as 'high'] ?? c;
|
||||
|
||||
// Each test fails if the list file invented a result or lost the query it answers.
|
||||
describe('CaMa follow-up list as a file', () => {
|
||||
it('has CaMa columns, the query and the count', () => {
|
||||
const sheet = camaFollowUpSheet([row()], [['Búsqueda', 'Ninguna']], priority);
|
||||
expect(sheet.head).toEqual([
|
||||
'Paciente', 'CURP', 'Grupo de edad', 'Última mastografía (BI-RADS)', 'Fecha de la mastografía',
|
||||
'Última biopsia', 'Fecha de reporte de la biopsia', 'Estatus de seguimiento', 'Prioridad',
|
||||
]);
|
||||
expect(sheet.query).toEqual([['Búsqueda', 'Ninguna'], ['Registros', '1']]);
|
||||
expect(sheet.head.join()).not.toMatch(/LIEAG|VPH|Cáncer|Etapas/);
|
||||
});
|
||||
it('says what is missing: no biopsy, no BI-RADS, no CURP, no priority, never a made-up value', () => {
|
||||
const [r] = camaFollowUpSheet(
|
||||
[row({ mammogram: { date: '' }, priority: '' })],
|
||||
[],
|
||||
priority,
|
||||
).rows;
|
||||
expect(r.slice(0, 2)).toEqual(['abcdefghij', 'No disponible']);
|
||||
expect(r.slice(3, 7)).toEqual(['Sin dato', 'No disponible', 'No disponible', 'No disponible']);
|
||||
expect(r[8]).toBe('No disponible');
|
||||
});
|
||||
it('shows a biopsy with its date, or no grade when it has none', () => {
|
||||
const rows = camaFollowUpSheet(
|
||||
[row({ biopsy: { date: '2026-11-30', histology: 'benign' } }), row({ biopsy: { date: '2026-11-01' } })],
|
||||
[],
|
||||
priority,
|
||||
).rows;
|
||||
expect(rows[0].slice(5, 7)).toEqual(['Benigno', '2026-11-30']);
|
||||
expect(rows[1].slice(5, 7)).toEqual(['Sin resultado', '2026-11-01']);
|
||||
expect(rows[0][8]).toBe('Alta');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { durationMax, durationRows } from './durations';
|
||||
import { chainStarts, durationMax, durationRows } from './durations';
|
||||
import { Reading } from './measures';
|
||||
|
||||
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
|
||||
@@ -53,3 +53,10 @@ describe('durationRows', () => {
|
||||
expect(durationMax([])).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('chainStarts', () => {
|
||||
it('starts each step where the one it follows ends, two of them sharing a start', () => {
|
||||
expect(chainStarts([{ median: 4 }, { median: 6 }, { median: 2, after: 0 }])).toEqual([0, 4, 4]);
|
||||
expect(chainStarts([{ median: 4 }, {}, { median: 2 }])).toEqual([0, 4, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,8 @@ import { Reading } from './measures';
|
||||
export interface RouteStep {
|
||||
label: string;
|
||||
measure?: string;
|
||||
/** the step (its position) this one starts after; the previous one by default */
|
||||
after?: number;
|
||||
}
|
||||
|
||||
/** One row of a duration table: the median days, how many measurements and the quartiles.
|
||||
@@ -17,6 +19,25 @@ export interface DurationRow {
|
||||
observations?: number;
|
||||
low?: number;
|
||||
high?: number;
|
||||
after?: number;
|
||||
/** where its bar starts, in days, when the steps are chained */
|
||||
start?: number;
|
||||
}
|
||||
|
||||
/** Where each step's bar starts when drawn as a schematic sequence (a Gantt chart): where the
|
||||
* step it follows ends. A step without a median moves nothing after it. */
|
||||
export function chainStarts(steps: { median?: number; after?: number }[]): number[] {
|
||||
const starts: number[] = [];
|
||||
steps.forEach(({ after }, i) => {
|
||||
const j = after ?? i - 1;
|
||||
starts.push(j < 0 ? 0 : starts[j] + (steps[j].median ?? 0));
|
||||
});
|
||||
return starts;
|
||||
}
|
||||
|
||||
export function chained(rows: DurationRow[]): DurationRow[] {
|
||||
const starts = chainStarts(rows);
|
||||
return rows.map((row, i) => ({ ...row, start: starts[i] }));
|
||||
}
|
||||
|
||||
/** The rows of a route in one reading; every step keeps its row. `published` says which
|
||||
@@ -26,12 +47,13 @@ export function durationRows(
|
||||
read: (measure: string) => Reading | undefined,
|
||||
published: (measure: string) => boolean,
|
||||
): DurationRow[] {
|
||||
return steps.map(({ label, measure }) => {
|
||||
if (!measure || !published(measure)) return { label, status: 'unpublished' };
|
||||
return steps.map(({ label, measure, after }) => {
|
||||
if (!measure || !published(measure)) return { label, after, status: 'unpublished' };
|
||||
const r = read(measure);
|
||||
if (r?.score === undefined) return { label, status: 'empty' };
|
||||
if (r?.score === undefined) return { label, after, status: 'empty' };
|
||||
return {
|
||||
label,
|
||||
after,
|
||||
status: 'value',
|
||||
median: r.score,
|
||||
observations: r.populations['measure-observation'],
|
||||
@@ -41,6 +63,6 @@ export function durationRows(
|
||||
});
|
||||
}
|
||||
|
||||
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
|
||||
/** The scale of a table of durations, from zero: the farthest median or third quartile shown. */
|
||||
export const durationMax = (rows: DurationRow[]): number =>
|
||||
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
|
||||
Math.max(0, ...rows.map((r) => (r.start ?? 0) + Math.max(r.median ?? 0, r.high ?? 0)));
|
||||
|
||||
@@ -125,7 +125,7 @@ export function scenarioBars(
|
||||
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
|
||||
);
|
||||
const y = order
|
||||
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
|
||||
? scenarios.map((s, i) => `${label(s)}<br>${options.ofAll ? 'Reportes' : 'Pacientes'}: ${totals[i]}`)
|
||||
: scenarios.map(label);
|
||||
return {
|
||||
data: catalog.categories.map((c) => ({
|
||||
@@ -304,9 +304,11 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
// an empty slice says nothing (its label would sit on its neighbours')
|
||||
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
|
||||
texttemplate: values.map((v) =>
|
||||
v ? `%{label}<br>%{percent} del total de ${center}` : '',
|
||||
),
|
||||
textposition: 'outside',
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`,
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Sheet } from '../export';
|
||||
import { STATES } from '../paciente/stages';
|
||||
import type { Row } from './follow-up';
|
||||
import type { CamaRow, Row } from './follow-up';
|
||||
import { name } from './measures';
|
||||
|
||||
const NONE = 'No disponible';
|
||||
@@ -50,3 +50,40 @@ export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
const CAMA_HEAD = [
|
||||
'Paciente',
|
||||
'CURP',
|
||||
'Grupo de edad',
|
||||
'Última mastografía (BI-RADS)',
|
||||
'Fecha de la mastografía',
|
||||
'Última biopsia',
|
||||
'Fecha de reporte de la biopsia',
|
||||
'Estatus de seguimiento',
|
||||
'Prioridad',
|
||||
];
|
||||
|
||||
/** CaMa's follow-up list as a table to save: what the page shows, a missing value said as such and
|
||||
* never filled in. */
|
||||
export function camaFollowUpSheet(
|
||||
rows: CamaRow[],
|
||||
query: [string, string][],
|
||||
priority: (code: string) => string,
|
||||
): Sheet {
|
||||
return {
|
||||
title: 'Resultados de seguimiento de cáncer de mama',
|
||||
query: [...query, ['Registros', `${rows.length}`]],
|
||||
head: CAMA_HEAD,
|
||||
rows: rows.map((r) => [
|
||||
r.name ?? r.patient.id!.slice(0, 10),
|
||||
r.curp ?? NONE,
|
||||
r.ageGroup || NONE,
|
||||
(r.mammogram.birads && name(r.mammogram.birads)) || 'Sin dato',
|
||||
r.mammogram.date || NONE,
|
||||
r.biopsy ? name(r.biopsy.histology ?? '') || 'Sin resultado' : NONE,
|
||||
r.biopsy?.date ?? NONE,
|
||||
name(r.status),
|
||||
priority(r.priority) || NONE,
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RiskAssessment } from 'fhir/r4';
|
||||
import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
|
||||
import { periods } from './measures';
|
||||
import { historyPeriods, periods } from './measures';
|
||||
|
||||
describe('follow-up list', () => {
|
||||
it('starts the window the day after the same day months before (core.follow_up)', () => {
|
||||
@@ -36,6 +36,16 @@ describe('follow-up list', () => {
|
||||
expect(currentRisk(risks, 'cin2', 3)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ends history at the selected complete period for months and semesters', () => {
|
||||
const monthly = historyPeriods('month', '2025-03');
|
||||
expect(monthly.slice(-3)).toEqual(['2025-01', '2025-02', '2025-03']);
|
||||
expect(monthly).toHaveLength(72);
|
||||
const firstSemester = historyPeriods('semester', '2025-S1');
|
||||
expect(firstSemester.slice(-3)).toEqual(['2024-S1', '2024-S2', '2025-S1']);
|
||||
const secondSemester = historyPeriods('semester', '2025-S2');
|
||||
expect(secondSemester.slice(-2)).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
|
||||
it('lists periods most recent first', () => {
|
||||
expect(periods('semester', 1, new Date(2026, 10, 25))).toEqual(['2026-S2', '2026-S1']);
|
||||
expect(periods('month', 1, new Date(2026, 1, 3)).slice(0, 3)).toEqual([
|
||||
|
||||
@@ -36,28 +36,28 @@ import { Loading } from '../loading';
|
||||
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
|
||||
} @else {
|
||||
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
|
||||
<mat-tab label="Resumen">
|
||||
<mat-tab label="Indicadores">
|
||||
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
|
||||
</mat-tab>
|
||||
<mat-tab label="Histórico">
|
||||
<mat-tab label="Trazabilidad">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
@if (domain() === 'cacu') {
|
||||
<mat-tab label="Seguimiento">
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-riesgos [domain]="domain()" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'tea') {
|
||||
<mat-tab label="Seguimiento">
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-riesgos-tea [domain]="domain()" />
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'cama') {
|
||||
<mat-tab label="Seguimiento">
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-seguimiento [domain]="domain()" />
|
||||
</ng-template>
|
||||
|
||||
@@ -19,8 +19,8 @@ export const LAYOUTS: Record<string, Layout> = {
|
||||
],
|
||||
route: [
|
||||
{
|
||||
label: 'Días de toma de citología a resultado',
|
||||
step: 'Días de toma de citología a resultado',
|
||||
label: 'Resultado de citología',
|
||||
step: 'Toma a resultado de citología',
|
||||
fromSample: 'CACU_EU_TIEMPO_REPORTE',
|
||||
fromStep: 'CACU_EU_TIEMPO_REPORTE',
|
||||
},
|
||||
@@ -51,7 +51,6 @@ export const LAYOUTS: Record<string, Layout> = {
|
||||
'CAMA_EU38A',
|
||||
'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
'CAMA_CONFIRMACION_BIRADS45',
|
||||
'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
|
||||
],
|
||||
route: [
|
||||
{
|
||||
|
||||
@@ -23,6 +23,13 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Historical periods ending in the selected month or semester, oldest first. */
|
||||
export function historyPeriods(type: PeriodType, selected: string): string[] {
|
||||
const [year, part] = selected.split('-');
|
||||
const month = type === 'semester' ? (part === 'S1' ? 0 : 6) : Number(part) - 1;
|
||||
return periods(type, 6, new Date(Number(year), month, 1)).reverse();
|
||||
}
|
||||
|
||||
export function periodLabel(period: string): string {
|
||||
const [year, part] = period.split('-');
|
||||
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
|
||||
@@ -103,9 +110,12 @@ export const LABELS: Record<string, string> = {
|
||||
NILM: 'Normal (NILM)',
|
||||
LSIL: 'LIEBG',
|
||||
HSIL: 'LIEAG',
|
||||
CIN2: 'CIN 2',
|
||||
CIN3: 'CIN 3',
|
||||
normal: 'Normal',
|
||||
carcinoma: 'Carcinoma',
|
||||
no_data: 'Sin dato',
|
||||
'<25': '<25 años (sin límite inferior)',
|
||||
no_biopsy: 'Sin biopsia',
|
||||
pre_colposcopy: 'Pre colposcopia',
|
||||
post_colposcopy: 'Post colposcopia',
|
||||
@@ -134,7 +144,7 @@ export const LABELS: Record<string, string> = {
|
||||
bad: 'Malo',
|
||||
not_analyzed: 'Sin analizar',
|
||||
initial: 'Detección inicial',
|
||||
subsequent: 'Detección subsecuente',
|
||||
subsequent: 'Con detección anterior',
|
||||
positive: 'Positivo',
|
||||
negative: 'Negativo',
|
||||
hpv_16: 'VPH 16',
|
||||
@@ -153,6 +163,21 @@ export const LABELS: Record<string, string> = {
|
||||
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
|
||||
),
|
||||
};
|
||||
/** Breast histologic types (ICD-O-3 morphology); a code not listed is shown as it is. */
|
||||
const HISTOLOGIC_TYPES: Record<string, string> = {
|
||||
'8500/2': 'Carcinoma ductal in situ',
|
||||
'8500/3': 'Carcinoma ductal infiltrante',
|
||||
'8520/2': 'Carcinoma lobulillar in situ',
|
||||
'8520/3': 'Carcinoma lobulillar infiltrante',
|
||||
'8522/3': 'Carcinoma ductal y lobulillar infiltrante',
|
||||
'8480/3': 'Adenocarcinoma mucinoso',
|
||||
'8211/3': 'Carcinoma tubular',
|
||||
'8510/3': 'Carcinoma medular',
|
||||
'8530/3': 'Carcinoma inflamatorio',
|
||||
'8540/3': 'Enfermedad de Paget de la mama',
|
||||
'9010/0': 'Fibroadenoma',
|
||||
'9016/0': 'Fibroadenoma gigante',
|
||||
};
|
||||
/** A follow-up priority's label. */
|
||||
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
|
||||
export const STRATA: Record<string, string> = {
|
||||
@@ -165,11 +190,11 @@ export const STRATA: Record<string, string> = {
|
||||
cytology: 'Citología previa',
|
||||
hpv: 'VPH de la citología previa',
|
||||
level: 'Histología confirmada',
|
||||
round: 'Tamizaje inicial o subsecuente',
|
||||
round: 'Detección inicial o anterior',
|
||||
hpv_16: 'VPH 16',
|
||||
hpv_18: 'VPH 18',
|
||||
};
|
||||
export const name = (value: string) => LABELS[value] ?? value;
|
||||
export const name = (value: string) => LABELS[value] ?? HISTOLOGIC_TYPES[value] ?? value;
|
||||
|
||||
export function formatScore(measure: Measure, r: Reading | undefined): string {
|
||||
if (!r || r.score === undefined) return 'Sin dato';
|
||||
|
||||
@@ -8,13 +8,13 @@ import {
|
||||
PPV_DONUT,
|
||||
PPV_LEVEL_COLORS,
|
||||
QUARTILE,
|
||||
REQUEST_COLORS,
|
||||
ROUND_COLORS,
|
||||
} from './cacu-palette';
|
||||
import type { Catalog, Page, ReadingsCard } from './pages';
|
||||
|
||||
const OLIVE = '#A8C243';
|
||||
const ROSE = '#C24269';
|
||||
const ABNORMAL = { label: 'Anormal', color: ROSE, codes: ['ASC-US', 'LSIL', 'ASC-H', 'HSIL', 'CIS', 'carcinoma'] };
|
||||
|
||||
/** Bethesda results as the old app grouped and coloured them. */
|
||||
const CYTOLOGY: Catalog = {
|
||||
@@ -29,6 +29,12 @@ const CYTOLOGY: Catalog = {
|
||||
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
|
||||
{ code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
|
||||
{ code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
|
||||
{
|
||||
code: 'carcinoma',
|
||||
label: 'Carcinoma epidermoide invasor',
|
||||
color: BIOPSY_COLORS['carcinoma'],
|
||||
group: 'abnormal',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -41,7 +47,9 @@ const BIOPSY: Catalog = {
|
||||
categories: [
|
||||
{ code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
|
||||
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], group: 'low' },
|
||||
{ code: 'CIN2', label: 'CIN 2', color: BIOPSY_COLORS['CIN2'], group: 'high' },
|
||||
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: BIOPSY_COLORS['HSIL'], group: 'high' },
|
||||
{ code: 'CIN3', label: 'CIN 3', color: BIOPSY_COLORS['CIN3'], group: 'high' },
|
||||
{ code: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
|
||||
{
|
||||
code: 'carcinoma',
|
||||
@@ -59,15 +67,8 @@ const HPV = [
|
||||
{ code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
|
||||
{ code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] },
|
||||
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
|
||||
{ code: 'positive_other', label: 'Positivo', color: HPV_COLORS['positive_other'] },
|
||||
{ code: 'positive_other', label: 'Positivo sin genotipo', color: HPV_COLORS['positive_other'] },
|
||||
];
|
||||
const REQUESTS = [
|
||||
{ code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] },
|
||||
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: REQUEST_COLORS['below_high_grade'] },
|
||||
{ code: 'pending', label: 'Pendiente', color: REQUEST_COLORS['pending'] },
|
||||
{ code: 'no_grade', label: 'Sin grado', color: REQUEST_COLORS['no_grade'] },
|
||||
];
|
||||
|
||||
/** The screening route's bars: a median, and the marks of its quartiles. */
|
||||
const TINT = { bar: DURATION, mark: QUARTILE };
|
||||
|
||||
@@ -75,16 +76,14 @@ const TINT = { bar: DURATION, mark: QUARTILE };
|
||||
const ROUNDS = ['initial', 'subsequent', 'no_data'];
|
||||
const ROUND_CAPTION =
|
||||
'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección inicial (primera vez en la vida), ' +
|
||||
'subsecuente (detección previa registrada, o ya con colposcopía o tratamiento) o «Sin dato». ' +
|
||||
'con detección anterior (registrada, o ya con colposcopía o tratamiento) o «Sin dato». ' +
|
||||
'Un grupo sin pacientes se muestra en cero; sin porcentaje.';
|
||||
|
||||
/** The views the cytology and HPV-by-genotype cards share (one selector for both). */
|
||||
const GENERAL = 'General';
|
||||
const BY_AGE = 'Por grupo de edad';
|
||||
const BY_STATUS = 'Por estatus de seguimiento';
|
||||
const BY_ROUND = 'Por detección inicial y subsecuente';
|
||||
const BY_ROUND = 'Por detección inicial y anterior';
|
||||
const AGE_GROUPS = ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'];
|
||||
const STATUSES = ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case', 'no_data'];
|
||||
/** HPV categories the cards do not draw (their reports stay in the total and the percentages). */
|
||||
const HPV_HIDDEN = {
|
||||
codes: ['positive_incomplete', 'inconsistent', 'no_result'],
|
||||
@@ -96,29 +95,38 @@ const groupViews = (
|
||||
measure: string,
|
||||
catalog: { code: string; label: string; color: string }[],
|
||||
unit: string,
|
||||
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {},
|
||||
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string }; aggregate?: typeof ABNORMAL } = {},
|
||||
): Mode[] =>
|
||||
[
|
||||
{ label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS },
|
||||
{ label: BY_STATUS, stratum: 'follow_up_status', order: STATUSES },
|
||||
{ label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
|
||||
].map((v) => ({
|
||||
kind: 'grouped' as const,
|
||||
measure,
|
||||
catalog,
|
||||
unit,
|
||||
caption: measure === 'CACU_VPH_GENOTIPO'
|
||||
? 'Porcentaje de reportes de VPH del grupo por genotipo.'
|
||||
: 'Porcentaje de pacientes del grupo por resultado citológico.',
|
||||
...v,
|
||||
...more,
|
||||
}));
|
||||
|
||||
/** A PPV's card: the whole, and by each of its stratifiers. */
|
||||
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
|
||||
const ppv = (
|
||||
measure: string,
|
||||
title: string,
|
||||
note: string,
|
||||
percentLabel: string,
|
||||
...more: Mode[]
|
||||
): ReadingsCard => ({
|
||||
kind: 'readings',
|
||||
title,
|
||||
headline: measure,
|
||||
footnote: true,
|
||||
note: `${note} Confirma la histología LIEBG o mayor.`,
|
||||
modes: [
|
||||
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT },
|
||||
{ kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT, percentLabel },
|
||||
{
|
||||
kind: 'shares',
|
||||
label: 'Citología previa',
|
||||
@@ -127,6 +135,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
|
||||
stratum: 'cytology',
|
||||
colors: PPV_CYTOLOGY_COLORS,
|
||||
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
|
||||
percentLabel: 'Porcentaje de pacientes con esta citología previa',
|
||||
},
|
||||
{
|
||||
kind: 'shares',
|
||||
@@ -136,6 +145,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
|
||||
stratum: 'hpv',
|
||||
colors: HPV_COLORS,
|
||||
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
|
||||
percentLabel: 'Porcentaje de pacientes de cada grupo de VPH previo',
|
||||
},
|
||||
{
|
||||
kind: 'shares',
|
||||
@@ -144,16 +154,18 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
|
||||
stratum: 'level',
|
||||
colors: PPV_LEVEL_COLORS,
|
||||
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
|
||||
percentLabel: 'Porcentaje de pacientes de cada nivel de histología',
|
||||
},
|
||||
{
|
||||
kind: 'shares',
|
||||
label: 'Por detección inicial y subsecuente',
|
||||
label: 'Por detección inicial y anterior',
|
||||
caption: ROUND_CAPTION,
|
||||
measure,
|
||||
stratum: 'round',
|
||||
colors: ROUND_COLORS,
|
||||
order: ROUNDS,
|
||||
complete: true,
|
||||
percentLabel: 'Porcentaje de pacientes de cada ronda',
|
||||
},
|
||||
...more,
|
||||
],
|
||||
@@ -174,34 +186,29 @@ export const CACU: Page = {
|
||||
},
|
||||
{
|
||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||
title: 'Días de toma de citología a resultado',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
title: 'Días de tamizaje a primer diagnóstico',
|
||||
title: 'Tiempo desde la toma de muestra al resultado',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||
title: 'Días de tamizaje a diagnóstico tras biopsia',
|
||||
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
title: 'Días de tamizaje a tratamiento',
|
||||
title: 'Tiempo de tamizaje a tratamiento',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
title: 'Días de diagnóstico a tratamiento',
|
||||
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
...CACU_DAYS,
|
||||
},
|
||||
],
|
||||
opportunity: [
|
||||
{
|
||||
kind: 'readings',
|
||||
title: 'Días de la ruta del tamizaje',
|
||||
title: 'Tiempos de tamizaje',
|
||||
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
|
||||
modes: [
|
||||
{
|
||||
@@ -209,7 +216,7 @@ export const CACU: Page = {
|
||||
tint: TINT,
|
||||
label: 'Acumulado desde la toma',
|
||||
steps: [
|
||||
{ label: 'Días de toma de citología a resultado', measure: 'CACU_EU_TIEMPO_REPORTE' },
|
||||
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
|
||||
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
|
||||
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
|
||||
{
|
||||
@@ -221,11 +228,13 @@ export const CACU: Page = {
|
||||
{
|
||||
kind: 'days',
|
||||
tint: TINT,
|
||||
label: 'Por pasos',
|
||||
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
|
||||
label: 'Por ventana de tiempo',
|
||||
staggered: true,
|
||||
caption:
|
||||
'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus propias pacientes: las medianas no se suman.',
|
||||
steps: [
|
||||
{
|
||||
label: 'Días de toma de citología a resultado',
|
||||
label: 'Toma a resultado de citología',
|
||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||
},
|
||||
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
|
||||
@@ -236,7 +245,7 @@ export const CACU: Page = {
|
||||
{
|
||||
kind: 'days',
|
||||
tint: TINT,
|
||||
label: 'Primer diagnóstico',
|
||||
label: 'Diagnóstico precolposcópico',
|
||||
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
|
||||
},
|
||||
{
|
||||
@@ -258,7 +267,7 @@ export const CACU: Page = {
|
||||
kind: 'columns',
|
||||
title: 'Resultados de citología, VPH y biopsia',
|
||||
viewsLabel: 'Lectura de la distribución citológica y del VPH por genotipo',
|
||||
views: [GENERAL, BY_AGE, BY_STATUS, BY_ROUND],
|
||||
views: [GENERAL, BY_AGE, BY_ROUND],
|
||||
sections: [
|
||||
{
|
||||
kind: 'readings',
|
||||
@@ -266,8 +275,16 @@ export const CACU: Page = {
|
||||
title: 'Distribución de resultados citológicos',
|
||||
note: 'Pacientes, por su última muestra válida del periodo.',
|
||||
modes: [
|
||||
{ kind: 'counts', label: GENERAL, measure: 'CACU_EU7', catalog: CYTOLOGY.categories },
|
||||
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'),
|
||||
{
|
||||
kind: 'counts',
|
||||
label: GENERAL,
|
||||
measure: 'CACU_EU7',
|
||||
catalog: CYTOLOGY.categories,
|
||||
aggregate: ABNORMAL,
|
||||
unit: 'Pacientes',
|
||||
percentLabel: 'Porcentaje de pacientes',
|
||||
},
|
||||
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes', { aggregate: ABNORMAL, ofAll: true }),
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -281,6 +298,8 @@ export const CACU: Page = {
|
||||
label: GENERAL,
|
||||
measure: 'CACU_VPH_GENOTIPO',
|
||||
catalog: HPV,
|
||||
unit: 'Reportes',
|
||||
percentLabel: 'Porcentaje de reportes de VPH',
|
||||
hidden: HPV_HIDDEN,
|
||||
},
|
||||
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
|
||||
@@ -299,6 +318,8 @@ export const CACU: Page = {
|
||||
label: 'General',
|
||||
measure: 'CACU_BIOPSIA_RESULTADOS',
|
||||
catalog: BIOPSY.categories,
|
||||
unit: 'Reportes',
|
||||
percentLabel: 'Porcentaje de reportes de biopsia',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -314,6 +335,7 @@ export const CACU: Page = {
|
||||
'CACU_VPP_COLPOSCOPIA',
|
||||
'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
|
||||
'Porcentaje de pacientes',
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -322,13 +344,7 @@ export const CACU: Page = {
|
||||
'CACU_VPP_BIOPSIA',
|
||||
'Tasa de confirmación histopatológica de referencia a biopsia',
|
||||
'Pacientes con biopsia reportada, por fecha de solicitud.',
|
||||
{
|
||||
kind: 'counts',
|
||||
label: 'Solicitudes',
|
||||
caption: 'Solicitudes de biopsia registradas, según su resultado.',
|
||||
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
|
||||
catalog: REQUESTS,
|
||||
},
|
||||
'Porcentaje de biopsias reportadas',
|
||||
),
|
||||
},
|
||||
],
|
||||
|
||||
@@ -26,6 +26,8 @@ export interface ReadingsCard {
|
||||
kind: 'readings';
|
||||
title: string;
|
||||
headline?: string;
|
||||
/** say the headline under the figure instead of above it */
|
||||
footnote?: boolean;
|
||||
/** what the headline proportion counts, in the plural (default: pacientes) */
|
||||
unit?: string;
|
||||
note?: string;
|
||||
@@ -122,7 +124,6 @@ const CAMA_DAYS = {
|
||||
value: '{median} días (mediana)',
|
||||
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
|
||||
};
|
||||
const PENDING = 'Indicador no publicado en el catálogo institucional.';
|
||||
|
||||
/** BI-RADS 4 to 6 as the old app named and coloured them. */
|
||||
const BIRADS: Catalog = {
|
||||
@@ -248,6 +249,7 @@ export const PAGES: Record<string, Page> = {
|
||||
},
|
||||
cama: {
|
||||
anchor: 'CAMA_BIRADS456_PACIENTE',
|
||||
// every single-number card, together at the start, in the order asked for
|
||||
kpis: [
|
||||
{
|
||||
measure: 'CAMA_BIRADS456_PACIENTE',
|
||||
@@ -255,37 +257,41 @@ export const PAGES: Record<string, Page> = {
|
||||
value: '{n} pacientes',
|
||||
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
|
||||
title: 'Tasa de detección histopatológica',
|
||||
value: '{pct} %',
|
||||
note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_EU38A',
|
||||
title: 'Días de toma de mastografía a interpretación radiológica',
|
||||
title: 'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
title: 'Días de interpretación radiológica a diagnóstico',
|
||||
title: 'Tiempo de interpretación radiológica a diagnóstico',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
title: 'Días de diagnóstico a tratamiento',
|
||||
value: 'Indicador no disponible',
|
||||
note: PENDING,
|
||||
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
|
||||
title: 'Tiempo de interpretación radiológica a resultado de biopsia',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
],
|
||||
opportunity: [
|
||||
{
|
||||
kind: 'route',
|
||||
title: 'Días de tamizaje a diagnóstico',
|
||||
title: 'Tiempo de tamizaje a diagnóstico y tratamiento',
|
||||
// from the mammography: only the two measures that start at it
|
||||
sample: [
|
||||
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
|
||||
{
|
||||
label: 'Diagnóstico (días de tamizaje a diagnóstico)',
|
||||
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
},
|
||||
],
|
||||
@@ -295,11 +301,16 @@ export const PAGES: Record<string, Page> = {
|
||||
label: 'Interpretación radiológica a diagnóstico',
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
},
|
||||
{
|
||||
label: 'Diagnóstico tras biopsia a tratamiento',
|
||||
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
},
|
||||
{
|
||||
label: 'Interpretación radiológica a resultado de biopsia',
|
||||
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
|
||||
// from the interpretation, as the diagnosis: not after it
|
||||
after: 0,
|
||||
},
|
||||
{ label: 'Diagnóstico a tratamiento' },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -325,28 +336,31 @@ export const PAGES: Record<string, Page> = {
|
||||
},
|
||||
{
|
||||
kind: 'readings',
|
||||
title: 'Resultado histopatológico por categoría BI-RADS',
|
||||
note: 'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave reportada, por fecha del examen. El porcentaje maligno se calcula solo sobre las pacientes con biopsia con grado.',
|
||||
title: 'Tipo histológico por categoría BI-RADS',
|
||||
note: 'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave reportada, por fecha del examen. Los tipos siguen la clasificación CIE-O-3; «Sin dato» incluye tipos ausentes o con vínculo ambiguo. El porcentaje maligno conserva la clasificación de la biopsia y su denominador de pacientes con clasificación conocida.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'outcomes',
|
||||
label: 'Por categoría BI-RADS',
|
||||
heading: 'Resultados por paciente',
|
||||
caption: NO_BIOPSY_MEANS,
|
||||
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
|
||||
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
|
||||
stratum: 'birads',
|
||||
rows: BIRADS.categories,
|
||||
results: [...BIOPSY_GRADES, ...NO_RESULT],
|
||||
results: NO_RESULT,
|
||||
malignant: ['in_situ', 'invasive'],
|
||||
dynamicResults: true,
|
||||
malignancyMeasure: 'CAMA_HISTOPATOLOGIA_BIRADS',
|
||||
},
|
||||
{
|
||||
kind: 'counts',
|
||||
label: 'Todas las categorías',
|
||||
heading: 'Resultados por paciente',
|
||||
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
|
||||
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
|
||||
catalog: [...BIOPSY_GRADES, ...NO_RESULT],
|
||||
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
|
||||
catalog: [],
|
||||
unit: 'Pacientes',
|
||||
percent: true,
|
||||
percentLabel: 'Porcentaje de pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -356,21 +370,22 @@ export const PAGES: Record<string, Page> = {
|
||||
card: true,
|
||||
choices: [
|
||||
{
|
||||
label: 'Resultado de biopsias',
|
||||
label: 'Tipos histológicos',
|
||||
section: {
|
||||
kind: 'readings',
|
||||
title: 'Resultado de biopsias',
|
||||
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
|
||||
title: 'Tipos histológicos',
|
||||
unit: 'biopsias',
|
||||
note: 'Biopsias con resultado reportado, por fecha del reporte (no son pacientes ni mastografías). La tasa divide los carcinomas (in situ o invasor) entre biopsias con grado conocido. Los porcentajes de la distribución incluyen todas las biopsias reportadas, también «Sin dato» (sin grado), por lo que sus denominadores pueden ser distintos.',
|
||||
note: 'Biopsias por fecha de reporte, agrupadas por tipo histológico (CIE-O-3). «Sin dato» incluye los tipos ausentes y los que no pueden vincularse de forma inequívoca. La tasa de detección conserva su cálculo de carcinomas entre biopsias con clasificación conocida; su denominador puede ser distinto.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'counts',
|
||||
label: 'Biopsias reportadas',
|
||||
heading: 'Biopsias reportadas',
|
||||
measure: 'CAMA_BIOPSIAS',
|
||||
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
|
||||
label: 'Tipos histológicos',
|
||||
heading: 'Tipo histológico',
|
||||
measure: 'CAMA_TIPO_HISTOLOGICO',
|
||||
catalog: [],
|
||||
unit: 'Biopsias',
|
||||
percent: true,
|
||||
percentLabel: 'Porcentaje de reportes de biopsia',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -382,7 +397,7 @@ export const PAGES: Record<string, Page> = {
|
||||
title: 'Mastografías con biopsia',
|
||||
headline: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
unit: 'mastografías',
|
||||
note: 'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de la biopsia; no es equivalente a la tasa de detección.',
|
||||
note: 'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de la biopsia.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'split',
|
||||
@@ -391,6 +406,8 @@ export const PAGES: Record<string, Page> = {
|
||||
yes: 'Con reporte de biopsia',
|
||||
no: 'Sin reporte de biopsia',
|
||||
colors: [INSTITUTIONAL, NEUTRAL],
|
||||
unit: 'Mastografías',
|
||||
percentLabel: 'Porcentaje de mastografías',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -468,7 +485,9 @@ export const HISTORY: Record<string, History> = {
|
||||
[
|
||||
['normal', 'Normal', '#9DBFE3'],
|
||||
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
|
||||
['CIN2', 'CIN 2', '#E07A9C'],
|
||||
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
|
||||
['CIN3', 'CIN 3', '#A8325A'],
|
||||
['CIS', 'Carcinoma in situ', '#9C42C2'],
|
||||
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
|
||||
['no_biopsy', 'Sin biopsia aún', GREY],
|
||||
@@ -476,27 +495,27 @@ export const HISTORY: Record<string, History> = {
|
||||
],
|
||||
),
|
||||
{
|
||||
title: 'Días de toma de citología a resultado',
|
||||
title: 'Días de la toma de la citología a su resultado',
|
||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de tamizaje a primer diagnóstico',
|
||||
title: 'Tiempo de tamizaje a primer diagnóstico',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de tamizaje a diagnóstico tras biopsia',
|
||||
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de tamizaje a tratamiento',
|
||||
title: 'Tiempo de tamizaje a tratamiento',
|
||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de diagnóstico a tratamiento',
|
||||
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
@@ -511,6 +530,7 @@ export const HISTORY: Record<string, History> = {
|
||||
cama: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{ title: 'Tiempo de diagnóstico tras biopsia a tratamiento', measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO', kind: 'median' },
|
||||
{
|
||||
title: 'Días de la toma de la mastografía a su resultado',
|
||||
measure: 'CAMA_EU38A',
|
||||
@@ -522,10 +542,11 @@ export const HISTORY: Record<string, History> = {
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de tamizaje a diagnóstico',
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{ title: 'Tasa de detección histopatológica', measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', kind: 'percent' },
|
||||
stack(
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_MASTOGRAFIA',
|
||||
@@ -546,7 +567,7 @@ export const HISTORY: Record<string, History> = {
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
title: 'Confirmación histopatológica',
|
||||
measure: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
kind: 'percent',
|
||||
},
|
||||
|
||||
@@ -54,13 +54,13 @@ import { Reading } from './measures';
|
||||
@for (group of g.groups; track group.code) {
|
||||
<section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label">
|
||||
<h4>
|
||||
{{ group.label }} <span class="n">n = {{ group.total }}</span>
|
||||
{{ group.label }} <span class="n">{{ countUnit() }}: {{ group.total }}</span>
|
||||
@if (group.hint) {
|
||||
<span class="hint">{{ group.hint }}</span>
|
||||
}
|
||||
</h4>
|
||||
@for (row of group.rows; track row.label) {
|
||||
<div class="row" [attr.data-category]="row.label">
|
||||
<div class="row" [class.sub]="row.sub" [attr.data-category]="row.label">
|
||||
<span class="name">{{ row.label }}</span>
|
||||
<span class="track" aria-hidden="true">
|
||||
<span
|
||||
@@ -94,7 +94,7 @@ import { Reading } from './measures';
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (row of t.rows; track row.label) {
|
||||
<tr>
|
||||
<tr [class.sub]="row.sub">
|
||||
<th scope="row">
|
||||
{{ row.label }}
|
||||
@if (row.hint) {
|
||||
@@ -116,6 +116,7 @@ import { Reading } from './measures';
|
||||
} @else {
|
||||
<span
|
||||
class="bar"
|
||||
[style.margin-left.%]="row.offset"
|
||||
[style.width.%]="row.width"
|
||||
[style.background]="row.color"
|
||||
></span>
|
||||
@@ -146,8 +147,15 @@ import { Reading } from './measures';
|
||||
} @else {
|
||||
<p class="state">Sin datos en el periodo.</p>
|
||||
}
|
||||
@if (foot()) {
|
||||
<p class="state">{{ foot() }}</p>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
tr.sub th,
|
||||
.row.sub .name {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
:host {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
@@ -347,6 +355,8 @@ export class Readings {
|
||||
readonly title = input.required<string>();
|
||||
readonly headline = input('');
|
||||
readonly note = input('');
|
||||
/** a line under the figure */
|
||||
readonly foot = input('');
|
||||
/** the card around it names it already (tabs inside one card) */
|
||||
readonly hideTitle = input(false);
|
||||
readonly camaStyle = input(false);
|
||||
@@ -359,6 +369,11 @@ export class Readings {
|
||||
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
|
||||
|
||||
protected readonly chosen = signal('');
|
||||
protected readonly countUnit = computed(() => {
|
||||
const mode = this.mode();
|
||||
const unit = mode.kind === 'grouped' ? mode.unit : 'pacientes';
|
||||
return unit[0].toUpperCase() + unit.slice(1);
|
||||
});
|
||||
protected readonly mode = computed(
|
||||
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Component, input, signal } from '@angular/core';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { Loading } from '../loading';
|
||||
import { DurationRow, durationMax } from './durations';
|
||||
import { chained, DurationRow, durationMax } from './durations';
|
||||
|
||||
/** A screening route as one compact card: a bar per step with its median, its observations
|
||||
* and its quartiles, read step by step or cumulatively from the sample. A step that is not
|
||||
@@ -29,15 +29,16 @@ import { DurationRow, durationMax } from './durations';
|
||||
@if (loading()) {
|
||||
<app-loading what="los tiempos" [figure]="true" />
|
||||
} @else {
|
||||
@let rows = mode() === 'sample' ? sample() : step();
|
||||
@let rows = mode() === 'sample' ? sample() : chain(step());
|
||||
@let max = scale(rows);
|
||||
<p class="state">
|
||||
@if (mode() === 'sample') {
|
||||
Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se
|
||||
calcula por separado.
|
||||
} @else {
|
||||
Cada barra es la mediana de su paso, desde cero y por separado; los pasos pueden
|
||||
corresponder a poblaciones diferentes, por lo que las medianas no se suman.
|
||||
Esquema: cada barra es la mediana de su paso y empieza donde termina el paso del que
|
||||
parte. Los pasos pueden corresponder a poblaciones diferentes, por lo que las
|
||||
medianas no se suman.
|
||||
}
|
||||
Las marcas indican el primer y tercer cuartil.
|
||||
@if (max) {
|
||||
@@ -62,16 +63,17 @@ import { DurationRow, durationMax } from './durations';
|
||||
<span class="track" aria-hidden="true">
|
||||
<span
|
||||
class="bar"
|
||||
[style.margin-left.%]="max ? (100 * (row.start ?? 0)) / max : 0"
|
||||
[style.width.%]="max ? (100 * row.median!) / max : 0"
|
||||
></span>
|
||||
@if (row.low !== undefined && row.high !== undefined) {
|
||||
<span
|
||||
class="mark"
|
||||
[style.left.%]="max ? (100 * row.low) / max : 0"
|
||||
[style.left.%]="max ? (100 * ((row.start ?? 0) + row.low)) / max : 0"
|
||||
></span>
|
||||
<span
|
||||
class="mark"
|
||||
[style.left.%]="max ? (100 * row.high) / max : 0"
|
||||
[style.left.%]="max ? (100 * ((row.start ?? 0) + row.high)) / max : 0"
|
||||
></span>
|
||||
}
|
||||
</span>
|
||||
@@ -180,4 +182,5 @@ export class RouteCard {
|
||||
|
||||
protected readonly mode = signal<'sample' | 'step'>('step');
|
||||
protected readonly scale = durationMax;
|
||||
protected readonly chain = chained;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
|
||||
<app-readings
|
||||
[title]="s.title"
|
||||
[camaStyle]="hasCamaHeading(s)"
|
||||
[headline]="headlineOf(s)"
|
||||
[headline]="s.footnote ? '' : headlineOf(s)"
|
||||
[foot]="footOf(s)"
|
||||
[note]="s.note ?? ''"
|
||||
[modes]="s.modes"
|
||||
[view]="view()"
|
||||
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
|
||||
[title]="c.section.title"
|
||||
[hideTitle]="true"
|
||||
[camaStyle]="true"
|
||||
[headline]="headlineOf(c.section)"
|
||||
[headline]="c.section.footnote ? '' : headlineOf(c.section)"
|
||||
[foot]="footOf(c.section)"
|
||||
[note]="c.section.note ?? ''"
|
||||
[modes]="c.section.modes"
|
||||
[loading]="of().loading"
|
||||
@@ -162,6 +164,12 @@ export class ReadingsSection {
|
||||
const words = detail(measure, r, s.unit);
|
||||
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
|
||||
}
|
||||
/** The headline of a card that says it under its figure, as one line separated by commas. */
|
||||
protected footOf(s: ReadingsCard): string {
|
||||
return s.footnote
|
||||
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
|
||||
: '';
|
||||
}
|
||||
protected readonly draw = computed(() => (mode: Mode) => {
|
||||
if (mode.kind !== 'figure') return undefined;
|
||||
const r = this.of().reading(mode.measure);
|
||||
|
||||
@@ -31,6 +31,21 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
|
||||
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
|
||||
espécimen fue insatisfactorio.
|
||||
</p>
|
||||
<h4>Riesgos de referencia NCI</h4>
|
||||
<p>
|
||||
Los riesgos de referencia corresponden a la cohorte Kaiser Permanente Northern
|
||||
California (2003–2017, pacientes de 25 a 65 años). Las guías ASCCP deciden la
|
||||
conducta con el riesgo de CIN3+. Los riesgos publicados de CIN2+ y cáncer son
|
||||
resultados complementarios; no son directamente comparables con las estimaciones
|
||||
institucionales porque no están validados para la población de esta plataforma.
|
||||
</p>
|
||||
<ul>
|
||||
<li><a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/" target="_blank" rel="noopener noreferrer">Egemen y colaboradores: estimaciones que sustentan las guías (2020).</a></li>
|
||||
<li><a href="https://doi.org/10.1097/LGT.0000000000000528" target="_blank" rel="noopener noreferrer">Cheung y colaboradores: métodos de estimación (2020).</a></li>
|
||||
<li><a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/" target="_blank" rel="noopener noreferrer">Perkins y colaboradores: guías de manejo ASCCP 2019.</a></li>
|
||||
<li><a href="https://data.lhncbc.nlm.nih.gov/public/cervixca/AdditionalTables.zip" target="_blank" rel="noopener noreferrer">LHNCBC: libros de tablas adicionales.</a></li>
|
||||
<li><a href="https://web.archive.org/web/20240710095705/https://lhncbc.nlm.nih.gov/LHC-research/LHC-projects/image-processing/cervixca.html" target="_blank" rel="noopener noreferrer">LHNCBC: página archivada de las tablas, 10 de julio de 2024.</a></li>
|
||||
</ul>
|
||||
}
|
||||
@if (available().length) {
|
||||
<p>Periodicidad disponible: {{ available().join(', ') }}.</p>
|
||||
@@ -48,6 +63,20 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
|
||||
@if (m.description) {
|
||||
<p>{{ m.description }}</p>
|
||||
}
|
||||
@if (m.relatedArtifact?.length) {
|
||||
<h4>Referencias</h4>
|
||||
<ul>
|
||||
@for (reference of m.relatedArtifact; track $index) {
|
||||
<li>
|
||||
@if (reference.url) {
|
||||
<a [href]="reference.url" target="_blank" rel="noopener noreferrer">{{ reference.citation || reference.display || reference.url }}</a>
|
||||
} @else {
|
||||
{{ reference.citation || reference.display }}
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<h4>Cálculo</h4>
|
||||
<p>
|
||||
{{ scoring[code(m.scoring) ?? ''] }}
|
||||
|
||||
@@ -40,49 +40,96 @@
|
||||
}
|
||||
@if (page(); as pg) {
|
||||
@if (applied(); as period) {
|
||||
<section class="card opportunity" aria-labelledby="opportunity-title">
|
||||
<div class="section-head">
|
||||
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
|
||||
<span class="period">Periodo {{ period }}</span>
|
||||
</div>
|
||||
<div class="kpis">
|
||||
@for (k of pg.kpis; track k.title) {
|
||||
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
|
||||
<mat-card-content>
|
||||
<h3 class="kpi-title">{{ k.title }}</h3>
|
||||
@if (reports.isLoading() && k.measure) {
|
||||
<app-loading [what]="k.title.toLowerCase()" />
|
||||
} @else {
|
||||
<div class="kpi-value" [class.pending]="!k.measure">
|
||||
@let v = kpiParts(kpiValue(k));
|
||||
{{ v[0] }}
|
||||
@if (v[1]) {
|
||||
<span class="kpi-qualifier">{{ v[1] }}</span>
|
||||
}
|
||||
</div>
|
||||
<div class="kpi-detail">{{ kpiNote(k) }}</div>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
@if (domain() === 'cama') {
|
||||
<section class="card opportunity" aria-labelledby="opportunity-title">
|
||||
<div class="section-head">
|
||||
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
|
||||
<span class="period">Periodo {{ period }}</span>
|
||||
</div>
|
||||
<div class="kpis" style="--kpi-cols-md: 3; --kpi-cols-lg: 3">
|
||||
@for (k of pg.kpis; track k.title) {
|
||||
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
|
||||
}
|
||||
</div>
|
||||
@for (section of pg.opportunity ?? []; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
@for (section of pg.opportunity ?? []; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
</section>
|
||||
<section class="card clinical-page" aria-labelledby="clinical-title">
|
||||
<h2 id="clinical-title">Indicadores clínicos</h2>
|
||||
@for (section of pg.clinical; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
} @else {
|
||||
@if (domain() === 'cacu') {
|
||||
<section class="card clinical-page" aria-labelledby="clinical-title">
|
||||
<h2 id="clinical-title">Indicadores clínicos</h2>
|
||||
@for (section of pg.clinical; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</section>
|
||||
<section class="card opportunity" aria-labelledby="opportunity-title">
|
||||
<div class="section-head">
|
||||
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
|
||||
<span class="period">Periodo {{ period }}</span>
|
||||
</div>
|
||||
<div
|
||||
class="kpis"
|
||||
[style.--kpi-cols-md]="pg.kpis.length < 3 ? pg.kpis.length : 3"
|
||||
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
|
||||
>
|
||||
@for (k of pg.kpis; track k.title) {
|
||||
<ng-container *ngTemplateOutlet="kpiView; context: { $implicit: k }" />
|
||||
}
|
||||
</div>
|
||||
@for (section of pg.opportunity ?? []; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="card clinical-page" aria-labelledby="clinical-title">
|
||||
<h2 id="clinical-title">Indicadores clínicos</h2>
|
||||
@for (section of pg.clinical; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
@if (domain() !== 'cacu') {
|
||||
<section class="card clinical-page" aria-labelledby="clinical-title">
|
||||
<h2 id="clinical-title">Indicadores clínicos</h2>
|
||||
@for (section of pg.clinical; track $index) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="sectionView; context: { $implicit: section, period: period }"
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
<ng-template #kpiView let-k>
|
||||
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
|
||||
<mat-card-content>
|
||||
<h3 class="kpi-title">{{ k.title }}</h3>
|
||||
@if (reports.isLoading() && k.measure) {
|
||||
<app-loading [what]="k.title.toLowerCase()" />
|
||||
} @else {
|
||||
<div class="kpi-value" [class.pending]="!k.measure">
|
||||
@let v = kpiParts(kpiValue(k));
|
||||
{{ v[0] }}
|
||||
@if (v[1]) {
|
||||
<span class="kpi-qualifier">{{ v[1] }}</span>
|
||||
}
|
||||
</div>
|
||||
<div class="kpi-detail">{{ kpiNote(k) }}</div>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #sectionView let-section let-period="period">
|
||||
@switch (section.kind) {
|
||||
@case ('readings')
|
||||
|
||||
@@ -42,13 +42,13 @@ h2 {
|
||||
|
||||
@media (min-width: 1000px) {
|
||||
.kpis {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-columns: repeat(var(--kpi-cols-md, 3), 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1350px) {
|
||||
.kpis {
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
grid-template-columns: repeat(var(--kpi-cols-lg, 5), 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@
|
||||
</td>
|
||||
<td>
|
||||
{{ row.age ?? 'No disponible' }}
|
||||
<small>Grupo: {{ row.ageGroup }}</small>
|
||||
<small>Grupo: {{ name(row.ageGroup) }}</small>
|
||||
</td>
|
||||
<td>{{ name(row.status) }}</td>
|
||||
<td>
|
||||
|
||||
@@ -16,8 +16,8 @@ import { MatSelectModule } from '@angular/material/select';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import type { Bundle } from 'fhir/r4';
|
||||
import { Fhir } from '../fhir';
|
||||
import { saveExcel, savePdf } from '../export';
|
||||
import { Stages } from '../paciente/stages';
|
||||
import { saveFollowUp } from './follow-up-export';
|
||||
import { cytologyResult, followUpSheet } from './follow-up-sheet';
|
||||
import { bornFor, Row, rows, windowStart } from './follow-up';
|
||||
import { PatientSearch, patientSearch } from './patient-search';
|
||||
@@ -140,24 +140,28 @@ export class TabRiesgos {
|
||||
|
||||
/** The whole list, not the page shown, as a file. */
|
||||
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
|
||||
const page = this.page();
|
||||
if (!page) return;
|
||||
this.saving.set(true);
|
||||
this.saveError.set('');
|
||||
try {
|
||||
const cutoff = this.applied();
|
||||
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
|
||||
const pages = await this.fhir.all(this.domain(), 'Patient', asked);
|
||||
const start = windowStart(cutoff, this.window());
|
||||
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon()));
|
||||
const sheet = followUpSheet(all, [
|
||||
['Ventana consultada', `${start} al ${cutoff}`],
|
||||
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
|
||||
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`],
|
||||
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`],
|
||||
['Búsqueda', this.search() || 'Ninguna'],
|
||||
['Horizonte de la probabilidad (años)', `${this.horizon()}`],
|
||||
]);
|
||||
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu');
|
||||
else await savePdf([sheet], 'seguimiento-cacu', true);
|
||||
await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) => {
|
||||
const cutoffYear = Number(query.cutoff.slice(0, 4));
|
||||
// bornFor encodes the minimum with le and the maximum with gt at one year earlier.
|
||||
const lower = query.birthdates.find((value) => value.startsWith('le'));
|
||||
const upper = query.birthdates.find((value) => value.startsWith('gt'));
|
||||
const minimum = lower ? `${cutoffYear - Number(lower.slice(2, 6))}` : 'Sin límite';
|
||||
const maximum = upper ? `${cutoffYear - Number(upper.slice(2, 6)) - 1}` : 'Sin límite';
|
||||
const all = pages.flatMap((p) => rows(p, query.start, query.cutoff, query.horizon));
|
||||
return followUpSheet(all, [
|
||||
['Ventana consultada', query.window],
|
||||
['Estatus de seguimiento', query.status],
|
||||
['Edad mínima', minimum],
|
||||
['Edad máxima', maximum],
|
||||
['Búsqueda', query.search],
|
||||
['Horizonte de la probabilidad (años)', `${query.horizon}`],
|
||||
]);
|
||||
});
|
||||
} catch {
|
||||
this.saveError.set('No se generó el archivo.');
|
||||
} finally {
|
||||
|
||||
@@ -35,7 +35,26 @@
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button
|
||||
mat-stroked-button
|
||||
type="button"
|
||||
[disabled]="saving() || !applied()"
|
||||
(click)="save('xlsx')"
|
||||
>
|
||||
Exportar Excel
|
||||
</button>
|
||||
<button
|
||||
mat-stroked-button
|
||||
type="button"
|
||||
[disabled]="saving() || !applied()"
|
||||
(click)="save('pdf')"
|
||||
>
|
||||
Exportar PDF
|
||||
</button>
|
||||
</form>
|
||||
@if (saveError()) {
|
||||
<p class="muted" role="alert">{{ saveError() }}</p>
|
||||
}
|
||||
|
||||
@if (error()) {
|
||||
<p class="muted" role="alert">
|
||||
|
||||
@@ -7,6 +7,8 @@ import { MatSelectModule } from '@angular/material/select';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import type { Bundle } from 'fhir/r4';
|
||||
import { Fhir } from '../fhir';
|
||||
import { saveFollowUp } from './follow-up-export';
|
||||
import { camaFollowUpSheet } from './follow-up-sheet';
|
||||
import { camaRows, windowStart } from './follow-up';
|
||||
import { PatientSearch, patientSearch } from './patient-search';
|
||||
import { Loading } from '../loading';
|
||||
@@ -46,23 +48,23 @@ export class TabSeguimiento {
|
||||
protected readonly statuses = STATUSES;
|
||||
protected readonly name = name;
|
||||
protected readonly priority = (code: string) => PRIORITY[code] ?? code;
|
||||
protected readonly saving = signal(false);
|
||||
protected readonly saveError = signal('');
|
||||
|
||||
/** The list as it is asked for, whatever the page. */
|
||||
private readonly query = computed(() => ({
|
||||
'follow-up-window': this.window(),
|
||||
...patientSearch(this.search()),
|
||||
'follow-up-cutoff': this.cutoff() || undefined,
|
||||
'follow-up-status': this.status() || undefined,
|
||||
_revinclude: ['DiagnosticReport:subject'],
|
||||
'_include:iterate': 'DiagnosticReport:result',
|
||||
}));
|
||||
private readonly first = resource({
|
||||
params: () => ({
|
||||
domain: this.domain(),
|
||||
'follow-up-window': this.window(),
|
||||
...patientSearch(this.search()),
|
||||
'follow-up-cutoff': this.cutoff() || undefined,
|
||||
'follow-up-status': this.status() || undefined,
|
||||
_count: this.size(),
|
||||
}),
|
||||
loader: ({ params: { domain, ...params } }) => {
|
||||
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
|
||||
loader: ({ params: { domain, query, size } }) => {
|
||||
this.moved.set(undefined);
|
||||
return this.fhir.search(domain, 'Patient', {
|
||||
...params,
|
||||
_revinclude: ['DiagnosticReport:subject'],
|
||||
'_include:iterate': 'DiagnosticReport:result',
|
||||
});
|
||||
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
|
||||
},
|
||||
});
|
||||
protected readonly loading = signal(false);
|
||||
@@ -95,6 +97,31 @@ export class TabSeguimiento {
|
||||
this.first.reload();
|
||||
}
|
||||
|
||||
/** The whole list, not the page shown, as a file. */
|
||||
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
|
||||
const page = this.page();
|
||||
if (!page) return;
|
||||
this.saving.set(true);
|
||||
this.saveError.set('');
|
||||
try {
|
||||
await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) =>
|
||||
camaFollowUpSheet(
|
||||
pages.flatMap((p) => camaRows(p, query.cutoff)),
|
||||
[
|
||||
['Ventana consultada', query.window],
|
||||
['Estatus de seguimiento', query.status],
|
||||
['Búsqueda', query.search],
|
||||
],
|
||||
this.priority,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
this.saveError.set('No se generó el archivo.');
|
||||
} finally {
|
||||
this.saving.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected has(relation: 'next' | 'previous'): boolean {
|
||||
return !!this.page()?.link?.some((l) => l.relation === relation);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import type { Measure } from 'fhir/r4';
|
||||
import { Fhir } from '../fhir';
|
||||
import { HISTORY } from './pages';
|
||||
import { TabTrazabilidad } from './tab-trazabilidad';
|
||||
|
||||
describe('Trazabilidad: periodo seleccionado', () => {
|
||||
for (const domain of ['cama', 'cacu']) {
|
||||
it(`applies a monthly and semester period to the ${domain} queries`, async () => {
|
||||
const requests: Record<string, string>[] = [];
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TabTrazabilidad],
|
||||
providers: [
|
||||
{
|
||||
provide: Fhir,
|
||||
useValue: {
|
||||
all: async (_domain: string, _resource: string, params: Record<string, string>) => {
|
||||
requests.push(params);
|
||||
return [{ resourceType: 'Bundle', type: 'searchset', entry: [] }];
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
const fixture = TestBed.createComponent(TabTrazabilidad);
|
||||
fixture.componentRef.setInput('domain', domain);
|
||||
fixture.componentRef.setInput('measures', [
|
||||
{ resourceType: 'Measure', id: 'test', name: HISTORY[domain].panels[0].measure },
|
||||
] as Measure[]);
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
const component = fixture.componentInstance as any;
|
||||
component.chosen.set('2025-03');
|
||||
fixture.detectChanges();
|
||||
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2025-03');
|
||||
expect(requests.at(-1)?.['as-of']).toBeUndefined();
|
||||
component.setType('semester');
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
component.chosen.set('2024-S1');
|
||||
fixture.detectChanges();
|
||||
(fixture.nativeElement.querySelector('button[mat-flat-button]') as HTMLButtonElement).click();
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
expect(requests.at(-1)?.['reporting-period'].split(',').at(-1)).toBe('2024-S1');
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import type { Measure, MeasureReport } from 'fhir/r4';
|
||||
import { Fhir, resources } from '../fhir';
|
||||
import { Loading } from '../loading';
|
||||
import { Figure, Plot } from '../plot';
|
||||
import { historyFigure } from './figures';
|
||||
import { periodLabel, periods, PeriodType, reading } from './measures';
|
||||
import { historyPeriods, periodLabel, periods, PeriodType, reading } from './measures';
|
||||
import { HISTORY, HistoryPanel } from './pages';
|
||||
|
||||
interface Drawn {
|
||||
@@ -19,18 +21,31 @@ interface Drawn {
|
||||
* each measure period by period. */
|
||||
@Component({
|
||||
selector: 'app-tab-trazabilidad',
|
||||
imports: [Loading, MatButtonToggleModule, Plot],
|
||||
imports: [Loading, MatButtonModule, MatButtonToggleModule, MatSelectModule, Plot],
|
||||
template: `
|
||||
<section class="card filters" aria-labelledby="history-filters">
|
||||
<h2 id="history-filters" class="filters-title">Filtros</h2>
|
||||
<mat-button-toggle-group
|
||||
[value]="type()"
|
||||
(change)="type.set($event.value)"
|
||||
(change)="setType($event.value)"
|
||||
aria-label="Intervalo de análisis"
|
||||
>
|
||||
<mat-button-toggle value="month">Mensual</mat-button-toggle>
|
||||
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
@if (domain() === 'cama' || domain() === 'cacu') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
|
||||
@for (p of options(); track p) {
|
||||
<mat-option [value]="p">{{ p }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button mat-flat-button (click)="applied.set(chosen())" [disabled]="chosen() === applied()">
|
||||
Aplicar
|
||||
</button>
|
||||
}
|
||||
</section>
|
||||
@if (series.isLoading()) {
|
||||
<app-loading what="el histórico" text="Cargando histórico…" />
|
||||
@@ -71,6 +86,12 @@ interface Drawn {
|
||||
padding: 16px 20px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
}
|
||||
.filters-title {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
@@ -95,13 +116,28 @@ export class TabTrazabilidad {
|
||||
readonly domain = input.required<string>();
|
||||
readonly measures = input.required<Measure[]>();
|
||||
protected readonly type = signal<PeriodType>('month');
|
||||
protected readonly options = computed(() => periods(this.type()));
|
||||
protected readonly chosen = signal(periods('month')[0]);
|
||||
protected readonly applied = signal(periods('month')[0]);
|
||||
|
||||
protected setType(type: PeriodType): void {
|
||||
this.type.set(type);
|
||||
const latest = this.options()[0];
|
||||
this.chosen.set(latest);
|
||||
this.applied.set(latest);
|
||||
}
|
||||
|
||||
protected readonly series = resource({
|
||||
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
|
||||
params: () => ({
|
||||
domain: this.domain(),
|
||||
type: this.type(),
|
||||
measures: this.measures(),
|
||||
period: this.applied(),
|
||||
}),
|
||||
loader: async ({ params }) => {
|
||||
const history = HISTORY[params.domain];
|
||||
if (!history) return [];
|
||||
const asked = periods(params.type).reverse();
|
||||
const asked = historyPeriods(params.type, params.period);
|
||||
return Promise.all(
|
||||
history.panels.map(async (panel) => {
|
||||
const measure = params.measures.find((m) => m.name === panel.measure);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { camaRecordSheets } from './cama-record-sheets';
|
||||
|
||||
const sheets = (over: Partial<Parameters<typeof camaRecordSheets>> = []) =>
|
||||
camaRecordSheets(
|
||||
(over[0] as any) ?? [['Nombre', 'Ana'], ['CURP', undefined]],
|
||||
(over[1] as any) ?? [['Categoría BI-RADS de la última mastografía', '4B'], ['Resultado histopatológico', undefined]],
|
||||
(over[2] as any) ?? [{ date: '2025-01-02', kind: 'Procedimiento', text: 'Mastectomía' }],
|
||||
(over[3] as any) ?? [{ date: '2025-01-01', kind: 'Mastografía', reported: undefined, results: ['BI-RADS: 4B'], findings: [] }],
|
||||
(over[4] as any) ?? [],
|
||||
(over[5] as any) ?? [],
|
||||
);
|
||||
const by = (s: ReturnType<typeof sheets>, title: string) => s.find((x) => x.title.startsWith(title))!;
|
||||
|
||||
// Each test fails if the PDF made up a value, kept a section of CaCu or dropped what CaMa publishes.
|
||||
describe('the CaMa record as a PDF', () => {
|
||||
it('has only CaMa sections and says a missing value as such', () => {
|
||||
const s = sheets();
|
||||
expect(s.map((x) => x.title)).toEqual([
|
||||
'Datos de la paciente',
|
||||
'Última mastografía y resultado histopatológico',
|
||||
'Historial médico',
|
||||
'Pruebas y resultados',
|
||||
'Riesgos y recomendaciones publicados',
|
||||
]);
|
||||
expect(s.some((x) => /citolog|VPH|NCI|ASCCP|Etapas/i.test(x.title + x.head.join()))).toBe(false);
|
||||
expect(by(s, 'Datos').rows).toEqual([['Nombre', 'Ana'], ['CURP', 'No disponible']]);
|
||||
expect(by(s, 'Última').rows[1]).toEqual(['Resultado histopatológico', 'No disponible']);
|
||||
expect(by(s, 'Pruebas').rows[0].slice(0, 3)).toEqual(['2025-01-01', 'Mastografía', 'Pendiente']);
|
||||
});
|
||||
it('without published estimates it says there are none, with no probability', () => {
|
||||
expect(by(sheets(), 'Riesgos').rows).toEqual([
|
||||
['Sin estimaciones publicadas', 'No disponible', 'No disponible', 'No disponible', 'No disponible'],
|
||||
]);
|
||||
});
|
||||
it('publishes each estimate by horizon with its interval, and a zero is a value', () => {
|
||||
const s = sheets([
|
||||
undefined, undefined, undefined, undefined,
|
||||
[{ text: 'Supervivencia v2', index: '2026-01-01', predictions: [{ years: 0, p: 0, low: 0, high: 0.01 }, { years: 5, p: 0.8 }] }],
|
||||
] as any);
|
||||
expect(by(s, 'Riesgos').rows).toEqual([
|
||||
['Supervivencia v2', '2026-01-01', 'Al índice', '0.00 %', '0.00 % a 1.00 %'],
|
||||
['Supervivencia v2', '2026-01-01', '5 años', '80.00 %', 'No disponible'],
|
||||
]);
|
||||
});
|
||||
it('lists the scenario curves, the ones without a curve and the group nature of the estimates', () => {
|
||||
const s = sheets([
|
||||
undefined, undefined, undefined, undefined, [],
|
||||
[{ title: 'Supervivencia', scenarios: ['A', 'B'], figures: ['A (n = 9, fallecidos = 6)'], undrawn: ['B'] }],
|
||||
] as any);
|
||||
const sheet = by(s, 'Supervivencia y recurrencia');
|
||||
expect(sheet.title).toContain('no predicciones individuales');
|
||||
expect(sheet.rows).toEqual([
|
||||
['Supervivencia', 'A (n = 9, fallecidos = 6)', 'Curva publicada'],
|
||||
['Supervivencia', 'B', 'No disponible: datos insuficientes'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,14 @@ export const CRITERION_TEXT: Record<string, string> = {
|
||||
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
|
||||
cancer_history: 'Antecedente de cáncer cervicouterino',
|
||||
prior_treatment: 'Tratamiento previo a la visita índice',
|
||||
no_referral: 'Sin resultado que sustente la referencia a colposcopia',
|
||||
no_referral: 'Sin citología de referencia previa a la colposcopia',
|
||||
referral_not_graded: 'Citología de referencia de bajo grado sin VPH positivo',
|
||||
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
|
||||
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
|
||||
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
|
||||
no_birth_date: 'Fecha de nacimiento desconocida',
|
||||
died_by_index: 'Defunción en o antes de la visita índice',
|
||||
not_evaluated: 'Escenario que la plataforma no evalúa por ahora',
|
||||
};
|
||||
|
||||
export interface Reason {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EligibilityState, Visit } from './eligibility';
|
||||
import { ineligibility } from './ineligibility';
|
||||
import { currency, ineligibility } from './ineligibility';
|
||||
|
||||
const visit = (indexDate: string, ...reasons: string[]): Visit => ({
|
||||
indexDate,
|
||||
@@ -28,4 +28,28 @@ describe('ineligibility', () => {
|
||||
expect(ineligibility(state, 'case', '2025-06-01')).toBeUndefined();
|
||||
expect(ineligibility({ kind: 'error' }, 'pre_colposcopy', '2025-06-01')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('says of a treated patient only that she was already treated', () => {
|
||||
const text = 'No disponible por: paciente ya tratada.';
|
||||
expect(ineligibility(state, 'post_treatment', '2025-06-01')).toBe(text);
|
||||
expect(ineligibility({ kind: 'error' }, 'post_treatment', '2025-06-01')).toBe(text);
|
||||
});
|
||||
});
|
||||
|
||||
describe('currency', () => {
|
||||
const pre = [{ model: 'cacu.cin2_pim', index: '2025-01-01' }];
|
||||
const post = [{ model: 'cacu.cin2_pim_post_colposcopy', index: '2025-01-01' }];
|
||||
|
||||
it('dates the estimate and says when there is a later cytology', () => {
|
||||
expect(currency(pre, ['2025-01-01', '2024-01-01']).note).toBe(
|
||||
'Estimación de la citología del 2025-01-01.',
|
||||
);
|
||||
expect(currency(pre, ['2025-06-01', '2025-01-01']).note).toContain('posterior, del 2025-06-01');
|
||||
expect(currency([], ['2025-06-01'])).toEqual({});
|
||||
});
|
||||
|
||||
it('shows no post-colposcopy estimate once there is a later visit', () => {
|
||||
expect(currency(post, ['2025-01-01']).excluded).toBeUndefined();
|
||||
expect(currency(post, ['2025-06-01', '2025-01-01']).excluded).toContain('(2025-06-01)');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,6 @@ import type { EligibilityState } from './eligibility';
|
||||
const SCENARIOS: Record<string, string[]> = {
|
||||
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
|
||||
post_colposcopy: ['post_colposcopy'],
|
||||
post_treatment: ['post_treatment'],
|
||||
};
|
||||
|
||||
/** What the risk section says when she is not eligible in her clinical scenario, from its latest
|
||||
@@ -15,6 +14,8 @@ export function ineligibility(
|
||||
status: string,
|
||||
day: string,
|
||||
): string | undefined {
|
||||
// a treated patient has no risk estimate, whatever visit was indexed
|
||||
if (status === 'post_treatment') return 'No disponible por: paciente ya tratada.';
|
||||
if (state.kind !== 'evaluated') return undefined;
|
||||
for (const scenario of SCENARIOS[status] ?? []) {
|
||||
// visits come latest first
|
||||
@@ -29,3 +30,27 @@ export function ineligibility(
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Which cytology her estimates speak of, against her latest by the cut-off. After the first
|
||||
* post-colposcopy visit nothing is evaluated; otherwise a later cytology is only said. */
|
||||
export function currency(
|
||||
estimates: { model: string; index: string }[],
|
||||
cytologies: string[],
|
||||
): { sample?: string; excluded?: string; note?: string } {
|
||||
const sample = estimates.map((e) => e.index.slice(0, 10)).sort().at(-1);
|
||||
if (!sample) return {};
|
||||
const latest = cytologies.map((d) => d.slice(0, 10)).sort().at(-1);
|
||||
if (!latest || latest <= sample) {
|
||||
return { sample, note: `Estimación de la citología del ${sample}.` };
|
||||
}
|
||||
if (estimates.some((e) => e.model.includes('post_colposcopy'))) {
|
||||
return {
|
||||
sample,
|
||||
excluded: `No disponible por: hay una citología posterior a la primera visita poscolposcopía (${latest}) y solo se evalúa esa primera visita.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
sample,
|
||||
note: `Estimación de la citología del ${sample}. Hay una citología posterior, del ${latest}, que no se evalúa.`,
|
||||
};
|
||||
}
|
||||
|
||||
+151
-74
@@ -5,9 +5,21 @@
|
||||
@if (error()) {
|
||||
<p class="muted" role="alert">No se encontró la paciente.</p>
|
||||
} @else if (patient(); as p) {
|
||||
<h1>
|
||||
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
|
||||
</h1>
|
||||
<div class="record-head">
|
||||
<h1>
|
||||
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
|
||||
</h1>
|
||||
@if (cama()) {
|
||||
<div class="head-actions">
|
||||
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
|
||||
Exportar PDF
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@if (cama() && saveError()) {
|
||||
<p class="muted" role="alert">{{ saveError() }}</p>
|
||||
}
|
||||
<dl class="summary">
|
||||
<div>
|
||||
<dt>CURP</dt>
|
||||
@@ -119,6 +131,9 @@
|
||||
@if (saveError()) {
|
||||
<p class="muted" role="alert">{{ saveError() }}</p>
|
||||
}
|
||||
<p class="muted route-note">
|
||||
Los pasos muestran el tamizaje actual, en curso: el de la citología que se consulta.
|
||||
</p>
|
||||
<div data-section="etapas">
|
||||
<app-stages [stages]="s" [detail]="true" />
|
||||
</div>
|
||||
@@ -139,7 +154,7 @@
|
||||
<td>
|
||||
{{ h.text }}
|
||||
@if (h.code && h.code !== h.text) {
|
||||
<span class="muted">({{ h.code }})</span>
|
||||
<span class="muted">(CIE-10: {{ h.code }})</span>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -246,66 +261,76 @@
|
||||
</mat-card>
|
||||
}
|
||||
|
||||
<mat-card appearance="outlined" class="wide" data-section="riesgos">
|
||||
<mat-card-content>
|
||||
@if (riskExclusion(); as reason) {
|
||||
<p role="status">{{ reason }}</p>
|
||||
} @else {
|
||||
<app-risk-scales [groups]="groups()" />
|
||||
@if (excluded() || groups().length || domain() !== 'cacu' || riskModels().length) {
|
||||
<mat-card appearance="outlined" class="wide" data-section="riesgos">
|
||||
@if (excluded(); as reason) {
|
||||
<mat-card-header>
|
||||
<mat-card-title>Sin estimación de riesgo: criterio de exclusión</mat-card-title>
|
||||
</mat-card-header>
|
||||
}
|
||||
@if (riskModels().length) {
|
||||
<details data-section="modelos">
|
||||
<summary>Modelos y valores</summary>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Modelo</th>
|
||||
<th>Fecha índice</th>
|
||||
<th>Horizonte</th>
|
||||
<th>Probabilidad</th>
|
||||
<th>IC 95 %</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (m of riskModels(); track m.model) {
|
||||
@for (p of m.predictions; track p.years) {
|
||||
<tr>
|
||||
<td>{{ $first ? m.text : '' }}</td>
|
||||
<td>{{ $first ? m.index : '' }}</td>
|
||||
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
|
||||
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
|
||||
<td>
|
||||
@if (p.low !== undefined) {
|
||||
{{ p.low * 100 | number: '1.1-2' }}–{{
|
||||
p.high! * 100 | number: '1.1-2'
|
||||
}}
|
||||
%
|
||||
} @else {
|
||||
—
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
}
|
||||
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
|
||||
<details class="curves" open data-section="curvas">
|
||||
<summary>Curvas de probabilidad con su intervalo</summary>
|
||||
@if (riskSeries.value()?.length) {
|
||||
<app-risk-series [series]="riskSeries.value()!" />
|
||||
} @else {
|
||||
<app-plot [figure]="curve()" [height]="300" />
|
||||
<mat-card-content>
|
||||
@if (excluded(); as reason) {
|
||||
<p role="status" data-state="excluded">{{ reason }}</p>
|
||||
} @else {
|
||||
@if (currency().note; as note) {
|
||||
<p class="muted route-note" data-state="toma">{{ note }}</p>
|
||||
}
|
||||
</details>
|
||||
}
|
||||
@if (!riskModels().length && !riskExclusion()) {
|
||||
<p class="muted">Sin evaluación de un modelo en producción.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<app-risk-scales [groups]="groups()" />
|
||||
@if (riskModels().length) {
|
||||
<details data-section="modelos">
|
||||
<summary>Modelos y valores</summary>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Modelo</th>
|
||||
<th>Fecha índice</th>
|
||||
<th>Horizonte</th>
|
||||
<th>Probabilidad</th>
|
||||
<th>IC 95 %</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (m of riskModels(); track m.model) {
|
||||
@for (p of m.predictions; track p.years) {
|
||||
<tr>
|
||||
<td>{{ $first ? m.text : '' }}</td>
|
||||
<td>{{ $first ? m.index : '' }}</td>
|
||||
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
|
||||
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
|
||||
<td>
|
||||
@if (p.low !== undefined) {
|
||||
{{ p.low * 100 | number: '1.1-2' }}–{{
|
||||
p.high! * 100 | number: '1.1-2'
|
||||
}}
|
||||
%
|
||||
} @else {
|
||||
—
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
}
|
||||
@if (riskModels().length || hasCurves()) {
|
||||
<details class="curves" open data-section="curvas">
|
||||
<summary>Curvas de probabilidad con su intervalo</summary>
|
||||
@if (hasCurves()) {
|
||||
<app-risk-series [series]="riskSeries.value()!" />
|
||||
} @else {
|
||||
<app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
|
||||
}
|
||||
</details>
|
||||
}
|
||||
@if (!riskModels().length) {
|
||||
<p class="muted">Sin evaluación de un modelo en producción.</p>
|
||||
}
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
@if (domain() === 'tea') {
|
||||
<mat-card appearance="outlined" class="wide" data-section="tea">
|
||||
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
|
||||
@@ -561,11 +586,70 @@
|
||||
}}</mat-card-title>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<h3>Análisis de supervivencia</h3>
|
||||
@if (survival.isLoading()) {
|
||||
@if (domain() !== 'cacu') {
|
||||
<h3>Análisis de supervivencia</h3>
|
||||
}
|
||||
@if (domain() === 'cacu') {
|
||||
<app-risk-scales [groups]="survivalScales()" />
|
||||
@for (g of survivalScales(); track $index) {
|
||||
<details data-section="valores-supervivencia">
|
||||
<summary>Modelos y valores</summary>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Modelo</th>
|
||||
<th>Fecha índice</th>
|
||||
<th>Horizonte</th>
|
||||
<th>Supervivencia</th>
|
||||
<th>IC 95 %</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (v of g.scales; track v.label) {
|
||||
<tr>
|
||||
<td>{{ $first ? g.model : '' }}</td>
|
||||
<td>{{ $first ? g.index : '' }}</td>
|
||||
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
|
||||
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
|
||||
<td>
|
||||
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
|
||||
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
|
||||
v.risk!.high! * 100 | number: '1.1-2'
|
||||
}}
|
||||
%
|
||||
} @else {
|
||||
—
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
}
|
||||
<h3>Curva de supervivencia</h3>
|
||||
@if (combination.isLoading()) {
|
||||
<app-loading what="la curva de supervivencia" [figure]="true" />
|
||||
} @else if (combination.error()) {
|
||||
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
||||
} @else if (combination.value(); as c) {
|
||||
@if (c.curves) {
|
||||
<p class="muted">
|
||||
Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 %
|
||||
Greenwood; n =
|
||||
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
|
||||
</p>
|
||||
<app-curve-chooser [choices]="c.curves.choices" [draw]="c.curves.draw" />
|
||||
} @else {
|
||||
<p class="muted">{{ c.missing }}</p>
|
||||
}
|
||||
} @else {
|
||||
<p class="muted">
|
||||
No disponible: la estimación no conserva los valores usados para elegir la curva.
|
||||
</p>
|
||||
}
|
||||
} @else if (survival.isLoading()) {
|
||||
<app-loading what="las curvas de supervivencia" [figure]="true" />
|
||||
} @else if (domain() === 'cacu') {
|
||||
<p class="muted">No disponible: el informe no contiene la curva para esta combinación.</p>
|
||||
} @else if (survival.value(); as s) {
|
||||
<h3>Escenario clínico de la paciente</h3>
|
||||
<ul class="scenarios">
|
||||
@@ -605,14 +689,7 @@
|
||||
} @else if (survival.error()) {
|
||||
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
||||
} @else {
|
||||
<p class="muted" data-state="sin-informe">
|
||||
@if (domain() === 'cacu') {
|
||||
No disponible: no hay un informe de supervivencia para los escenarios de la
|
||||
paciente.
|
||||
} @else {
|
||||
No disponible: datos insuficientes.
|
||||
}
|
||||
</p>
|
||||
<p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
@@ -138,3 +138,19 @@ h1 .id {
|
||||
margin: 8px 0;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
/* The name and, in CaMa, the export of the record on the same line; narrow screens put the button under the name. */
|
||||
.record-head {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.record-head h1 {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.head-actions {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import type { Domain } from '../api/models/domain';
|
||||
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
|
||||
import { scenarioFigure } from '../gobernanza/figures';
|
||||
import { savePdf } from '../export';
|
||||
import { camaRecordSheets } from './cama-record-sheets';
|
||||
import { recordSheets } from './record-sheets';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import type { Parameters as FhirParameters } from 'fhir/r4';
|
||||
@@ -29,10 +30,11 @@ import { firstValueFrom } from 'rxjs';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
|
||||
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
|
||||
import { ineligibility } from './ineligibility';
|
||||
import { currency, ineligibility } from './ineligibility';
|
||||
import { parseSeries, RiskSeries, Series } from './risk-series';
|
||||
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 { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
|
||||
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 { Loading } from '../loading';
|
||||
import { Factores, ScenarioFactors } from './factores';
|
||||
import { CurveChooser, figureChoices } from './curve-chooser';
|
||||
|
||||
/** An Observation's value as the screens say it, whatever its type. */
|
||||
function shown(o: Observation): string {
|
||||
@@ -79,10 +82,30 @@ function methods(figures: { figure: { data: unknown[] } }[]): string[] {
|
||||
return [...new Set(names.filter((n): n is string => !!n))];
|
||||
}
|
||||
|
||||
/** The day of an instant in the hospital's time zone (America/Monterrey). */
|
||||
function localDay(instant: string | undefined): string | undefined {
|
||||
return instant
|
||||
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
|
||||
if (!value) return undefined;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente',
|
||||
imports: [
|
||||
Factores,
|
||||
CurveChooser,
|
||||
Loading,
|
||||
DecimalPipe,
|
||||
MatButtonModule,
|
||||
@@ -174,6 +197,31 @@ export class Paciente {
|
||||
? `No disponible por: histerectomía registrada el ${recorded}.`
|
||||
: undefined;
|
||||
});
|
||||
/** CaCu: why the backend withholds some of her estimates at the cut-off, if it does. */
|
||||
protected readonly withheld = computed(() => {
|
||||
const patient = this.patient();
|
||||
return patient ? ext(patient, 'risk-withheld')?.valueString : undefined;
|
||||
});
|
||||
/** The one criterion she does not meet: nothing else of her risk is then shown. */
|
||||
protected readonly excluded = computed(
|
||||
() => this.withheld() ?? this.riskExclusion() ?? this.currency().excluded,
|
||||
);
|
||||
/** CaCu: the cytology her estimates speak of, against her latest by the cut-off. */
|
||||
protected readonly currency = computed(() =>
|
||||
this.domain() === 'cacu'
|
||||
? currency(
|
||||
this.riskModels(),
|
||||
(this.data.value()?.reports ?? [])
|
||||
.filter((r) => code(r.code) === 'cervical_cytology')
|
||||
.map((r) => r.effectiveDateTime ?? '')
|
||||
.filter((d) => d && d.slice(0, 10) <= this.cutoff()),
|
||||
)
|
||||
: {},
|
||||
);
|
||||
/** Whether any published series has a point to draw. */
|
||||
protected readonly hasCurves = computed(
|
||||
() => this.riskSeries.value()?.some((s) => s.points.length > 0) ?? false,
|
||||
);
|
||||
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
|
||||
protected readonly stages = computed(() => {
|
||||
const cytologies = (this.data.value()?.reports ?? []).filter(
|
||||
@@ -183,19 +231,52 @@ export class Paciente {
|
||||
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
|
||||
});
|
||||
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
|
||||
protected readonly riskModels = computed(() => this.models().filter((m) => isRiskModel(m.model)));
|
||||
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
|
||||
protected readonly scales = computed(() =>
|
||||
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
|
||||
);
|
||||
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */
|
||||
/** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
|
||||
* survival only there is nothing to draw here: its scales are in the survival section. */
|
||||
protected readonly groups = computed(() =>
|
||||
this.domain() === 'cacu' ? riskGroups(this.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. */
|
||||
protected readonly riskSeries = resource({
|
||||
params: () =>
|
||||
this.domain() === 'cacu'
|
||||
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
|
||||
? // the NCI's series speak of the same cytology as the institutional estimate
|
||||
{
|
||||
id: this.id(),
|
||||
cutoff: this.corte(),
|
||||
sample: this.currency().sample ?? this.citologia(),
|
||||
}
|
||||
: undefined,
|
||||
loader: async ({ params }): Promise<Series[] | undefined> => {
|
||||
try {
|
||||
@@ -242,11 +323,15 @@ export class Paciente {
|
||||
);
|
||||
protected readonly saving = signal(false);
|
||||
protected readonly saveError = signal('');
|
||||
/** CaCu: her record as a PDF. */
|
||||
/** Her record as a PDF (CaCu's or CaMa's). */
|
||||
protected async save(): Promise<void> {
|
||||
this.saving.set(true);
|
||||
this.saveError.set('');
|
||||
try {
|
||||
if (this.domain() === 'cama') {
|
||||
await this.saveCama();
|
||||
return;
|
||||
}
|
||||
const { name: who, curp, numbers } = this.identity();
|
||||
const facts: [string, string | undefined][] = [
|
||||
['Nombre', who],
|
||||
@@ -257,7 +342,7 @@ export class Paciente {
|
||||
['Estatus de seguimiento', this.status()],
|
||||
['Fecha de corte', this.cutoff()],
|
||||
];
|
||||
if (this.riskExclusion()) facts.push(['Evaluación de riesgo', this.riskExclusion()]);
|
||||
if (this.riskExclusion()) facts.push(['Evaluación de probabilidad', this.riskExclusion()]);
|
||||
const sheets = recordSheets(
|
||||
facts,
|
||||
this.stages() ?? [],
|
||||
@@ -273,6 +358,51 @@ export class Paciente {
|
||||
this.saving.set(false);
|
||||
}
|
||||
}
|
||||
/** CaMa: her record as a PDF, with what CaMa publishes of her. */
|
||||
private async saveCama(): Promise<void> {
|
||||
const c = this.cama();
|
||||
const { name: who, curp, numbers } = this.identity();
|
||||
const p = this.patient();
|
||||
const facts: [string, string | undefined][] = [
|
||||
['Nombre', who],
|
||||
['CURP', curp],
|
||||
['Expedientes', numbers.join(', ')],
|
||||
['Fecha de nacimiento', p?.birthDate],
|
||||
['Sexo', p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined],
|
||||
['Grupo de edad', c?.ageGroup],
|
||||
['Escenario clínico', c?.scenario],
|
||||
['Fecha de corte', c?.cutoff],
|
||||
[
|
||||
'Estatus de seguimiento',
|
||||
c ? (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`) : undefined,
|
||||
],
|
||||
['Prioridad', c?.priority],
|
||||
['Días de mastografía a diagnóstico', c?.days?.toString()],
|
||||
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as [string, string][]) : []),
|
||||
];
|
||||
const studies: [string, string | undefined][] = [
|
||||
['Categoría BI-RADS de la última mastografía', c?.birads],
|
||||
['Fecha de la última mastografía', c?.mammogram],
|
||||
['Resultado histopatológico', c?.histology],
|
||||
['Fecha de reporte de la biopsia', c?.biopsy],
|
||||
];
|
||||
const analysis = (title: string, r: typeof this.survival) => {
|
||||
// a report that failed to load is no analysis: its absence is said, the file is still made
|
||||
const v = r.hasValue() ? r.value() : undefined;
|
||||
return v
|
||||
? [{ title, scenarios: v.scenarios, figures: v.figures.map((f) => f.title), undrawn: v.unavailable }]
|
||||
: [];
|
||||
};
|
||||
const sheets = camaRecordSheets(
|
||||
facts,
|
||||
studies,
|
||||
this.history(),
|
||||
this.tests(),
|
||||
this.models(),
|
||||
[...analysis('Supervivencia', this.survival), ...analysis('Recurrencia', this.recurrence)],
|
||||
);
|
||||
await savePdf(sheets, 'expediente-cama');
|
||||
}
|
||||
protected readonly tests = computed(() => {
|
||||
const d = this.data.value();
|
||||
if (!d) return [];
|
||||
@@ -341,6 +471,9 @@ export class Paciente {
|
||||
text: r.method?.text ?? '',
|
||||
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
|
||||
index: r.occurrenceDateTime ?? '',
|
||||
measure: ext(r, 'prediction-measure')?.valueCode,
|
||||
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
|
||||
evaluated: localDay(r.meta?.lastUpdated),
|
||||
// the clinical scenarios of the model's report she falls in
|
||||
scenarios: (r.extension ?? [])
|
||||
.filter((e) => e.url === EXT + 'escenario-clinico')
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('the PDF of a record', () => {
|
||||
'Historial médico',
|
||||
'Antecedentes y evaluación ginecológica',
|
||||
'Pruebas y resultados',
|
||||
'Riesgos',
|
||||
'Probabilidades',
|
||||
]);
|
||||
});
|
||||
it('writes each stage with its state, its day or its request, and where it comes from', () => {
|
||||
|
||||
@@ -75,8 +75,8 @@ export function recordSheets(
|
||||
]),
|
||||
},
|
||||
{
|
||||
title: 'Riesgos',
|
||||
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
|
||||
title: 'Probabilidades',
|
||||
head: ['Estimación', 'Probabilidad', 'IC 95 %'],
|
||||
rows: scales.map(({ label, risk }) => [
|
||||
label,
|
||||
risk ? percent(risk.p) : NONE,
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { Parameters, ParametersParameter } from 'fhir/r4';
|
||||
/** The states a resolution ends in, as the screens say them. */
|
||||
export const STATUS_TEXT: Record<string, string> = {
|
||||
resolved: 'Referencia disponible',
|
||||
not_published: 'Riesgo no publicado en las tablas',
|
||||
not_published: 'Probabilidad no publicada en las tablas',
|
||||
missing_data: 'Falta un dato clínico',
|
||||
history_not_demonstrable: 'Antecedente no demostrable',
|
||||
not_applicable: 'Escenario no aplicable',
|
||||
@@ -44,7 +44,7 @@ export const REASON_TEXT: Record<string, string> = {
|
||||
hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.',
|
||||
cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.',
|
||||
biopsy_without_histology: 'La biopsia no tiene histología.',
|
||||
risk_blank_in_the_tables: 'Las tablas dejan este riesgo en blanco.',
|
||||
risk_blank_in_the_tables: 'Las tablas dejan esta probabilidad en blanco.',
|
||||
no_row_for_the_combination: 'Las tablas no publican esa combinación.',
|
||||
several_rows: 'Más de una fila podría corresponder.',
|
||||
no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.',
|
||||
@@ -54,7 +54,7 @@ export const REASON_TEXT: Record<string, string> = {
|
||||
index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.',
|
||||
population_not_verified:
|
||||
'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.',
|
||||
no_reference: 'Las tablas no dan un riesgo a este horizonte.',
|
||||
no_reference: 'Las tablas no dan una probabilidad a este horizonte.',
|
||||
};
|
||||
|
||||
const KEY_TEXT: Record<string, string> = {
|
||||
@@ -304,9 +304,9 @@ const OFFICIAL: Record<string, string> = {
|
||||
<section
|
||||
class="reference"
|
||||
data-section="referencia-nci"
|
||||
aria-label="Comparación de riesgos de referencia"
|
||||
aria-label="Comparación de probabilidades de referencia"
|
||||
>
|
||||
<h3>Comparación de riesgos de referencia</h3>
|
||||
<h3>Comparación de probabilidades de referencia</h3>
|
||||
<dl class="meta">
|
||||
<div>
|
||||
<dt>Estado</dt>
|
||||
@@ -458,7 +458,7 @@ const OFFICIAL: Record<string, string> = {
|
||||
</section>
|
||||
}
|
||||
<p class="muted note">
|
||||
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos
|
||||
La diferencia es la probabilidad institucional menos la probabilidad NCI y solo se calcula si ambos
|
||||
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
|
||||
</p>
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ describe('the institutional curves', () => {
|
||||
model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]),
|
||||
]);
|
||||
const lines = found.filter((t) => !t.name?.startsWith('IC'));
|
||||
expect(lines.map((t) => t.name)).toEqual(['Riesgo LIEAG+', 'Riesgo cáncer']);
|
||||
expect(lines.map((t) => t.name)).toEqual(['Probabilidad LIEAG+', 'Probabilidad cáncer']);
|
||||
expect(lines[0].x).toEqual([1, 3, 5]);
|
||||
expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]);
|
||||
expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere
|
||||
@@ -94,7 +94,7 @@ describe('the institutional curves', () => {
|
||||
model('Vacío v1', []),
|
||||
]),
|
||||
).toEqual([
|
||||
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
|
||||
'Probabilidad LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,7 +16,10 @@ export interface CurveModel {
|
||||
|
||||
const percent = (n: number) =>
|
||||
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 });
|
||||
const title = (m: CurveModel) => m.text.replace(/ v\d+$/, '');
|
||||
const title = (m: CurveModel) =>
|
||||
m.text
|
||||
.replace(/ v\d+$/, '')
|
||||
.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'));
|
||||
const interval = (p: CurvePrediction) => p.low !== undefined && p.high !== undefined;
|
||||
|
||||
/** The institutional models' risk by horizon: one series per model, drawn only at the horizons it
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -37,7 +37,7 @@ describe('the risk scales', () => {
|
||||
]);
|
||||
expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
|
||||
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
|
||||
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años'];
|
||||
const labels = ['Probabilidad inmediata (al índice)', 'Probabilidad a 5 años'];
|
||||
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
|
||||
expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]);
|
||||
expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]);
|
||||
@@ -48,15 +48,15 @@ describe('the risk scales', () => {
|
||||
expect(rest).toEqual([]);
|
||||
expect(none.title).toBeUndefined();
|
||||
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
|
||||
['Riesgo inmediato (al índice)', undefined],
|
||||
['Riesgo a 5 años', undefined],
|
||||
['Probabilidad inmediata (al índice)', undefined],
|
||||
['Probabilidad a 5 años', undefined],
|
||||
]);
|
||||
});
|
||||
it('the PDF keeps its flat list, with no scale for a page with no model', () => {
|
||||
expect(riskScales([])).toEqual([]);
|
||||
expect(riskScales([{ text: 'M', predictions: [at(5, 0.1)] }]).map((s) => s.label)).toEqual([
|
||||
'M, riesgo inmediato',
|
||||
'M, riesgo a 5 años',
|
||||
'M, probabilidad inmediata',
|
||||
'M, probabilidad a 5 años',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
+143
-12
@@ -21,7 +21,7 @@ export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(mo
|
||||
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
|
||||
return models.flatMap((m) =>
|
||||
[0, 5].map((years) => ({
|
||||
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`,
|
||||
label: `${m.text.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad'))}, probabilidad ${years ? 'a 5 años' : 'inmediata'}`,
|
||||
risk: m.predictions.find((p) => p.years === years),
|
||||
})),
|
||||
);
|
||||
@@ -48,24 +48,78 @@ export interface RiskGroup {
|
||||
title?: string;
|
||||
scenario?: string;
|
||||
index?: string;
|
||||
survival?: boolean;
|
||||
inputs?: Record<string, unknown>;
|
||||
/** the model and version that scored her, and the day it did */
|
||||
model?: string;
|
||||
evaluated?: string;
|
||||
scales: { label: string; risk?: Prediction }[];
|
||||
}
|
||||
|
||||
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
|
||||
export function survivalGroups(
|
||||
models: {
|
||||
index: string;
|
||||
predictions: Prediction[];
|
||||
scenarios?: string[];
|
||||
inputs?: Record<string, unknown>;
|
||||
text?: string;
|
||||
evaluated?: string;
|
||||
}[],
|
||||
): RiskGroup[] {
|
||||
return models
|
||||
.map((m) => ({
|
||||
title: 'Supervivencia',
|
||||
index: m.index,
|
||||
survival: true,
|
||||
inputs: m.inputs,
|
||||
model: m.text,
|
||||
evaluated: m.evaluated,
|
||||
scenario: m.scenarios?.join(' · '),
|
||||
scales: m.predictions.flatMap((p) => {
|
||||
const v = horizon(m.predictions, p.years);
|
||||
return v
|
||||
? [
|
||||
{
|
||||
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
|
||||
risk: {
|
||||
years: p.years,
|
||||
p: 1 - v.p,
|
||||
low: v.high === undefined ? undefined : 1 - v.high,
|
||||
high: v.low === undefined ? undefined : 1 - v.low,
|
||||
},
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
}))
|
||||
.filter((g) => g.scales.length);
|
||||
}
|
||||
|
||||
const HORIZONS: [number, string][] = [
|
||||
[0, 'Riesgo inmediato (al índice)'],
|
||||
[5, 'Riesgo a 5 años'],
|
||||
[0, 'Probabilidad inmediata (al índice)'],
|
||||
[5, 'Probabilidad a 5 años'],
|
||||
];
|
||||
|
||||
/** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */
|
||||
export function titleParts(text: string): { title: string; scenario?: string } {
|
||||
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
|
||||
return { title, scenario };
|
||||
return {
|
||||
title: title.replace(/riesgo/gi, (word) => (word[0] === 'R' ? 'Probabilidad' : 'probabilidad')),
|
||||
scenario,
|
||||
};
|
||||
}
|
||||
|
||||
/** The scales the page draws: both horizons of every model, or, with no model, both horizons
|
||||
* unavailable. */
|
||||
export function riskGroups(
|
||||
models: { text: string; index: string; predictions: Prediction[] }[],
|
||||
models: {
|
||||
text: string;
|
||||
index: string;
|
||||
predictions: Prediction[];
|
||||
inputs?: Record<string, unknown>;
|
||||
evaluated?: string;
|
||||
}[],
|
||||
): RiskGroup[] {
|
||||
const scales = (predictions: Prediction[]) =>
|
||||
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
|
||||
@@ -73,6 +127,9 @@ export function riskGroups(
|
||||
? models.map((m) => ({
|
||||
...titleParts(m.text),
|
||||
index: m.index,
|
||||
inputs: m.inputs,
|
||||
model: m.text,
|
||||
evaluated: m.evaluated,
|
||||
scales: scales(m.predictions),
|
||||
}))
|
||||
: [{ scales: scales([]) }];
|
||||
@@ -85,9 +142,6 @@ export function riskGroups(
|
||||
selector: 'app-risk-scales',
|
||||
imports: [DecimalPipe],
|
||||
template: `
|
||||
@if (groups().length) {
|
||||
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
|
||||
}
|
||||
@for (g of groups(); track $index) {
|
||||
@if (g.title) {
|
||||
<h3>{{ g.title }}</h3>
|
||||
@@ -105,7 +159,7 @@ export function riskGroups(
|
||||
· No disponible
|
||||
}
|
||||
</p>
|
||||
<div class="risk-plot" [class.unavailable]="!s.risk">
|
||||
<div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
|
||||
<div class="risk-line" aria-hidden="true"></div>
|
||||
@if (s.risk; as r) {
|
||||
@if (r.low !== undefined && r.high !== undefined) {
|
||||
@@ -134,12 +188,55 @@ export function riskGroups(
|
||||
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
|
||||
</p>
|
||||
}
|
||||
@if (g.title && !g.survival) {
|
||||
<section>
|
||||
<h4>Factores de riesgo considerados</h4>
|
||||
@if (g.inputs) {
|
||||
<dl>
|
||||
@for (item of entries(g.inputs); track item[0]) {
|
||||
<div>
|
||||
<dt>{{ inputName(item[0]) }}</dt>
|
||||
<dd>{{ inputValue(item[0], item[1]) }}</dd>
|
||||
</div>
|
||||
}
|
||||
</dl>
|
||||
} @else {
|
||||
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
@if (g.model) {
|
||||
<details data-section="metodos">
|
||||
<summary>Métodos</summary>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>Modelo y versión</dt>
|
||||
<dd>{{ g.model }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Fecha índice</dt>
|
||||
<dd>{{ g.index }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Fecha de evaluación</dt>
|
||||
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Covariables</dt>
|
||||
<dd>
|
||||
@for (item of entries(g.inputs ?? {}); track item[0]) {
|
||||
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
|
||||
} @empty {
|
||||
No disponibles para esta estimación.
|
||||
}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
.note {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.risk-scale {
|
||||
margin: 8px 0 14px;
|
||||
max-width: 740px;
|
||||
@@ -170,6 +267,15 @@ export function riskGroups(
|
||||
#fff 25%
|
||||
);
|
||||
}
|
||||
.survival .risk-line {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
#c24269 0 25%,
|
||||
#df8640 25% 50%,
|
||||
#a8c243 50% 75%,
|
||||
#42a77e 75% 100%
|
||||
);
|
||||
}
|
||||
.risk-interval {
|
||||
border-left: 2px solid #17324d;
|
||||
border-right: 2px solid #17324d;
|
||||
@@ -216,4 +322,29 @@ export function riskGroups(
|
||||
})
|
||||
export class RiskScales {
|
||||
readonly groups = input.required<RiskGroup[]>();
|
||||
protected readonly entries = Object.entries;
|
||||
protected readonly inputName = (name: string) =>
|
||||
(
|
||||
({
|
||||
age_group: 'Edad al diagnóstico',
|
||||
cytology: 'Citología',
|
||||
hpv: 'VPH',
|
||||
hpv_positive: 'VPH',
|
||||
hpv_16_18: 'VPH 16/18',
|
||||
referral_grade: 'Citología de referencia',
|
||||
bethesda: 'Citología',
|
||||
hpv_16: 'VPH 16',
|
||||
hpv_18: 'VPH 18',
|
||||
}) as Record<string, string>
|
||||
)[name] ?? name;
|
||||
protected readonly inputValue = (name: string, value: unknown) => {
|
||||
if (value === null || value === undefined) return 'No documentado';
|
||||
if (name === 'referral_grade' && (value === 'high' || value === 'low'))
|
||||
return value === 'high' ? 'Alto grado' : 'Bajo grado';
|
||||
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
|
||||
return value ? 'Positivo' : 'Negativo';
|
||||
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
|
||||
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
|
||||
return String(value);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ describe('risk series', () => {
|
||||
],
|
||||
});
|
||||
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', outcome: 'CIN3+' })).toBe('NCI, CIN3+');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Component, computed, input, signal } from '@angular/core';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import type { Parameters, ParametersParameter } from 'fhir/r4';
|
||||
import { Plot } from '../plot';
|
||||
import { CurveChooser } from './curve-chooser';
|
||||
import { curveFigure } from './risk-curve';
|
||||
|
||||
export interface SeriesPoint {
|
||||
@@ -29,7 +28,11 @@ const OUTCOME_TEXT: Record<string, string> = {
|
||||
cancer: 'Cáncer',
|
||||
};
|
||||
|
||||
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).replace(' (CIN2+)', '');
|
||||
// the platform's own models are the hospital's
|
||||
return `${s.source === 'Institucional' ? 'ISSSTELEON' : s.source}, ${outcome}`;
|
||||
};
|
||||
|
||||
/** The series of the answer. A value absent from it stays absent. */
|
||||
export function parseSeries(answer: Parameters): Series[] {
|
||||
@@ -56,25 +59,11 @@ export function parseSeries(answer: Parameters): Series[] {
|
||||
/** The chosen series as curves. Series are shown side by side; no difference is computed. */
|
||||
@Component({
|
||||
selector: 'app-risk-series',
|
||||
imports: [MatCheckboxModule, Plot],
|
||||
imports: [CurveChooser],
|
||||
template: `
|
||||
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
|
||||
<div class="choices">
|
||||
@for (s of available(); track s.id) {
|
||||
<mat-checkbox [checked]="chosen().has(s.id)" (change)="toggle(s.id)">
|
||||
{{ name(s) }}
|
||||
</mat-checkbox>
|
||||
}
|
||||
</div>
|
||||
@if (selected().length) {
|
||||
@for (s of selected(); track s.id) {
|
||||
@for (assumption of s.assumptions; track assumption) {
|
||||
<p class="muted">{{ name(s) }}: {{ assumption }}</p>
|
||||
}
|
||||
}
|
||||
<app-plot [figure]="figure()" [height]="340" />
|
||||
}
|
||||
@if (!available().length) {
|
||||
@if (available().length) {
|
||||
<app-curve-chooser [choices]="choices()" [draw]="draw()" [notes]="assumptions()" />
|
||||
} @else {
|
||||
<p class="muted">No disponible: datos insuficientes.</p>
|
||||
}
|
||||
`,
|
||||
@@ -82,48 +71,43 @@ export function parseSeries(answer: Parameters): Series[] {
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
.choices {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class RiskSeries {
|
||||
readonly series = input.required<Series[]>();
|
||||
protected readonly name = seriesName;
|
||||
protected readonly available = computed(() => this.series().filter((s) => s.points.length));
|
||||
/** what the user toggled away from the default (the institutional series) */
|
||||
private readonly toggled = signal(new Set<string>());
|
||||
protected readonly chosen = computed(
|
||||
() =>
|
||||
new Set(
|
||||
this.available()
|
||||
.filter((s) => (s.source === 'Institucional') !== this.toggled().has(s.id))
|
||||
.map((s) => s.id),
|
||||
),
|
||||
/** the platform's own series and the NCI master table's CIN2+ and CIN3+ are drawn until the
|
||||
* user says otherwise */
|
||||
protected readonly choices = computed(() =>
|
||||
this.available().map((s) => ({
|
||||
id: s.id,
|
||||
name: seriesName(s),
|
||||
on: s.source === 'Institucional' || ['nci-master-CIN2+', 'nci-master-CIN3+'].includes(s.id),
|
||||
})),
|
||||
);
|
||||
protected readonly selected = computed(() =>
|
||||
this.available().filter((s) => this.chosen().has(s.id)),
|
||||
);
|
||||
protected readonly figure = computed(() => {
|
||||
const shown = this.selected().map((s) => ({
|
||||
model: s.id,
|
||||
text: seriesName(s),
|
||||
index: '',
|
||||
predictions: s.points,
|
||||
}));
|
||||
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
|
||||
const figure = curveFigure(shown, top);
|
||||
// sources do not share an index date: the axis says only the horizon
|
||||
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
|
||||
return figure;
|
||||
private readonly among = computed(() => {
|
||||
const all = this.available();
|
||||
return (ids: Set<string>) => all.filter((s) => ids.has(s.id));
|
||||
});
|
||||
/** what the chosen series assume, each said once */
|
||||
protected readonly assumptions = computed(() => {
|
||||
const chosen = this.among();
|
||||
return (ids: Set<string>) => [...new Set(chosen(ids).flatMap((s) => s.assumptions))];
|
||||
});
|
||||
protected readonly draw = computed(() => {
|
||||
const chosen = this.among();
|
||||
return (ids: Set<string>) => {
|
||||
const shown = chosen(ids).map((s) => ({
|
||||
model: s.id,
|
||||
text: seriesName(s),
|
||||
index: '',
|
||||
predictions: s.points,
|
||||
}));
|
||||
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
|
||||
const figure = curveFigure(shown, top);
|
||||
// sources do not share an index date: the axis says only the horizon
|
||||
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
|
||||
return figure;
|
||||
};
|
||||
});
|
||||
|
||||
protected toggle(id: string) {
|
||||
const next = new Set(this.toggled());
|
||||
if (!next.delete(id)) next.add(id);
|
||||
this.toggled.set(next);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)',
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
|
||||
export class Plot implements OnDestroy {
|
||||
readonly figure = input.required<Figure>();
|
||||
readonly height = input(320);
|
||||
/** Plotly's buttons over the chart; a record's curves go without them */
|
||||
readonly toolbar = input(true);
|
||||
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const { data, layout } = this.figure();
|
||||
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG);
|
||||
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
|
||||
...CONFIG,
|
||||
...(this.toolbar() ? {} : { displayModeBar: false }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user