Compare commits

...

63 Commits

Author SHA1 Message Date
edgar 0fe772ed6f Describir los motivos de exclusión de la referencia 2026-12-03 17:12:03 -06:00
Angel Capetillo Zavala 63f6e16d19 Clarify CaCu and CaMa chart labels 2026-12-03 15:18:22 -06:00
Angel Capetillo Zavala d38c795c8a Hide the CaMa diagnosis-to-treatment card until the indicator is defined
The card read "Indicador no disponible" and the route listed a step with no
measure. Both are removed from the CaMa summary, and the opportunity grid sizes
its columns to the cards it has so the remaining ones fill the row.
2026-12-03 11:00:55 -06:00
Angel Capetillo Zavala 3bff3d5e3f Añadir exportaciones de CaMa y conservar los filtros aplicados 2026-12-03 10:23:42 -06:00
edgar 4ec071332d Usar un solo selector de curvas para riesgo y supervivencia 2026-12-03 07:31:12 -06:00
edgar 5a82dc780e Elegir los ajustes de supervivencia que se comparan 2026-12-03 07:30:01 -06:00
edgar db74a19439 Dibujar todos los ajustes de supervivencia en la ficha 2026-12-03 07:28:48 -06:00
edgar 24415b79b6 Quitar la barra de Plotly en las curvas de la ficha 2026-12-03 00:24:50 -06:00
edgar b43c89befd Decir una sola vez el supuesto de la referencia NCI 2026-12-03 00:18:28 -06:00
edgar 9c17a383d1 Usar barras comunes en confirmación y renombrar la serie de ingreso del NCI 2026-12-03 00:06:32 -06:00
edgar 8e16de33b7 Mostrar tabla de valores de supervivencia 2026-12-02 23:44:28 -06:00
edgar 5d660b7043 Mostrar confirmación con intervalo en barra y ajustar etiquetas de la ficha 2026-12-02 23:43:18 -06:00
edgar a3a100450b Mostrar supervivencia con su curva de combinación y métodos por estimación 2026-12-02 23:20:51 -06:00
edgar a92515eb4d Mostrar factores usados en cada estimación 2026-12-02 23:13:59 -06:00
edgar 5f92c49ed4 Mostrar escalas de supervivencia publicadas 2026-12-02 23:00:06 -06:00
edgar a22ce12067 Mostrar solo curvas de probabilidad disponibles 2026-12-02 22:53:44 -06:00
edgar a19874438b Ajustar resumen y ocultar series no disponibles 2026-12-02 22:50:30 -06:00
edgar c08a0b8874 Ajustar pestañas y etiquetas de días 2026-12-02 21:54:54 -06:00
edgar 5201340a13 Aclarar etiquetas de días en indicadores CaCu 2026-12-02 21:50:01 -06:00
edgar cca9517b7c Conservar la exclusión por histerectomía cuando la API no la reporta 2026-12-02 20:26:14 -06:00
edgar 3693991772 Renombrar tasas de confirmación histopatológica 2026-12-02 20:23:32 -06:00
edgar e49dde10e7 Distinguir diagnósticos en la ruta de tamizaje 2026-12-02 20:19:36 -06:00
edgar 2dec5af826 Distinguir tiempos de diagnóstico en indicadores 2026-12-02 20:19:36 -06:00
edgar 0316966374 Ajustar la prueba de las escalas al título sin versión 2026-12-02 19:43:55 -06:00
edgar 3d72c153c5 Ficha: quitar la nota de las etapas de la citología 2026-12-02 19:42:55 -06:00
edgar 422b408e37 Ficha: quitar la procedencia del formulario de citología 2026-12-02 19:42:53 -06:00
edgar 211f02edad Ficha: mostrar el VPH como estudio aparte 2026-12-02 19:42:51 -06:00
edgar 32b879edd2 Ficha: mostrar la tabla de modelos como desplegable 2026-12-02 19:42:48 -06:00
edgar 9726d6faa3 Ficha: quitar el texto de las curvas de probabilidad 2026-12-02 19:42:46 -06:00
edgar bafd6760d4 Ficha: llevar la comparación y sus filtros a las curvas de probabilidad 2026-12-02 19:42:43 -06:00
edgar 0666ce3077 Ficha: no mostrar la comparación de riesgos de referencia 2026-12-02 19:42:41 -06:00
edgar d2eada9385 Ficha: titular cada riesgo por su desenlace y llevar el escenario al pie 2026-12-02 19:42:38 -06:00
edgar 0d458818b5 Ficha: dibujar el intervalo sobre la escala y llevar la fecha índice al pie 2026-12-02 19:42:36 -06:00
edgar 2970ce16b0 Ficha: quitar el título Riesgos y recomendaciones 2026-12-02 19:42:33 -06:00
Angel Capetillo Zavala a43cf4b51b Distinguir ausencias e insuficiencia en supervivencia CaCu 2026-12-02 19:26:50 -06:00
edgar a4cc80fbe2 Mostrar la elegibilidad CaCu solo cuando la paciente no es elegible 2026-12-02 19:04:00 -06:00
Angel Capetillo Zavala 370da43695 Agregar elegibilidad CaCu por escenario clínico 2026-12-02 18:47:09 -06:00
edgar f7fdab950a Comparar series de riesgo seleccionables en la ficha CaCu 2026-12-02 18:24:33 -06:00
edgar 1260e0ff2a Mostrar métodos y escenarios sin curva en la supervivencia de la ficha 2026-12-02 18:14:19 -06:00
Angel Capetillo Zavala 09e5f4dd34 CaCu record: grouped NCI comparison, Spanish outcome names, survival texts and risk-only scales
The NCI comparison shows the reference once per horizon and one block per model, saying the
reasons that every incompatible comparison shares only once. Outcome names are translated for
display only (the API identifiers stay), and the reference outcome is read from the answer.
The CaCu survival card is titled as survival and states that its curves estimate the clinical
scenario's group, not an individual. Survival and recurrence estimates no longer feed the risk
scales, curves, probability table or PDF.
2026-12-02 17:48:03 -06:00
Angel Capetillo Zavala f119ba048a Simplify CaCu distribution descriptions 2026-12-02 14:09:02 -06:00
edgar 9ae8254dee Mostrar el motivo de exclusión en la ficha CaCu 2026-12-02 09:35:25 -06:00
Angel Capetillo Zavala b9e210d825 Merge the CaMa diagnostic pathway and biopsy results into the CaCu rounds, record and risk work 2026-12-01 19:02:02 -06:00
Angel Capetillo Zavala 652fd45c29 CaCu record: the NCI reference comparison section and probability curves at the published horizons 2026-12-01 18:32:11 -06:00
Angel Capetillo Zavala 8fc06038fb CaCu record: stages with states and sources, segmented risk scales, antecedents and collapsible findings 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala e1e8da6093 CaCu indicators: one selector for the cytology and HPV genotype views, grouped bars and genotype labels 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala 81894a3777 CaCu: show screening rounds and restore category palettes 2026-12-01 14:22:23 -06:00
Angel Capetillo Zavala 749afe765d CaMa: present diagnostic pathway and biopsy results 2026-12-01 12:27:16 -06:00
Roberto Treviño fe4dd55452 CaCu's page by readings, screening stages, ages and exports 2026-11-30 23:31:58 -06:00
Roberto Treviño 053679c817 Connecting a database no longer freezes the page: the columns field keeps one empty list 2026-11-30 05:17:14 -06:00
Roberto Treviño ffa732df12 The page test follows the pages as they are 2026-11-30 02:14:16 -06:00
Roberto Treviño 786b199203 The generated API client matches the API 2026-11-29 21:15:12 -06:00
Roberto Treviño ca887c29ab Wording: formal, precise, no narrative; the missing reports of a promotion in Spanish 2026-11-29 15:24:25 -06:00
Roberto Treviño bb506c3926 Conectar: Configuración and Avanzado tabs, rows instead of JSON, field titles as keys, captions that fit their nodes 2026-11-29 15:24:24 -06:00
Roberto Treviño b48c025400 Page test: no overlapping, clipped or wrapped labels at 1440 and 820 px 2026-11-29 12:39:07 -06:00
Roberto Treviño a93cd71126 Cosmetic pass: legends above plots, readable hovers and ticks, KPI qualifiers, a header that never wraps 2026-11-29 12:39:07 -06:00
Roberto Treviño 979b7cf34d Gobernanza: the header's domain switcher, model titles, confirmations, a stop button, an upload button 2026-11-29 12:39:07 -06:00
Roberto Treviño cde9b1cfb1 Revisión: documents no route recognises; reasons and fields in Spanish 2026-11-29 12:39:07 -06:00
Roberto Treviño edc32af67e CaMa record as the old card: summary, mammography, histopathology, prognosis, risk of death and its scenarios' risk factors 2026-11-29 12:39:07 -06:00
Roberto Treviño 2216186d26 Patient lists have a search box; TEA alterations by their Spanish names 2026-11-29 12:39:07 -06:00
Roberto Treviño 55c4e0b173 OpenAPI client: model titles, run termination, Patient name and identifier 2026-11-29 12:39:07 -06:00
Roberto Treviño 52cca0a84c Record history shows only ICD-10 codes beside a diagnosis 2026-11-29 07:13:57 -06:00
Roberto Treviño 7e50ff9b90 OpenAPI spec names the configured promotion reports and CaMa's history 2026-11-29 06:58:38 -06:00
112 changed files with 12866 additions and 665 deletions
+343
View File
@@ -0,0 +1,343 @@
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
const ROUND = { name: 'Por detección inicial y subsecuente' };
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
const VIEWS = ['General', 'Por grupo de edad', 'Por estatus de seguimiento', ROUND.name];
const TITLES = {
cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
};
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page,
}) => {
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Tasa de confirmación histopatológica de referencia a colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por ventana de tiempo', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
// one selector for the cytology distribution and the HPV by genotype; the biopsy card is apart
await expect(
tab.locator('app-readings', {
has: page.getByRole('heading', { name: 'Pacientes evaluadas por resultado de VPH' }),
}),
).toHaveCount(0);
const views = tab.getByRole('radiogroup', { name: VIEWS_LABEL });
await expect(views.getByRole('radio')).toHaveText(VIEWS);
await expect(views.getByRole('radio', { name: 'General' })).toBeChecked();
await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
for (const view of VIEWS.slice(1)) {
await views.getByRole('radio', { name: view }).click();
for (const card of [TITLES.cytology, TITLES.genotype]) {
const readings = tab.locator('app-readings', {
has: page.getByRole('heading', { name: card }),
});
// each card has no toggle of its own: the selector drives both
await expect(readings.getByRole('radio')).toHaveCount(0);
// no long description beside the bars: the cards read from their title, note and legend
await expect(readings).not.toContainText(
/Cada barra|Cada paciente cuenta una vez|«Detección inicial»|una barra vacía|«Positivo»/,
);
await expect(
readings
.locator('.group')
.first()
.or(readings.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
}
}
const biopsyCard = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.biopsy }),
});
await expect(biopsyCard.getByRole('radio')).toHaveCount(0);
await views.getByRole('radio', { name: 'General' }).click();
await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: TITLES.cytology }) })
.getByRole('table'),
).toBeVisible();
// the PPV cards keep their round tab, in the same words and order
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.colposcopy }),
});
await colposcopy.getByRole('radio', ROUND).click();
await expect(
colposcopy
.getByRole('table', ROUND)
.or(colposcopy.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.ppvBiopsy }),
})
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de 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();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried on top of the API's own answers. They show how the page draws them, not the
// backend. The shared selector drives the cytology and the HPV-by-genotype cards; the PPV cards keep a tab.
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
const GENOTYPE_COLOURS = {
Negativo: '#42A77E',
'VPH 16': '#DF8640',
'VPH 18': '#C29C42',
'VPH 16 y 18': '#C24269',
Positivo: '#A8C243',
};
const CYTOLOGY_COLOURS = {
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const view = async (name: string) => {
await tab.getByRole('radiogroup', { name: VIEWS_LABEL }).getByRole('radio', { name }).click();
};
/** A PPV card on its round tab. */
const ppv = async (key: 'colposcopy' | 'ppvBiopsy') => {
await tab
.getByRole('radio', { name: key === 'colposcopy' ? 'Colposcopía' : 'Biopsia', exact: true })
.click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, card, view, ppv };
}
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first();
/** The groups of a card as the page draws them: "label<br>unit: N", the width of the first bar and the colour of
* each category (the first group's rows), in hex. */
const traces = (readings: Locator) =>
readings.evaluate((el) => {
const hex = (rgb: string) =>
'#' +
(rgb.match(/\d+/g) ?? [])
.slice(0, 3)
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const groups = [...el.querySelectorAll('.group')];
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>${g.querySelector('.n')!.textContent!.trim()}`,
),
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries(
[...groups[0].querySelectorAll('.row')].map((r) => [
r.querySelector('.name')!.textContent!.trim(),
hex(getComputedStyle(r.querySelector('.fill')!).backgroundColor),
]),
),
};
});
for (const key of ['colposcopy', 'ppvBiopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'as-is');
const readings = await ppv(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'no-initial');
const readings = await ppv(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'unpublished');
const readings = await ppv(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
for (const card of ['cytology', 'genotype'] as const) {
test(`rondas (simulado) ${card}: the selector draws the rounds in order, with the category colours`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'as-is');
await view(ROUND.name);
const readings = of(TITLES[card]);
await expect(plotOf(readings)).toBeVisible();
const found = await traces(readings);
expect(found.y.map((l) => l.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(found.colours).toMatchObject(card === 'cytology' ? CYTOLOGY_COLOURS : GENOTYPE_COLOURS);
});
test(`rondas (simulado) ${card}: an empty initial group is an empty bar with its zero`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name);
const found = await traces(of(TITLES[card]));
expect(found.y[0]).toBe('Detección inicial<br>Pacientes: 0');
expect(found.x[0]).toBe(0);
});
test(`rondas (simulado) ${card}: without the stratum the selector says it is not available`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'unpublished');
await view(ROUND.name);
await expect(of(TITLES[card])).toContainText('No disponible');
});
}
test('rondas (simulado): the genotype card never shows the incomplete positives, and carries no long description', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).not.toContainText('«Positivo»');
await expect(readings).not.toContainText('Cada barra');
await expect(readings.getByRole('rowheader')).not.toContainText([
'Otro de alto riesgo',
'incompleto',
]);
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim())).toEqual([
'Negativo',
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo sin genotipo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
const found = await traces(readings);
expect(Object.keys(found.colours)).toEqual(Object.keys(GENOTYPE_COLOURS));
}
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the shared selector on each view lays out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { view, ppv } = await withRounds(page, 'as-is');
for (const name of VIEWS) {
await view(name);
await page.waitForTimeout(1200);
// every option of the selector is inside the window (it wraps on a narrow screen)
for (const box of await page
.getByRole('radiogroup', { name: VIEWS_LABEL })
.getByRole('radio')
.evaluateAll((els) =>
els.map((e) => e.closest('mat-button-toggle')!.getBoundingClientRect().right),
))
expect(box).toBeLessThanOrEqual(width);
expect(await layoutProblems(page), name).toEqual([]);
}
await ppv('colposcopy');
await ppv('ppvBiopsy');
await page.waitForTimeout(1200);
expect(await layoutProblems(page)).toEqual([]);
});
}
+386
View File
@@ -0,0 +1,386 @@
import { expect, type Page, test } from '@playwright/test';
import { strFromU8, unzipSync } from 'fflate';
import { readFileSync } from 'node:fs';
// Exports of CaMa (the follow-up list as Excel and PDF, the record as PDF), and CaCu's still working.
// The contents are checked by the unit tests of their builders; here the real downloads are checked:
// the file's name and format, and for the filter regression the exported rows and query.
// "(simulado)" tests rewrite the API's answers in the browser to reach what the synthetic data lack.
const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
const SHOTS = process.env['SHOTS_DIR'];
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
async function saved(page: Page, click: () => Promise<unknown>) {
const [download] = await Promise.all([page.waitForEvent('download'), click()]);
const file = await download.path();
return { name: download.suggestedFilename(), bytes: readFileSync(file!) };
}
const isPdf = (b: Buffer) => b.subarray(0, 4).toString() === '%PDF';
const isXlsx = (b: Buffer) => b.subarray(0, 2).toString() === 'PK'; // a zip container
async function followUp(page: Page, domain: 'cama' | 'cacu') {
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('table.worklist tbody tr').first().waitFor({ timeout: 120_000 });
}
function workbookSheets(bytes: Buffer) {
const parts = unzipSync(bytes);
const strings = [
...strFromU8(parts['xl/sharedStrings.xml']).matchAll(/<t(?: [^>]*)?>(.*?)<\/t>/gs),
].map((match) => match[1]);
return [1, 2].map((sheet) =>
[...strFromU8(parts[`xl/worksheets/sheet${sheet}.xml`]).matchAll(/<row\b[^>]*>(.*?)<\/row>/gs)]
.map((row) => [...row[1].matchAll(/<v>(\d+)<\/v>/g)].map((cell) => strings[Number(cell[1])])),
);
}
async function pdfText(bytes: Buffer) {
const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
const task = getDocument({ data: Uint8Array.from(bytes) });
try {
const document = await task.promise;
const text: string[] = [];
for (let n = 1; n <= document.numPages; n++) {
const { items } = await (await document.getPage(n)).getTextContent();
text.push(...items.flatMap((item) => ('str' in item ? [item.str] : [])));
}
return text.join(' ').replace(/\s+/g, ' ');
} finally {
await task.destroy();
}
}
for (const domain of ['cama', 'cacu'] as const) {
for (const format of ['xlsx', 'pdf'] as const) {
test(`exportación (${domain}, ${format}): conserva los filtros aplicados en todas las páginas`, async ({
page,
}) => {
const original = 'Paciente original';
const changed = 'Paciente distinto';
const cutoff = '2026-11-30';
const studyDate = '2026-09-15';
const patients = [`${original} Alfa`, `${original} Beta`];
const requests: URLSearchParams[] = [];
const pending = Promise.withResolvers<void>();
const resume = Promise.withResolvers<void>();
await page.route(
(url) => url.pathname === `/api/${domain}/fhir/Patient` && url.searchParams.has('follow-up-window'),
async (route) => {
const self = new URL(route.request().url());
const filters = self.searchParams;
filters.set('follow-up-cutoff', cutoff);
const exportPage = filters.get('_count') === '200';
const offset = Number(filters.get('_offset') ?? '0');
if (exportPage) {
requests.push(new URLSearchParams(filters));
if (offset === 0) {
pending.resolve();
await resume.promise;
}
}
const matched = filters.get('name') !== changed;
const link = [{ relation: 'self', url: self.href }];
if (matched && exportPage && offset === 0) {
const next = new URL(self);
next.searchParams.set('_offset', '1');
link.push({ relation: 'next', url: next.href });
}
await route.fulfill({
json: {
resourceType: 'Bundle',
type: 'searchset',
total: matched ? patients.length : 0,
link,
entry: matched
? patients.flatMap((name, index) => {
if (exportPage && index !== offset) return [];
const id = `patient-${index}`;
return [
{
search: { mode: 'match' },
resource: { resourceType: 'Patient', id, birthDate: '1980-01-01', name: [{ text: name }] },
},
{
search: { mode: 'include' },
resource: {
resourceType: 'DiagnosticReport',
id: `report-${index}`,
subject: { reference: `Patient/${id}` },
code: { coding: [{ code: domain === 'cama' ? 'mammography' : 'cervical_cytology' }] },
effectiveDateTime: studyDate,
extension: [{ url: EXT + 'report-date', valueDate: studyDate }],
},
},
];
})
: [],
},
});
},
);
await followUp(page, domain);
const search = page.locator('app-patient-search input');
const searchFor = async (text: string) => {
await search.fill(text);
await search.press('Enter');
};
if (domain === 'cacu') {
await page.locator('input[name=ageFrom]').fill('25');
await page.locator('input[name=ageTo]').fill('64');
}
const applied = page.waitForResponse((response) => {
const url = new URL(response.url());
return url.pathname === `/api/${domain}/fhir/Patient` && url.searchParams.get('name') === original;
});
await searchFor(original);
await applied;
await expect(page.locator('table.worklist tbody tr')).toHaveCount(2);
const button = page.getByRole('button', { name: format === 'xlsx' ? 'Exportar Excel' : 'Exportar PDF' });
const download = page.waitForEvent('download');
await button.click();
await Promise.race([pending.promise, download.then(() => { throw new Error('Export request was not held'); })]);
try {
await searchFor(changed);
await page.getByRole('combobox', { name: 'Ventana de meses' }).click();
await page.getByRole('option', { name: '1 mes', exact: true }).click();
if (domain === 'cacu') {
await page.locator('input[name=ageFrom]').fill('40');
await page.getByRole('combobox', { name: 'Horizonte de la probabilidad' }).click();
await page.getByRole('option', { name: '1 año', exact: true }).click();
}
await expect(page.getByText('No hay registros para los filtros aplicados.')).toBeVisible();
} finally {
resume.resolve();
}
const file = await download;
expect(file.suggestedFilename()).toBe(`seguimiento-${domain}.${format}`);
const bytes = readFileSync((await file.path())!);
expect(requests.map((params) => params.get('_offset') ?? '0')).toEqual(['0', '1']);
for (const params of requests) {
expect(params.get('name')).toBe(original);
expect(params.get('follow-up-window')).toBe('3');
expect(params.get('follow-up-cutoff')).toBe(cutoff);
if (domain === 'cacu') {
expect(params.getAll('birthdate')).toEqual(['le2001-11-30', 'gt1961-11-30']);
expect(params.get('risk-horizon')).toBe('5');
}
}
const metadata = [
['Ventana consultada', `2026-08-31 al ${cutoff}`],
['Búsqueda', original],
['Registros', '2'],
...(domain === 'cacu'
? [['Edad mínima', '25'], ['Edad máxima', '64'], ['Horizonte de la probabilidad (años)', '5']]
: []),
];
if (format === 'xlsx') {
const [results, query] = workbookSheets(bytes);
expect(results.slice(1).map((row) => row[0])).toEqual(patients);
expect(results.slice(1).every((row) => row.some((cell) => cell.includes(studyDate)))).toBe(true);
expect(query).toEqual(expect.arrayContaining(metadata));
expect(query.flat()).not.toContain(changed);
} else {
const text = await pdfText(bytes);
for (const value of [...patients, studyDate, ...metadata.map(([key, value]) => `${key}: ${value}`)]) {
expect(text).toContain(value);
}
expect(text).not.toContain(changed);
}
});
}
}
test('exportación (CaMa): the follow-up list is saved as Excel and PDF with as many rows as the page asked for', async ({
page,
}) => {
await followUp(page, 'cama');
const total = await page.locator('table.worklist tbody tr').count();
const excel = await saved(page, () =>
page.getByRole('button', { name: 'Exportar Excel' }).click(),
);
expect(excel.name).toBe('seguimiento-cama.xlsx');
expect(isXlsx(excel.bytes)).toBe(true);
const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click());
expect(pdf.name).toBe('seguimiento-cama.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
expect(pdf.bytes.length).toBeGreaterThan(5_000);
expect(total).toBeGreaterThan(0);
await expect(page.getByText('No se generó el archivo.')).toHaveCount(0);
});
test('exportación (CaMa): the buttons wait for a cut-off and an empty search still saves a file', async ({
page,
}) => {
await followUp(page, 'cama');
await page.locator('app-patient-search input').fill('zzzz-sin-coincidencias');
await page.keyboard.press('Enter');
await expect(page.getByText('No hay registros para los filtros aplicados.')).toBeVisible({
timeout: 60_000,
});
const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click());
expect(isPdf(pdf.bytes)).toBe(true);
});
test('exportación (CaMa): the record is saved as a PDF', async ({ page }) => {
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
const button = page.getByRole('button', { name: 'Exportar PDF' });
await expect(button).toBeVisible({ timeout: 120_000 });
const pdf = await saved(page, () => button.click());
expect(pdf.name).toBe('expediente-cama.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
expect(pdf.bytes.length).toBeGreaterThan(5_000);
});
test('exportación (CaMa, simulado): a record with published survival and recurrence estimates saves its PDF', async ({
page,
}) => {
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
const estimate = (id: string, method: string, model: string) => ({
resourceType: 'RiskAssessment',
id,
status: 'final',
method: { text: method, coding: [{ code: model }] },
occurrenceDateTime: '2026-02-01',
extension: [{ url: EXT + 'escenario-clinico', valueString: 'En observación' }],
prediction: [
{
whenRange: { high: { value: 0, unit: 'a', code: 'a' } },
probabilityDecimal: 0,
extension: [],
},
{
whenRange: { high: { value: 5, unit: 'a', code: 'a' } },
probabilityDecimal: 0.8,
extension: [
{ url: EXT + 'ic-bajo', valueDecimal: 0.7 },
{ url: EXT + 'ic-alto', valueDecimal: 0.9 },
],
},
],
});
await page.route('**/api/cama/fhir/RiskAssessment**', (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: [
estimate('s', 'Supervivencia v1', 'cama.survival'),
estimate('r', 'Recurrencia v1', 'cama.recurrence'),
].map((resource) => ({ resource })),
}),
}),
);
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
const button = page.getByRole('button', { name: 'Exportar PDF' });
await expect(button).toBeVisible({ timeout: 120_000 });
const pdf = await saved(page, () => button.click());
expect(isPdf(pdf.bytes)).toBe(true);
if (SHOTS)
(await import('node:fs')).writeFileSync(
`${SHOTS}/SIMULADO-expediente-cama-con-estimaciones.pdf`,
pdf.bytes,
);
});
test('exportación (CaCu): the list and the record still save their files', async ({ page }) => {
await followUp(page, 'cacu');
const excel = await saved(page, () =>
page.getByRole('button', { name: 'Exportar Excel' }).click(),
);
expect(excel.name).toBe('seguimiento-cacu.xlsx');
expect(isXlsx(excel.bytes)).toBe(true);
const pdf = await saved(page, () => page.getByRole('button', { name: 'Exportar PDF' }).click());
expect(pdf.name).toBe('seguimiento-cacu.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cacu/pacientes/${patients.entry[0].resource.id}`);
const record = await saved(page, async () => {
await page.getByRole('button', { name: 'Exportar PDF' }).click();
});
expect(record.name).toBe('expediente-cacu.pdf');
expect(isPdf(record.bytes)).toBe(true);
});
for (const width of [1440, 480]) {
test(`exportación (CaMa) at ${width} px: the record's PDF button sits in the header beside the name, never over it`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
const button = page.getByRole('button', { name: 'Exportar PDF' });
await expect(button).toBeVisible({ timeout: 120_000 });
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
// one button, in the header; the "Historial médico" card no longer holds it
await expect(button).toHaveCount(1);
await expect(
page.locator('.record-head').getByRole('button', { name: 'Exportar PDF' }),
).toHaveCount(1);
await expect(
page
.locator('mat-card', { has: page.getByText('Historial médico', { exact: true }) })
.getByRole('button', { name: 'Exportar PDF' }),
).toHaveCount(0);
const [title, action] = await Promise.all([
page.locator('.record-head h1').boundingBox(),
button.boundingBox(),
]);
const overlaps = !(
action!.x >= title!.x + title!.width ||
title!.x >= action!.x + action!.width ||
action!.y >= title!.y + title!.height ||
title!.y >= action!.y + action!.height
);
expect(overlaps).toBe(false);
if (width >= 1000) {
expect(action!.x + action!.width).toBeGreaterThan(width - 120); // at the right end
expect(
Math.abs(action!.y + action!.height / 2 - (title!.y + title!.height / 2)),
).toBeLessThan(30); // on the name's line
} else {
expect(action!.x + action!.width).toBeLessThanOrEqual(width);
}
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
if (SHOTS)
await page.screenshot({
path: `${SHOTS}/captura-cama-ficha-boton-${width}.png`,
fullPage: false,
});
const pdf = await saved(page, () => button.click());
expect(pdf.name).toBe('expediente-cama.pdf');
expect(isPdf(pdf.bytes)).toBe(true);
if (SHOTS)
(await import('node:fs')).writeFileSync(
`${SHOTS}/descarga-ficha-cama-${width}.pdf`,
pdf.bytes,
);
});
}
test('exportación (CaCu): the record button stays in its "Historial médico" card', async ({
page,
}) => {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=1')).json();
await page.goto(`/indicadores/cacu/pacientes/${patients.entry[0].resource.id}`);
const card = page.locator('mat-card', {
has: page.getByText('Historial médico', { exact: true }),
});
await expect(card.getByRole('button', { name: 'Exportar PDF' })).toBeVisible({
timeout: 120_000,
});
await expect(page.locator('.record-head').getByRole('button')).toHaveCount(0);
});
File diff suppressed because it is too large Load Diff
+122
View File
@@ -0,0 +1,122 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+107 -14
View File
@@ -1,5 +1,6 @@
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test'; import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */ /** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] { function watch(page: Page): string[] {
@@ -58,13 +59,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14); await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
const bundle = await (await list).json(); const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource; const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10); const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
@@ -72,7 +73,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(rows).toHaveCount(Math.min(20, bundle.total)); await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first); await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click(); await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(`21–`)).toBeVisible(); await expect(page.getByText('Página 2 de')).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click(); await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click(); await rows.first().locator('a').first().click();
@@ -84,13 +85,13 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await page.goto('/indicadores/cama'); await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr'); const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS'); await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea'); await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
expect(problems).toEqual([]); expect(problems).toEqual([]);
}); });
@@ -101,12 +102,17 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar'); await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click(); await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible(); await expect(page.locator('vflow')).toBeVisible();
await page.getByText('Fuente de datos · Patients').click(); // a node's caption: its kind, then its name
await expect(page.locator('formly-form')).toBeVisible(); // drawn by hand: its raw form await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click(); await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible(); await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows. // A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Traducir códigos · cytology', { exact: true }).click(); await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible(); await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect await expect
.poll(() => .poll(() =>
@@ -139,13 +145,13 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
}) => { }) => {
const problems = watch(page); const problems = watch(page);
await page.goto('/gobernanza/cama'); await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' }); const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible(); await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click(); await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible(); await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click(); await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('clinical_validation'); await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]); expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
}); });
@@ -171,7 +177,7 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible(); await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados'); await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click(); await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.getByText('Fuente de datos · Resultados')).toBeVisible(); await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace. // A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click(); await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it'); await page.locator('[data-field="password"]').fill('not-it');
@@ -200,10 +206,43 @@ const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <peri
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) { for (const domain of ['cacu', 'cama', 'tea']) {
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
await page.goto(`/indicadores/${domain}`);
await expect(page.getByRole('tab', { name: 'Análisis de Riesgo', exact: true })).toHaveCount(1);
await expect(page.getByRole('tab', { name: 'Trazabilidad', exact: true })).toHaveCount(1);
const labels = await page.getByRole('tab').allTextContents();
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
});
}
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page, page,
}) => { }) => {
const old = captured(domain); const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// 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;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatoló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;
await page.goto(`/indicadores/${domain}`); await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores'); const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
@@ -213,7 +252,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
const from = headings.indexOf('Indicadores de oportunidad'); const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual( expect(headings.slice(from).map(period)).toEqual(
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
); );
// Each figure drawn is one of the old kinds (a figure with no data in the period is named). // Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab const drawn = await tab
@@ -283,3 +322,57 @@ for (const domain of ['cacu', 'cama', 'tea']) {
).toBeVisible(); ).toBeVisible();
}); });
} }
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from '@playwright/test';
/** SIMULATED answers. The pages read the API's aggregated MeasureReports; these helpers pass them
* through the browser and rewrite the screening-round strata, so the cards can be tried with the
* groups the contract of `rebuild` allows (stratum `round`, crossed `round-category`) without
* loading data. They prove how the page draws such answers, not what the backend computes.
*
* - `as-is`: the answers untouched, with a stratum named `screening_round` renamed `round`.
* - `no-initial`: nobody is in the initial group (the group is absent and the totals drop).
* - `unclassified`: the initial group folds into "Sin dato" (what 5740's answers look like).
* - `unpublished`: the round strata are not in the answers. */
export type Simulation = 'as-is' | 'no-initial' | 'unclassified' | 'unpublished';
type Stratum = {
value?: { text?: string };
component?: { value?: { text?: string } }[];
population?: { code?: { coding?: { code?: string }[] }; count: number }[];
};
type Stratifier = { code?: { coding?: { code?: string }[] }[]; stratum?: Stratum[] };
const named = (s: Stratifier) => (s.code ?? []).map((c) => c.coding?.[0]?.code).join('-');
const label = (x: Stratum) => x.component?.[0]?.value?.text ?? x.value?.text;
const pop = (o: { population?: Stratum['population'] }, code: string) =>
o.population?.find((p) => p.code?.coding?.[0]?.code === code);
function fold(into: Stratum, from: Stratum) {
for (const p of from.population ?? []) {
const q = pop(into, p.code!.coding![0].code!);
if (q) q.count += p.count;
else (into.population ??= []).push(structuredClone(p));
}
}
export function simulate(report: any, how: Simulation) {
const group = report?.group?.[0];
if (!group) return report;
for (const s of group.stratifier ?? ([] as Stratifier[]))
for (const c of s.code ?? []) {
const k = c.coding?.[0];
if (k?.code === 'screening_round') k.code = 'round';
}
const rounds: Stratifier[] = (group.stratifier ?? []).filter((s: Stratifier) =>
['round', 'round-category'].includes(named(s)),
);
if (how === 'unpublished')
group.stratifier = (group.stratifier ?? []).filter((s: Stratifier) => !rounds.includes(s));
if (how === 'no-initial' || how === 'unclassified')
for (const s of rounds) {
const initial = (s.stratum ?? []).filter((x) => label(x) === 'initial');
const rest = (s.stratum ?? []).filter((x) => label(x) !== 'initial');
for (const x of initial) {
if (how === 'unclassified') {
const other = x.component?.[1]?.value?.text;
const target = rest.find(
(y) => label(y) === 'no_data' && (!other || y.component?.[1]?.value?.text === other),
);
if (target) fold(target, x);
else {
(x.component ? x.component[0].value! : x.value!).text = 'no_data';
rest.push(x);
}
} else if (named(s) === 'round') {
// the group vanishes and the period's total drops by its patients: a real zero
for (const p of x.population ?? []) {
const total = pop(group, p.code!.coding![0].code!);
if (total && p.code!.coding![0].code !== 'numerator')
total.count = Math.max(0, total.count - p.count);
}
}
}
s.stratum = rest;
}
return report;
}
/** Answers every CaCu MeasureReport search through `simulate`. */
export async function simulateRounds(page: Page, how: Simulation) {
await page.route('**/api/cacu/fhir/MeasureReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const entry of body.entry ?? []) simulate(entry.resource, how);
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
+596 -12
View File
@@ -292,6 +292,7 @@
"default": "identity", "default": "identity",
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -422,6 +423,7 @@
}, },
"default": {}, "default": {},
"description": "Dato \u2192 columna, sin leer el texto.", "description": "Dato \u2192 columna, sin leer el texto.",
"keys": "field",
"title": "Datos tomados de columnas", "title": "Datos tomados de columnas",
"type": "object" "type": "object"
}, },
@@ -442,6 +444,7 @@
"description": "Qu\u00e9 estudio se saca del documento.", "description": "Qu\u00e9 estudio se saca del documento.",
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -455,13 +458,74 @@
"eeg" "eeg"
], ],
"title": "Estudio", "title": "Estudio",
"type": "string" "type": "string",
"widget": {
"formlyConfig": {
"props": {
"options": [
{
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
},
{
"label": "Biopsia cervical",
"value": "cervical_biopsy"
},
{
"label": "Mastograf\u00eda",
"value": "mammography"
},
{
"label": "Biopsia de mama",
"value": "breast_biopsy"
},
{
"label": "Tratamiento de c\u00e1ncer de mama",
"value": "breast_treatment"
},
{
"label": "Recurrencia de c\u00e1ncer de mama",
"value": "breast_recurrence"
},
{
"label": "Nota m\u00e9dica",
"value": "clinical_note"
},
{
"label": "Defunci\u00f3n",
"value": "death"
},
{
"label": "M-CHAT-R/F",
"value": "mchat"
},
{
"label": "ADOS-2",
"value": "ados2"
},
{
"label": "Electroencefalograma",
"value": "eeg"
}
]
}
}
}
}, },
"formats": { "formats": {
"additionalProperties": { "additionalProperties": {
"type": "string" "type": "string"
}, },
"default": {}, "default": {},
"keys": "field",
"title": "Formatos de fecha", "title": "Formatos de fecha",
"type": "object" "type": "object"
}, },
@@ -535,6 +599,7 @@
}, },
"default": {}, "default": {},
"description": "Dato \u2192 expresi\u00f3n con un grupo ( ).", "description": "Dato \u2192 expresi\u00f3n con un grupo ( ).",
"keys": "field",
"title": "Patrones", "title": "Patrones",
"type": "object" "type": "object"
}, },
@@ -582,6 +647,7 @@
"entity": { "entity": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -595,7 +661,67 @@
"eeg" "eeg"
], ],
"title": "Estudio", "title": "Estudio",
"type": "string" "type": "string",
"widget": {
"formlyConfig": {
"props": {
"options": [
{
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
},
{
"label": "Biopsia cervical",
"value": "cervical_biopsy"
},
{
"label": "Mastograf\u00eda",
"value": "mammography"
},
{
"label": "Biopsia de mama",
"value": "breast_biopsy"
},
{
"label": "Tratamiento de c\u00e1ncer de mama",
"value": "breast_treatment"
},
{
"label": "Recurrencia de c\u00e1ncer de mama",
"value": "breast_recurrence"
},
{
"label": "Nota m\u00e9dica",
"value": "clinical_note"
},
{
"label": "Defunci\u00f3n",
"value": "death"
},
{
"label": "M-CHAT-R/F",
"value": "mchat"
},
{
"label": "ADOS-2",
"value": "ados2"
},
{
"label": "Electroencefalograma",
"value": "eeg"
}
]
}
}
}
}, },
"id": { "id": {
"maxLength": 40, "maxLength": 40,
@@ -705,7 +831,8 @@
"url", "url",
"oauth", "oauth",
"table", "table",
"format" "format",
"columns"
], ],
"title": "Type", "title": "Type",
"type": "string" "type": "string"
@@ -828,7 +955,7 @@
"type": "string" "type": "string"
}, },
"on": { "on": {
"description": "Pares [columna izquierda, derecha].", "description": "Columna de la primera entrada = columna de la segunda.",
"items": { "items": {
"maxItems": 2, "maxItems": 2,
"minItems": 2, "minItems": 2,
@@ -1003,6 +1130,7 @@
"type": "string" "type": "string"
}, },
"description": "Dato de la plataforma \u2192 columna del sitio.", "description": "Dato de la plataforma \u2192 columna del sitio.",
"keys": "field",
"title": "Campos", "title": "Campos",
"type": "object" "type": "object"
}, },
@@ -1012,6 +1140,7 @@
}, },
"default": {}, "default": {},
"description": "Por ejemplo %d/%m/%Y.", "description": "Por ejemplo %d/%m/%Y.",
"keys": "field",
"title": "Formatos de fecha", "title": "Formatos de fecha",
"type": "object" "type": "object"
}, },
@@ -1059,6 +1188,7 @@
}, },
"default": {}, "default": {},
"description": "Un dato igual para todas las filas.", "description": "Un dato igual para todas las filas.",
"keys": "field",
"title": "Valores fijos", "title": "Valores fijos",
"type": "object" "type": "object"
} }
@@ -1173,6 +1303,24 @@
"title": "Metric", "title": "Metric",
"type": "object" "type": "object"
}, },
"Model": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"title": {
"title": "Title",
"type": "string"
}
},
"required": [
"name",
"title"
],
"title": "Model",
"type": "object"
},
"Option": { "Option": {
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
@@ -1393,6 +1541,7 @@
"entity": { "entity": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -1692,12 +1841,14 @@
"properties": { "properties": {
"args": { "args": {
"additionalProperties": true, "additionalProperties": true,
"advanced": true,
"default": {}, "default": {},
"description": "Los de la fuente dlt.", "description": "Los de la fuente dlt.",
"title": "Argumentos (JSON)", "title": "Argumentos",
"type": "object" "type": "object"
}, },
"guided": { "guided": {
"advanced": true,
"anyOf": [ "anyOf": [
{ {
"$ref": "#/components/schemas/Guided" "$ref": "#/components/schemas/Guided"
@@ -1705,7 +1856,8 @@
{ {
"type": "null" "type": "null"
} }
] ],
"title": "Asistente"
}, },
"id": { "id": {
"maxLength": 40, "maxLength": 40,
@@ -1746,6 +1898,7 @@
] ]
}, },
"primary_key": { "primary_key": {
"advanced": true,
"default": [], "default": [],
"description": "Columnas que identifican una fila.", "description": "Columnas que identifican una fila.",
"items": { "items": {
@@ -1755,6 +1908,7 @@
"type": "array" "type": "array"
}, },
"resource": { "resource": {
"advanced": true,
"anyOf": [ "anyOf": [
{ {
"type": "string" "type": "string"
@@ -1767,12 +1921,14 @@
"title": "Recurso" "title": "Recurso"
}, },
"source": { "source": {
"advanced": true,
"description": "M\u00f3dulo:funci\u00f3n de la fuente dlt.", "description": "M\u00f3dulo:funci\u00f3n de la fuente dlt.",
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$", "pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
"title": "Fuente dlt", "title": "Fuente dlt",
"type": "string" "type": "string"
}, },
"then": { "then": {
"advanced": true,
"anyOf": [ "anyOf": [
{ {
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$", "pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
@@ -1973,6 +2129,7 @@
"description": "En qu\u00e9 estudio de la plataforma se guarda.", "description": "En qu\u00e9 estudio de la plataforma se guarda.",
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -1986,7 +2143,67 @@
"eeg" "eeg"
], ],
"title": "Estudio", "title": "Estudio",
"type": "string" "type": "string",
"widget": {
"formlyConfig": {
"props": {
"options": [
{
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
},
{
"label": "Biopsia cervical",
"value": "cervical_biopsy"
},
{
"label": "Mastograf\u00eda",
"value": "mammography"
},
{
"label": "Biopsia de mama",
"value": "breast_biopsy"
},
{
"label": "Tratamiento de c\u00e1ncer de mama",
"value": "breast_treatment"
},
{
"label": "Recurrencia de c\u00e1ncer de mama",
"value": "breast_recurrence"
},
{
"label": "Nota m\u00e9dica",
"value": "clinical_note"
},
{
"label": "Defunci\u00f3n",
"value": "death"
},
{
"label": "M-CHAT-R/F",
"value": "mchat"
},
{
"label": "ADOS-2",
"value": "ados2"
},
{
"label": "Electroencefalograma",
"value": "eeg"
}
]
}
}
}
}, },
"id": { "id": {
"maxLength": 40, "maxLength": 40,
@@ -3398,6 +3615,7 @@
}, },
"/models/{domain}": { "/models/{domain}": {
"get": { "get": {
"description": "The domain's registered models, with their names on screen.",
"operationId": "models", "operationId": "models",
"parameters": [ "parameters": [
{ {
@@ -3415,7 +3633,7 @@
"application/json": { "application/json": {
"schema": { "schema": {
"items": { "items": {
"type": "string" "$ref": "#/components/schemas/Model"
}, },
"title": "Response Models", "title": "Response Models",
"type": "array" "type": "array"
@@ -3645,7 +3863,7 @@
}, },
"/models/{domain}/{name}/versions/{version}/promote": { "/models/{domain}/{name}/versions/{version}/promote": {
"post": { "post": {
"description": "The version risk batches come from from now on; refused (409) without its three\nreports: technical validation, interpretability and clinical validation.", "description": "The version risk batches come from from now on; refused (409) without the reports\nthe site requires (PROMOTION_REPORTS; default: technical validation, interpretability\nand clinical validation).",
"operationId": "promote", "operationId": "promote",
"parameters": [ "parameters": [
{ {
@@ -3707,7 +3925,7 @@
}, },
"/models/{domain}/{name}/versions/{version}/reports/clinical_validation": { "/models/{domain}/{name}/versions/{version}/reports/clinical_validation": {
"post": { "post": {
"description": "The clinical team's validation of a version: the third report promotion needs.", "description": "The clinical team's validation of a version: the third report, which promotion needs\nunless the site left it out of PROMOTION_REPORTS.",
"operationId": "add_clinical_validation", "operationId": "add_clinical_validation",
"parameters": [ "parameters": [
{ {
@@ -3855,6 +4073,7 @@
"schema": { "schema": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -3963,6 +4182,7 @@
"schema": { "schema": {
"enum": [ "enum": [
"identity", "identity",
"cacu_eligibility_evidence",
"cervical_cytology", "cervical_cytology",
"cervical_biopsy", "cervical_biopsy",
"mammography", "mammography",
@@ -4263,6 +4483,53 @@
] ]
} }
}, },
"/runs/{run_id}/terminate": {
"post": {
"description": "Stop a run (one started by mistake): Dagster cancels it.",
"operationId": "terminate_run",
"parameters": [
{
"in": "path",
"name": "run_id",
"required": true,
"schema": {
"title": "Run Id",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Terminate Run",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Terminate Run",
"tags": [
"runs"
]
}
},
"/tea/eegs": { "/tea/eegs": {
"get": { "get": {
"operationId": "studies", "operationId": "studies",
@@ -4773,7 +5040,7 @@
}, },
"/{domain}/fhir/Condition": { "/{domain}/fhir/Condition": {
"get": { "get": {
"description": "What clinical notes diagnosed.", "description": "What clinical notes diagnosed (CaMa: and each recurrence).",
"operationId": "search_condition", "operationId": "search_condition",
"parameters": [ "parameters": [
{ {
@@ -5443,6 +5710,57 @@
"title": "Follow-Up-Status" "title": "Follow-Up-Status"
} }
}, },
{
"description": "each word starts a word of her name (case and accents ignored)",
"in": "query",
"name": "name",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "each word starts a word of her name (case and accents ignored)",
"title": "Name"
}
},
{
"description": "[system|]value: a CURP or record number (case ignored)",
"in": "query",
"name": "identifier",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "[system|]value: a CURP or record number (case ignored)",
"title": "Identifier"
}
},
{
"description": "gt, ge, lt or le and a day (2000-12-31)",
"in": "query",
"name": "birthdate",
"required": false,
"schema": {
"default": [],
"description": "gt, ge, lt or le and a day (2000-12-31)",
"items": {
"type": "string"
},
"title": "Birthdate",
"type": "array"
}
},
{ {
"description": "-recent or -risk-<outcome>", "description": "-recent or -risk-<outcome>",
"in": "query", "in": "query",
@@ -5608,9 +5926,275 @@
] ]
} }
}, },
"/{domain}/fhir/Patient/{id}/$eligibility": {
"get": {
"description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.",
"operationId": "cacu_eligibility",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Limit the report to one CaCu scenario",
"in": "query",
"name": "scenario",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Limit the report to one CaCu scenario",
"title": "Scenario"
}
},
{
"description": "Only index dates up to this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only index dates up to this day",
"title": "Cutoff"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Eligibility",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$reference-risk": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.",
"operationId": "reference_risk",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Reference Risk",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$risk-series": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.",
"operationId": "cacu_risk_series",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Risk Series",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Procedure": { "/{domain}/fhir/Procedure": {
"get": { "get": {
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments).", "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
"operationId": "search_procedure", "operationId": "search_procedure",
"parameters": [ "parameters": [
{ {
+577 -2
View File
@@ -25,9 +25,11 @@
"d3-zoom": "3.0.0", "d3-zoom": "3.0.0",
"material-symbols": "0.48.3", "material-symbols": "0.48.3",
"ngx-vflow": "2.7.0", "ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2", "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"tslib": "^2.3.0" "tslib": "^2.3.0",
"write-excel-file": "4.1.1"
}, },
"devDependencies": { "devDependencies": {
"@angular/build": "^22.3.0", "@angular/build": "^22.3.0",
@@ -38,9 +40,12 @@
"@types/d3-selection": "3.0.13", "@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9", "@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"vitest": "^5.0.0" "vitest": "^5.0.0"
@@ -2010,6 +2015,283 @@
"win32" "win32"
] ]
}, },
"node_modules/@napi-rs/canvas": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz",
"integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==",
"dev": true,
"license": "MIT",
"optional": true,
"workspaces": [
"e2e/*"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/canvas-android-arm64": "1.2.1",
"@napi-rs/canvas-darwin-arm64": "1.2.1",
"@napi-rs/canvas-darwin-x64": "1.2.1",
"@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1",
"@napi-rs/canvas-linux-arm64-gnu": "1.2.1",
"@napi-rs/canvas-linux-arm64-musl": "1.2.1",
"@napi-rs/canvas-linux-riscv64-gnu": "1.2.1",
"@napi-rs/canvas-linux-x64-gnu": "1.2.1",
"@napi-rs/canvas-linux-x64-musl": "1.2.1",
"@napi-rs/canvas-win32-arm64-msvc": "1.2.1",
"@napi-rs/canvas-win32-x64-msvc": "1.2.1"
}
},
"node_modules/@napi-rs/canvas-android-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz",
"integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-arm64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz",
"integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-darwin-x64": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz",
"integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz",
"integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz",
"integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz",
"integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz",
"integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==",
"cpu": [
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz",
"integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-linux-x64-musl": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz",
"integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz",
"integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz",
"integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
"node_modules/@napi-rs/nice": { "node_modules/@napi-rs/nice": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/nice/-/nice-1.1.1.tgz",
@@ -2402,6 +2684,30 @@
"@ngx-formly/core": "11.2.0" "@ngx-formly/core": "11.2.0"
} }
}, },
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": { "node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.158.0", "version": "0.158.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz", "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
@@ -3465,6 +3771,12 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": { "node_modules/@tybys/wasm-util": {
"version": "0.10.5", "version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
@@ -3570,6 +3882,37 @@
"license": "MIT", "license": "MIT",
"peer": true "peer": true
}, },
"node_modules/@types/node": {
"version": "26.6.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/pdfkit": {
"version": "0.17.7",
"resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz",
"integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/pdfmake": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@types/pdfmake/-/pdfmake-0.3.5.tgz",
"integrity": "sha512-AQI4ISWzt7qmnKaipkikibz9x2XIvU/1zqfEHwKhBU7vP6oIhlGoLB9KsSIAryH7f9uuJebXScldb6F4ebwFxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/pdfkit": "*"
}
},
"node_modules/@types/plotly.js": { "node_modules/@types/plotly.js": {
"version": "3.0.15", "version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz", "resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
@@ -3816,6 +4159,15 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": { "node_modules/baseline-browser-mapping": {
"version": "2.11.39", "version": "2.11.39",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz",
@@ -3891,6 +4243,35 @@
"url": "https://github.com/sponsors/fb55" "url": "https://github.com/sponsors/fb55"
} }
}, },
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": { "node_modules/browserslist": {
"version": "4.29.6", "version": "4.29.6",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
@@ -4119,6 +4500,15 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1" "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
} }
}, },
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/colorjs.io": { "node_modules/colorjs.io": {
"version": "0.7.1", "version": "0.7.1",
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz", "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz",
@@ -4326,6 +4716,12 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": { "node_modules/dom-serializer": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
@@ -4561,7 +4957,6 @@
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-string-truncated-width": { "node_modules/fast-string-truncated-width": {
@@ -4626,6 +5021,12 @@
} }
} }
}, },
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/flru": { "node_modules/flru": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -4636,6 +5037,23 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/fs-extra": { "node_modules/fs-extra": {
"version": "11.4.1", "version": "11.4.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
@@ -5366,6 +5784,16 @@
"url": "https://opencollective.com/parcel" "url": "https://opencollective.com/parcel"
} }
}, },
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": { "node_modules/listr2": {
"version": "11.4.1", "version": "11.4.1",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz", "resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz",
@@ -5844,6 +6272,12 @@
"@oxc-parser/binding-win32-x64-msvc": "0.158.0" "@oxc-parser/binding-win32-x64-msvc": "0.158.0"
} }
}, },
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": { "node_modules/parse5": {
"version": "8.1.1", "version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
@@ -5922,6 +6356,47 @@
"url": "https://github.com/fb55/entities?sponsor=1" "url": "https://github.com/fb55/entities?sponsor=1"
} }
}, },
"node_modules/pdfjs-dist": {
"version": "6.5.438",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz",
"integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=22.13.0 || >=24"
},
"optionalDependencies": {
"@napi-rs/canvas": "^1.0.13"
}
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/pdfmake": {
"version": "0.3.14",
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
"license": "MIT",
"dependencies": {
"linebreak": "^1.1.0",
"pdfkit": "^0.20.2",
"xmldoc": "^2.0.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/picocolors": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -5990,6 +6465,14 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==", "integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.33", "version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6165,6 +6648,12 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": { "node_modules/rolldown": {
"version": "1.3.1", "version": "1.3.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz",
@@ -6663,6 +7152,15 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": { "node_modules/saxes": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -6852,6 +7350,12 @@
"node": ">=16.0.0" "node": ">=16.0.0"
} }
}, },
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": { "node_modules/tinybench": {
"version": "6.2.5", "version": "6.2.5",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
@@ -6979,6 +7483,53 @@
"node": ">=22.19.0" "node": ">=22.19.0"
} }
}, },
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/universalify": { "node_modules/universalify": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -7676,6 +8227,18 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1" "url": "https://github.com/chalk/ansi-styles?sponsor=1"
} }
}, },
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": { "node_modules/xml-name-validator": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -7693,6 +8256,18 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/xxhash-wasm": { "node_modules/xxhash-wasm": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+6 -1
View File
@@ -29,9 +29,11 @@
"d3-zoom": "3.0.0", "d3-zoom": "3.0.0",
"material-symbols": "0.48.3", "material-symbols": "0.48.3",
"ngx-vflow": "2.7.0", "ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2", "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"tslib": "^2.3.0" "tslib": "^2.3.0",
"write-excel-file": "4.1.1"
}, },
"devDependencies": { "devDependencies": {
"@angular/build": "^22.3.0", "@angular/build": "^22.3.0",
@@ -42,9 +44,12 @@
"@types/d3-selection": "3.0.13", "@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9", "@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"fflate": "0.8.3",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
"pdfjs-dist": "6.5.438",
"prettier": "^3.8.1", "prettier": "^3.8.1",
"typescript": "~6.0.2", "typescript": "~6.0.2",
"vitest": "^5.0.0" "vitest": "^5.0.0"
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuEligibility$Params {
domain: Domain;
id: string;
/**
* Limit the report to one CaCu scenario
*/
scenario?: (string | null);
/**
* Only index dates up to this day
*/
cutoff?: (string | null);
}
export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('scenario', params.scenario, {});
rb.query('cutoff', params.cutoff, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuRiskSeries$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ReferenceRisk$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
+18
View File
@@ -24,6 +24,21 @@ export interface SearchPatient$Params {
'follow-up-cutoff'?: (string | null); 'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null); 'follow-up-status'?: (string | null);
/**
* each word starts a word of her name (case and accents ignored)
*/
name?: (string | null);
/**
* [system|]value: a CURP or record number (case ignored)
*/
identifier?: (string | null);
/**
* gt, ge, lt or le and a day (2000-12-31)
*/
birthdate?: Array<string>;
/** /**
* -recent or -risk-<outcome> * -recent or -risk-<outcome>
*/ */
@@ -56,6 +71,9 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {}); rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {}); rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {}); rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('birthdate', params.birthdate, {});
rb.query('_sort', params['_sort'], {}); rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {}); rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {}); rb.query('_revinclude', params['_revinclude'], {});
+3 -2
View File
@@ -8,12 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder'; import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain'; import { Domain } from '../../models/domain';
import { Model } from '../../models/model';
export interface Models$Params { export interface Models$Params {
domain: Domain; domain: Domain;
} }
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> { export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Model>>> {
const rb = new RequestBuilder(rootUrl, models.PATH, 'get'); const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
if (params) { if (params) {
rb.path('domain', params.domain, {}); rb.path('domain', params.domain, {});
@@ -24,7 +25,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
).pipe( ).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse), filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => { map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<string>>; return r as StrictHttpResponse<Array<Model>>;
}) })
); );
} }
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params { export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params { export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+35
View File
@@ -0,0 +1,35 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface TerminateRun$Params {
run_id: string;
}
export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, terminateRun.PATH, 'post');
if (params) {
rb.path('run_id', params.run_id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
terminateRun.PATH = '/runs/{run_id}/terminate';
+8
View File
@@ -75,6 +75,8 @@ export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unr
export { unrecognised as unrecognised } from './fn/review/unrecognised'; export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status'; export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status'; export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies'; export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies'; export { studies as studies } from './fn/eeg/studies';
export type { Study$Params as Study$Params } from './fn/eeg/study'; export type { Study$Params as Study$Params } from './fn/eeg/study';
@@ -111,6 +113,12 @@ export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/sea
export { searchPatient as searchPatient } from './fn/fhir/search-patient'; export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient'; export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
export { readPatient as readPatient } from './fn/fhir/read-patient'; export { readPatient as readPatient } from './fn/fhir/read-patient';
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
export type { ReferenceRisk$Params as ReferenceRisk$Params } from './fn/fhir/reference-risk';
export { referenceRisk as referenceRisk } from './fn/fhir/reference-risk';
export type { CacuRiskSeries$Params as CacuRiskSeries$Params } from './fn/fhir/cacu-risk-series';
export { cacuRiskSeries as cacuRiskSeries } from './fn/fhir/cacu-risk-series';
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure'; export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure'; export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment'; export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
+1
View File
@@ -24,6 +24,7 @@ export type { Listing } from './models/listing';
export type { Login } from './models/login'; export type { Login } from './models/login';
export type { Map } from './models/map'; export type { Map } from './models/map';
export type { Metric } from './models/metric'; export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option'; export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision'; export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline'; export type { Pipeline } from './models/pipeline';
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable). * field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/ */
export interface Correction { export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string; field: string;
record: string; record: string;
value: string; value: string;
+1 -1
View File
@@ -25,7 +25,7 @@ export interface Extract {
/** /**
* Qué estudio se saca del documento. * Qué estudio se saca del documento.
*/ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
+1 -1
View File
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir { export interface Fhir {
column?: string; column?: string;
concept_map?: (string | null); concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'fhir'; kind?: 'fhir';
+1 -1
View File
@@ -11,5 +11,5 @@ export interface FieldSpec {
placeholder?: string; placeholder?: string;
provider?: (string | null); provider?: (string | null);
required?: boolean; required?: boolean;
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format'; type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format' | 'columns';
} }
+1 -1
View File
@@ -18,7 +18,7 @@ export interface Join {
label?: string; label?: string;
/** /**
* Pares [columna izquierda, derecha]. * Columna de la primera entrada = columna de la segunda.
*/ */
on: Array<[string, string]>; on: Array<[string, string]>;
position?: (Position | null); position?: (Position | null);
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Model {
name: string;
title: string;
}
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection { export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string; reason: string;
record: string; record: string;
} }
+1 -1
View File
@@ -12,7 +12,7 @@ export interface Target {
/** /**
* En qué estudio de la plataforma se guarda. * En qué estudio de la plataforma se guarda.
*/ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'target'; kind?: 'target';
+5 -3
View File
@@ -4,7 +4,9 @@
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" /> <img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a> </a>
@if (domain(); as current) { @if (domain(); as current) {
<span class="title">Plataforma de Indicadores</span> <span class="title">{{
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
}}</span>
<button <button
mat-flat-button mat-flat-button
class="domain" class="domain"
@@ -16,7 +18,7 @@
</button> </button>
<mat-menu #menu="matMenu"> <mat-menu #menu="matMenu">
@for (d of others(); track d) { @for (d of others(); track d) {
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a> <a mat-menu-item [routerLink]="['/' + section(), d]">{{ labels[d] }}</a>
} }
</mat-menu> </mat-menu>
} @else { } @else {
@@ -31,7 +33,7 @@
</nav> </nav>
@if (auth.user(); as u) { @if (auth.user(); as u) {
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta"> <button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
<mat-icon>account_circle</mat-icon> {{ u.name || u.email }} <mat-icon>account_circle</mat-icon><span class="who-name">{{ u.name || u.email }}</span>
</button> </button>
<mat-menu #account="matMenu"> <mat-menu #account="matMenu">
<span class="who" mat-menu-item disabled>{{ u.email }}</span> <span class="who" mat-menu-item disabled>{{ u.email }}</span>
+38 -1
View File
@@ -21,10 +21,22 @@
.title { .title {
flex: 1; flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.25rem; font-size: 1.25rem;
font-weight: 500; font-weight: 500;
} }
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain,
.sections a,
.user {
flex-shrink: 0;
white-space: nowrap;
}
.domain { .domain {
--mat-button-filled-container-color: var(--color-primary); --mat-button-filled-container-color: var(--color-primary);
--mat-button-filled-label-text-color: var(--color-text); --mat-button-filled-label-text-color: var(--color-text);
@@ -67,10 +79,35 @@
width: clamp(155px, 15vw, 185px); width: clamp(155px, 15vw, 185px);
} }
@media (max-width: 720px) { @media (max-width: 1100px) {
.title { .title {
display: none; display: none;
} }
.header {
justify-content: space-between;
gap: var(--space-3);
}
.sections {
gap: var(--space-3);
}
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name {
display: none;
}
.domain {
max-width: 15rem;
}
.domain ::ng-deep .mdc-button__label {
overflow: hidden;
text-overflow: ellipsis;
}
}
@media (max-width: 720px) {
.header {
flex-wrap: wrap;
padding-block: var(--space-2);
}
} }
.user { .user {
+5 -4
View File
@@ -43,10 +43,11 @@ export class App {
), ),
{ initialValue: '' }, { initialValue: '' },
); );
/** The domain of an indicator page, if this is one. */ /** The section and domain of a page that has one (indicators, governance): the switcher
protected readonly domain = computed( * moves between that section's domains. */
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined, private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
); protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
protected readonly others = computed(() => protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)), (this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
); );
+62 -35
View File
@@ -73,10 +73,6 @@
</button> </button>
</div> </div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p> <p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) { @if (d.inputs?.length) {
<div class="inputs"> <div class="inputs">
Entradas: Entradas:
@@ -87,40 +83,71 @@
} }
</div> </div>
} @else if (d.kind !== 'source') { } @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p> <p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
} }
@if (guided(d); as g) { <mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
<div class="source-summary"> <mat-tab label="Configuración">
<p> @if (d.kind === 'source') {
<mat-icon>check_circle</mat-icon> @if (guided(d)) {
{{ d.label || d.id }} <div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
} @else {
<p class="muted">
Esta fuente no corresponde a ningún tipo del asistente. Edítela en «Avanzado» o
vuelva a conectarla con el asistente.
</p>
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con el asistente
</button>
}
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
[options]="formOptions"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
</mat-tab>
<mat-tab label="Avanzado">
<p class="hint">
Para personal técnico: el nodo completo como lo guarda la plataforma.
@if (guided(d)) {
Si cambia su fuente aquí, deja de editarse con el asistente.
}
</p> </p>
<button mat-flat-button (click)="connectSource(d.id)"> <mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-icon>edit</mat-icon> Editar conexión <mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
<mat-hint>Nombre interno: minúsculas, números y _.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full raw">
<mat-label>Nodo (JSON)</mat-label>
<textarea
matInput
rows="16"
[value]="raw(d)"
(input)="rawDraft.set($any($event.target).value)"
></textarea>
</mat-form-field>
@if (rawError()) {
<p class="error" role="alert">{{ rawError() }}</p>
}
<button mat-stroked-button [disabled]="rawDraft() === undefined" (click)="applyRaw()">
Aplicar
</button> </button>
</div> </mat-tab>
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)"> </mat-tab-group>
Avanzado (para personal técnico)
</mat-slide-toggle>
} @else if (d.kind === 'source') {
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con ayuda
</button>
}
@if (!guided(d) || advanced()) {
@if (guided(d)) {
<p class="muted">Si cambia algo aquí, la fuente deja de editarse con ayuda.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
}
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
<button mat-stroked-button (click)="show()">Vista previa</button> <button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) { @if (preview(); as rows) {
<div class="preview"> <div class="preview">
+52
View File
@@ -140,3 +140,55 @@ h2 {
color: var(--color-success, #2e7d32); color: var(--color-success, #2e7d32);
} }
} }
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node {
box-sizing: border-box;
overflow: hidden;
padding: 4px 10px;
display: flex;
align-items: center;
}
:host ::ng-deep .node-caption {
min-width: 0;
width: 100%;
line-height: 1.2;
}
:host ::ng-deep .node-caption .kind {
display: block;
font-size: 10px;
color: var(--color-text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
:host ::ng-deep .node-caption .name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: 12px;
font-weight: 500;
overflow-wrap: anywhere;
}
.panel-tabs {
margin-top: var(--space-2);
}
.panel-tabs .hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: var(--space-3) 0;
}
.raw textarea {
font-family: monospace;
font-size: 12px;
}
.error {
color: var(--mat-sys-error);
font-size: 13px;
}
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3);
}
+86 -15
View File
@@ -1,5 +1,13 @@
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core'; import {
Component,
computed,
effect,
inject,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
@@ -7,7 +15,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list'; import { MatListModule } from '@angular/material/list';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatTabsModule } from '@angular/material/tabs';
import { MatTableModule } from '@angular/material/table'; import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core'; import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
@@ -57,21 +65,21 @@ export const KINDS: Record<Kind, string> = {
read: 'Leer documentos', read: 'Leer documentos',
route: 'Separar por tipo', route: 'Separar por tipo',
map: 'Traducir códigos', map: 'Traducir códigos',
extract: 'Sacar datos', extract: 'Extraer datos',
fhir: 'Leer FHIR', fhir: 'Leer FHIR',
join: 'Juntar', join: 'Unir',
link: 'Identificar a la persona', link: 'Identificar a la persona',
target: 'Guardar en la plataforma', target: 'Guardar en la plataforma',
}; };
export const HELP: Record<Kind, string> = { export const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.', source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Saca el texto de cada documento (PDF, Word, escaneos con OCR).', read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route: route:
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.', 'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.', map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Toma de cada documento los datos de un estudio: fechas, resultados, nombres.', extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee paquetes FHIR que un sistema envió y saca de ellos los estudios.', fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
join: 'Junta dos entradas que hablan de lo mismo; por ejemplo, un resultado con su orden.', join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.', link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.', target: 'Guarda los estudios ya revisados en la plataforma.',
}; };
@@ -90,7 +98,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule, MatIconModule,
MatInputModule, MatInputModule,
MatListModule, MatListModule,
MatSlideToggleModule, MatTabsModule,
MatTableModule, MatTableModule,
MatTooltipModule, MatTooltipModule,
Vflow, Vflow,
@@ -107,8 +115,9 @@ export class Conectar {
private readonly dialog = inject(MatDialog); private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][]; protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP; protected readonly help = HELP;
/** The raw form of a source drawn with the dialog ("Avanzado"). */ /** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly advanced = signal(false); protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) }); protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) }); private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -132,6 +141,20 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
}); });
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({}); protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {}; protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */ /** The selected node's form, generated from its kind's JSON Schema. */
@@ -264,7 +287,8 @@ export class Conectar {
); );
this.form = new UntypedFormGroup({}); this.form = new UntypedFormGroup({});
this.preview.set(undefined); this.preview.set(undefined);
this.advanced.set(false); this.rawDraft.set(undefined);
this.rawError.set('');
} }
/** A source the dialog drew (its answers make its dlt fields). */ /** A source the dialog drew (its answers make its dlt fields). */
@@ -279,13 +303,46 @@ export class Conectar {
const values = Object.fromEntries( const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null), Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
); );
if (this.advanced()) delete values['guided']; // drawn by hand from here on
this.update( this.update(
id, id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc, (d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
); );
} }
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2);
}
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void {
const d = this.doc();
const text = this.rawDraft();
if (!d || text === undefined) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(text);
} catch {
this.rawError.set('El texto no es JSON válido.');
return;
}
if (parsed['kind'] !== d.kind) {
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
return;
}
if (d.kind === 'source') {
const dlt = ['source', 'args', 'resource', 'then'] as const;
const before = d as unknown as Record<string, unknown>;
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
delete parsed['guided'];
}
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
this.select(d.id);
}
protected rename(to: string): void { protected rename(to: string): void {
const from = this.selected(); const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return; if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
@@ -363,7 +420,7 @@ export class Conectar {
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source }) ? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 }); : await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows); this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.'); this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
} catch (e) { } catch (e) {
this.message.set(problem(e)); this.message.set(problem(e));
} }
@@ -389,7 +446,14 @@ export class Conectar {
} }
function text(d: Doc): string { function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`; // ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
`<div class="node-caption" title="${kind} · ${name}">` +
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
);
} }
/** Each node's distance from the sources: its column when it has no saved position. */ /** Each node's distance from the sources: its column when it has no saved position. */
@@ -416,3 +480,10 @@ function problem(e: unknown): string {
} }
return String(e); return String(e);
} }
function escape(text: string): string {
return text.replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!,
);
}
+15 -3
View File
@@ -16,6 +16,12 @@ const PIPELINE = {
when: { type: 'array', items: { $ref: '#/$defs/Condition' } }, when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' }, resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' }, values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
on: {
type: 'array',
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
},
extra: { type: 'object', title: 'Extra' },
source: { type: 'string', advanced: true },
}, },
}, },
}, },
@@ -25,7 +31,7 @@ describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any; const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => { it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']); expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
expect(schema.required).toEqual(['when']); expect(schema.required).toEqual(['when']);
}); });
@@ -34,7 +40,13 @@ describe('node forms from the pipeline schema', () => {
expect(schema.properties.resource.type).toBe('string'); expect(schema.properties.resource.type).toBe('string');
}); });
it('edits maps as JSON', () => { it('edits maps of texts and pairs as rows', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json'); expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
});
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
expect(schema.properties.extra).toBeUndefined();
expect(schema.properties.source).toBeUndefined();
}); });
}); });
+236 -2
View File
@@ -3,6 +3,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { import {
ConfigOption, ConfigOption,
@@ -27,11 +28,29 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!; )!;
const node = structuredClone(defs[name]); const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field]; for (const field of CANVAS_FIELDS) delete node.properties?.[field];
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f)); // The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
delete node.properties![field];
}
node.required = (node.required ?? []).filter(
(f) => !CANVAS_FIELDS.includes(f) && f in (node.properties ?? {}),
);
delete node.additionalProperties; delete node.additionalProperties;
return simplify(node, defs); return simplify(node, defs);
} }
function isJson(schema: Schema): boolean {
return (
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
'json'
);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema { function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) { if (schema.$ref) {
const { $ref, ...rest } = schema; const { $ref, ...rest } = schema;
@@ -45,6 +64,34 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return simplify({ ...kept[0], ...rest }, defs); return simplify({ ...kept[0], ...rest }, defs);
} }
} }
const values = schema.additionalProperties as Schema | boolean | undefined;
if (
schema.type === 'object' &&
!schema.properties &&
typeof values === 'object' &&
values.type === 'string'
) {
const byField = (schema as { keys?: string }).keys === 'field';
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
} as Schema;
}
const pair = schema.items as Schema | undefined;
if (
schema.type === 'array' &&
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'pairs' } },
} as Schema;
}
const isMap = schema.type === 'object' && !schema.properties; const isMap = schema.type === 'object' && !schema.properties;
const isTuple = const isTuple =
schema.type === 'array' && schema.type === 'array' &&
@@ -117,7 +164,7 @@ export class ArrayType extends FieldArrayType {}
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule], imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: ` template: `
<mat-form-field appearance="outline" class="json"> <mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }} (JSON)</mat-label> <mat-label>{{ props.label }}</mat-label>
<textarea <textarea
matInput matInput
rows="4" rows="4"
@@ -152,11 +199,198 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
} }
} }
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
@if (props['fieldKeys']) {
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
@for (o of keyOptions(row[0]); track o[0]) {
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[value]="row[0]"
(change)="edit(i, $any($event.target).value, row[1])"
/>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
<mat-label>Valor</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
column-gap: 4px;
row-gap: 6px;
padding: 8px 0;
border-bottom: 1px solid var(--color-border);
}
.key,
.value {
min-width: 0;
grid-column: 1;
}
.row button {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
string | undefined;
const titles: Record<string, string> = entity
? (all[entity] ?? {})
: Object.assign({}, ...Object.values(all));
const options = Object.entries(titles);
if (current && !(current in titles)) options.unshift([current, current]);
return options;
}
protected rows(): [string, string][] {
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
this.formControl.markAsDirty();
}
protected edit(i: number, key: string, value: string): void {
const rows = this.rows();
rows[i] = [key.trim(), value];
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
: undefined;
let n = rows.length + 1;
while (used.has(`campo_${n}`)) n++;
this.save([...rows, [free ?? `campo_${n}`, '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Primera entrada</mat-label>
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
</mat-form-field>
<span>=</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Segunda entrada</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 6px;
}
.half {
flex: 1;
min-width: 0;
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(rows);
this.formControl.markAsDirty();
}
protected edit(i: number, side: 0 | 1, value: string): void {
const rows = this.rows();
rows[i][side] = value.trim();
this.save(rows);
}
protected add(): void {
this.save([...this.rows(), ['', '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
export const FORMLY_TYPES: ConfigOption = { export const FORMLY_TYPES: ConfigOption = {
types: [ types: [
{ name: 'object', component: ObjectType }, { name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType }, { name: 'array', component: ArrayType },
{ name: 'json', component: JsonType }, { name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ name: 'enum', extends: 'select' }, { name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' }, { name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } }, { name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
+20 -1
View File
@@ -128,6 +128,25 @@
} }
</mat-form-field> </mat-form-field>
} }
@case ('columns') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
multiple
[ngModel]="listed(name)"
(ngModelChange)="set(name, $event.length ? $event : null)"
[attr.data-field]="name"
placeholder="Todas"
>
@for (c of columnOptions(name); track c) {
<mat-option [value]="c">{{ c }}</mat-option>
}
</mat-select>
<mat-hint>{{
columnOptions(name).length ? f.help : 'Pulse «Probar conexión» para ver las columnas.'
}}</mat-hint>
</mat-form-field>
}
@case ('folder') { @case ('folder') {
<div class="picker"> <div class="picker">
<mat-form-field appearance="outline" class="grow"> <mat-form-field appearance="outline" class="grow">
@@ -319,7 +338,7 @@
</p> </p>
@if (t.detail) { @if (t.detail) {
<details> <details>
<summary>Lo que respondió el sistema</summary> <summary>Respuesta de la fuente</summary>
<pre>{{ t.detail }}</pre> <pre>{{ t.detail }}</pre>
</details> </details>
} }
+12
View File
@@ -33,6 +33,8 @@ export interface SourceDialogData {
guided?: Guided | null; guided?: Guided | null;
label?: string; label?: string;
} }
const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */ /** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult { export interface SourceDialogResult {
guided: Guided; guided: Guided;
@@ -203,6 +205,16 @@ export class SourceDialog {
} }
} }
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
/** The tables a database listed, for its table field. */ /** The tables a database listed, for its table field. */
protected tables(): string[] { protected tables(): string[] {
return this.tableList(); return this.tableList();
+8
View File
@@ -134,3 +134,11 @@ export function byDeviation(zones: Site[]): Site[] {
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value, scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
); );
} }
/** An EEG's quality level (models.tea.eeg.checks): how much of it the analysis could use. */
export const LEVEL_NAMES: Record<string, string> = {
complete: 'registro completo',
partial: 'registro parcial: menos de la mitad limpio',
no_ear_reference: 'sin referencia auricular',
not_analyzable: 'no analizable',
};
+69
View File
@@ -0,0 +1,69 @@
import type { Content, TDocumentDefinitions } from 'pdfmake/interfaces';
/** A table to save, as the page shows it: its headers and rows, and what it was asked with. */
export interface Sheet {
title: string;
query?: [string, string][];
head: string[];
rows: string[][];
}
/** Every cell is text: nothing in it runs as a formula. */
export async function saveExcel(sheet: Sheet, file: string): Promise<void> {
const { default: write } = await import('write-excel-file/browser');
const text = (value: string) => ({ value, type: String });
const head = sheet.head.map((value) => ({ ...text(value), fontWeight: 'bold' as const }));
await write([
{ sheet: 'Resultados', data: [head, ...sheet.rows.map((r) => r.map(text))] },
{ sheet: 'Consulta', data: (sheet.query ?? []).map((q) => q.map(text)) },
]).toFile(`${file}.xlsx`);
}
/** The tables on the institutional page: logo, date and page numbers. */
export async function savePdf(sheets: Sheet[], file: string, wide = false): Promise<void> {
const [pdfmake, fonts, logo] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
fetch('assets/branding/isssteleon-logo.png').then((r) => r.blob()),
]);
const image = await new Promise<string>((done, fail) => {
const reader = new FileReader();
reader.onload = () => done(reader.result as string);
reader.onerror = () => fail(reader.error);
reader.readAsDataURL(logo);
});
const made = new Date().toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
const definition: TDocumentDefinitions = {
pageSize: 'LETTER',
pageOrientation: wide ? 'landscape' : 'portrait',
pageMargins: [36, 60, 36, 40],
defaultStyle: { fontSize: 7.5 },
header: { image, width: 110, margin: [36, 18, 0, 0] },
footer: (page, pages) => ({
columns: [
`Generado: ${made}`,
{ text: 'Confidencial, uso interno', alignment: 'center' },
{ text: `Página ${page} de ${pages}`, alignment: 'right' },
],
margin: [36, 12],
fontSize: 7,
}),
content: sheets.flatMap((s): Content[] => [
{ text: s.title, fontSize: 13, bold: true, margin: [0, 10, 0, 4] },
...(s.query ?? []).map(([k, v]) => ({ text: [{ text: `${k}: `, bold: true }, v] })),
s.rows.length
? {
layout: 'lightHorizontalLines',
margin: [0, 6, 0, 0],
table: {
headerRows: 1,
dontBreakRows: true,
body: [s.head.map((text) => ({ text, bold: true })), ...s.rows],
},
}
: 'Sin registros.',
]),
};
pdfmake.default.addVirtualFileSystem(fonts.default);
await pdfmake.default.createPdf(definition).download(`${file}.pdf`);
}
+57 -21
View File
@@ -10,23 +10,44 @@ interface Band {
high?: (number | null)[]; high?: (number | null)[];
} }
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The stretches of x where the curve has both limits: a band is drawn only there, never from a
* limit that is absent (an absent limit is not zero). */
function bandRuns(b: Band): number[][] {
const runs: number[][] = [];
let run: number[] = [];
b.x.forEach((x, i) => {
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
else {
if (run.length > 1) runs.push(run);
run = [];
}
});
if (run.length > 1) runs.push(run);
return runs;
}
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] { function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = []; const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) { if (b.low && b.high) {
lines.push({ for (const run of bandRuns(b)) {
x: [...b.x, ...[...b.x].reverse()], const x = run.map((i) => b.x[i]);
y: [...b.high, ...[...b.low].reverse()] as number[], lines.push({
fill: 'toself', x: [...x, ...[...x].reverse()],
fillcolor: `${colour}33`, y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
line: { width: 0 }, fill: 'toself',
hoverinfo: 'skip', fillcolor: `${colour}33`,
showlegend: false, line: { width: 0 },
type: 'scatter', hoverinfo: 'skip',
}); showlegend: false,
type: 'scatter',
});
}
} }
lines.push({ lines.push({
x: b.x, x: b.x,
y: b.y, y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name, name,
type: 'scatter', type: 'scatter',
mode: 'lines', mode: 'lines',
@@ -286,27 +307,42 @@ export function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB), points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
], ],
layout: { layout: {
xaxis: { title: { text: 'Meses desde el diagnóstico' } }, // One label per month with every curve's survival there, as percentages.
yaxis: { title: { text: yTitle } }, hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
}, },
}, },
}; };
} }
/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
* point without both limits has no bar. */
function points( function points(
name: string, name: string,
x: number[], x: number[],
p: { S: number[]; low: number[]; high: number[] }, p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> { ): Partial<Plotly.Data> {
const errors = p.S.map((value, i) => {
const low = p.low?.[i];
const high = p.high?.[i];
return finite(value) && finite(low) && finite(high)
? { up: high - value, down: value - low }
: null;
});
return { return {
x, x,
y: p.S, y: p.S.map((v) => (finite(v) ? v : null)) as number[],
error_y: { ...(errors.some((error) => error !== null)
type: 'data', ? {
symmetric: false, error_y: {
array: p.high.map((h, i) => h - p.S[i]), type: 'data' as const,
arrayminus: p.S.map((v, i) => v - p.low[i]), symmetric: false,
}, array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: errors.map((error) => error?.down ?? null) as number[],
},
}
: {}),
name, name,
type: 'scatter', type: 'scatter',
mode: 'markers', mode: 'markers',
+67 -33
View File
@@ -1,10 +1,6 @@
<section class="page"> <section class="page">
<h1>Gobernanza de modelos</h1> <h1>{{ labels[domain()] ?? domain() }}</h1>
<nav class="domains" aria-label="Dominios"> <p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
@for (d of domains.value() ?? []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<form class="card actions" (submit)="$event.preventDefault()"> <form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -17,13 +13,44 @@
name="asOf" name="asOf"
/> />
</mat-form-field> </mat-form-field>
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button> @if (confirming(); as c) {
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button> <span class="confirm" role="alert">
@if (domain() === 'tea') { {{
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button> c === 'train'
? '¿Entrenar todos los modelos de este dominio ahora?'
: '¿Calcular los riesgos de todas las pacientes con los modelos en producción?'
}}
<button mat-flat-button type="button" (click)="start(c)">Sí, iniciar</button>
<button mat-button type="button" (click)="confirming.set(undefined)">Cancelar</button>
</span>
} @else {
<button
mat-flat-button
type="button"
[disabled]="running()"
(click)="confirming.set('train')"
>
Entrenar
</button>
<button
mat-stroked-button
type="button"
[disabled]="running()"
(click)="confirming.set('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
Analizar EEG
</button>
}
} }
@if (run(); as r) { @if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span> <span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
@if (running()) {
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
}
} }
</form> </form>
@if (message()) { @if (message()) {
@@ -33,17 +60,19 @@
@if (models.isLoading()) { @if (models.isLoading()) {
<app-loading what="los modelos" /> <app-loading what="los modelos" />
} @else if (!models.value()?.length) { } @else if (!models.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p> <p class="muted empty">Sin modelos entrenados en este dominio.</p>
} }
@for (m of models.value() ?? []; track m.name) { @for (m of models.value() ?? []; track m.name) {
<div class="card model"> <div class="card model">
<h2>{{ m.name }}</h2> <h2>
{{ m.title }} <code class="muted code">{{ m.name }}</code>
</h2>
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
<th>Versión</th> <th>Versión</th>
<th>Creada</th> <th>Creada</th>
<th>Entrenamiento / prueba</th> <th>Datos</th>
<th>Informes</th> <th>Informes</th>
<th>Validación clínica</th> <th>Validación clínica</th>
<th></th> <th></th>
@@ -59,32 +88,37 @@
} }
</td> </td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td> <td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num"> <td class="nowrap">{{ sizes(v) }}</td>
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td> <td>
@for (r of v.reports; track r) { <div class="reports">
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{ @for (r of v.reports; track r) {
reportNames[r] ?? r <a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
}}</a> reportNames[r] ?? r
} }}</a>
@if (v.reports.includes('interpretability')) { }
<button @if (v.reports.includes('interpretability')) {
mat-button <button
type="button" mat-button
(click)="chosen.set({ name: m.name, version: v.version })" type="button"
> (click)="chosen.set({ name: m.name, version: v.version })"
Ver gráficas >
</button> Ver gráficas
} </button>
}
</div>
</td> </td>
<td> <td>
@if (!v.reports.includes('clinical_validation')) { @if (!v.reports.includes('clinical_validation')) {
<input <input
#file
type="file" type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version" hidden
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
(change)="upload(m.name, v.version, $event)" (change)="upload(m.name, v.version, $event)"
/> />
<button mat-stroked-button type="button" (click)="file.click()">
Subir validación clínica
</button>
} @else { } @else {
Agregada Agregada
} }
@@ -105,7 +139,7 @@
@if (chosen(); as c) { @if (chosen(); as c) {
<div class="card"> <div class="card">
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2> <h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) { @for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3> <h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" /> <app-plot [figure]="f.figure" [height]="360" />
+32 -12
View File
@@ -1,18 +1,8 @@
:host { :host {
display: block; display: block;
} }
h1 { .subtitle {
text-align: center; margin: 4px 0 var(--space-4);
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
} }
.actions { .actions {
display: flex; display: flex;
@@ -30,6 +20,7 @@ h1 {
white-space: nowrap; white-space: nowrap;
} }
.badge { .badge {
white-space: nowrap;
margin-left: var(--space-2); margin-left: var(--space-2);
padding: 2px 8px; padding: 2px 8px;
border-radius: 999px; border-radius: 999px;
@@ -45,3 +36,32 @@ td a {
padding: 48px 0; padding: 48px 0;
text-align: center; text-align: center;
} }
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
}
.reports a {
margin-right: 0;
}
h2 .code {
font-size: 12px;
font-weight: 400;
margin-left: var(--space-2);
}
.confirm {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: 4px 4px 4px 12px;
border-radius: 8px;
background: var(--color-surface-warning, #fdf3dc);
}
td button {
white-space: nowrap;
}
+60 -11
View File
@@ -6,7 +6,6 @@ import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration'; import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
@@ -17,9 +16,9 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import { score } from '../api/fn/models/score'; import { score } from '../api/fn/models/score';
import { train } from '../api/fn/models/train'; import { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions'; import { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import { studies } from '../api/fn/eeg/studies'; import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study'; import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status'; import { runStatus } from '../api/fn/runs/run-status';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import type { Version } from '../api/models/version'; import type { Version } from '../api/models/version';
@@ -47,7 +46,6 @@ const REPORTS: Record<string, string> = {
MatButtonModule, MatButtonModule,
MatFormFieldModule, MatFormFieldModule,
MatInputModule, MatInputModule,
RouterLink,
Plot, Plot,
], ],
templateUrl: './gobernanza.html', templateUrl: './gobernanza.html',
@@ -60,15 +58,15 @@ export class Gobernanza {
protected readonly labels = DOMAINS as Record<string, string>; protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS; protected readonly reportNames = REPORTS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly refreshed = signal(0); private readonly refreshed = signal(0);
protected readonly models = resource({ protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }), params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
loader: async ({ params: { domain } }) => { loader: async ({ params: { domain } }) => {
const names = await this.api.invoke(models, { domain }); const found = await this.api.invoke(models, { domain });
return Promise.all( return Promise.all(
names.map(async (name) => ({ found.map(async ({ name, title }) => ({
name, name,
title,
versions: await this.api.invoke(versions, { domain, name }), versions: await this.api.invoke(versions, { domain, name }),
})), })),
); );
@@ -96,7 +94,41 @@ export class Gobernanza {
}); });
protected readonly metricNames = METRIC_NAMES; protected readonly metricNames = METRIC_NAMES;
protected readonly asOf = signal(''); protected readonly asOf = signal('');
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined); protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
undefined,
);
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
protected readonly running = computed(() => {
const r = this.run();
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
});
protected readonly STATUS: Record<string, string> = {
QUEUED: 'en cola',
NOT_STARTED: 'por iniciar',
STARTING: 'iniciando',
STARTED: 'en curso',
SUCCESS: 'terminado',
FAILURE: 'con error',
CANCELING: 'deteniéndose',
CANCELED: 'detenido',
};
/** A model's title by its name, for messages. */
protected titleOf(name: string): string {
return this.models.value()?.find((m) => m.name === name)?.title ?? name;
}
/** What a version learned from, as its metrics say it (each kind of model its own). */
protected sizes(v: Version): string {
const m = v.metrics;
const n = (x: number) => x.toLocaleString('es-MX');
if (m['n_train'] !== undefined)
return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`;
if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`;
if (m['children'] !== undefined) return `${n(m['children'])} niños`;
const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox'));
if (c) return `C-index ${c[1].toFixed(3)}`;
return '—';
}
protected readonly message = signal(''); protected readonly message = signal('');
protected champion(v: Version): boolean { protected champion(v: Version): boolean {
@@ -117,18 +149,27 @@ export class Gobernanza {
// OpenAPI's binary is typed as a string; the request builder sends the File as is. // OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string }, body: { file: file as unknown as string },
}); });
this.message.set(`Validación clínica agregada a ${name} v${version}.`); this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} }
protected async promote(name: string, version: number): Promise<void> { protected async promote(name: string, version: number): Promise<void> {
try { try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${name} v${version} es ahora la versión en producción.`); this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} catch (e) { } catch (e) {
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
this.message.set(`No se promovió: ${detail ?? 'error'}`); // "<model> v1 has no clinical_validation, interpretability": the reports it lacks
const missing = /has no (.+)$/.exec(String(detail ?? ''))?.[1];
this.message.set(
missing
? `No se promovió: faltan informes (${missing
.split(', ')
.map((r) => this.reportNames[r] ?? r)
.join(', ')}).`
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
);
} }
} }
@@ -140,14 +181,22 @@ export class Gobernanza {
private async follow(run_id: string, label: string): Promise<void> { private async follow(run_id: string, label: string): Promise<void> {
for (;;) { for (;;) {
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
this.run.set({ kind: label, status }); this.run.set({ id: run_id, kind: label, status });
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
await new Promise((r) => setTimeout(r, 2000)); await new Promise((r) => setTimeout(r, 2000));
} }
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} }
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
}
protected async start(kind: 'train' | 'score'): Promise<void> { protected async start(kind: 'train' | 'score'): Promise<void> {
this.confirming.set(undefined);
const domain = this.domain() as Domain; const domain = this.domain() as Domain;
const { run_id } = const { run_id } =
kind === 'train' kind === 'train'
+417
View File
@@ -0,0 +1,417 @@
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { scenarioBars } from './figures';
import { Reading } from './measures';
describe('bars', () => {
it('list every category, so the shares add up', () => {
const r: Reading = {
populations: {},
strata: {
category: { a: { 'initial-population': 3 }, other: { 'initial-population': 1 } },
},
};
const catalog = [{ code: 'a', label: 'A', color: '#000' }];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '75.0 %'],
['1', '25.0 %'],
]);
});
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: {},
strata: { s: { initial: { numerator: 0, denominator: 0 } } },
};
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
describe('screening rounds (complete)', () => {
const ORDER = ['initial', 'subsequent', 'no_data'];
const cell = (numerator: number, denominator: number) => ({ numerator, denominator });
const ppv = (strata: Record<string, any>, total: number): Reading => ({
populations: { 'initial-population': total, denominator: total },
strata: { round: strata },
});
const mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
} as const;
it('lists the three groups in order with their own counts', () => {
const r = ppv({ no_data: cell(1, 4), subsequent: cell(6, 10), initial: cell(0, 6) }, 20);
const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(t.rows.map((x) => x.cells)).toEqual([
['0/6', '0.0 %'],
['6/10', '60.0 %'],
['1/4', '25.0 %'],
]);
expect(t.note).toBeUndefined();
});
it('a group the report leaves out is zero patients when the counts add up', () => {
const r = ppv({ no_data: cell(0, 3), subsequent: cell(6, 10) }, 13);
const initial = bars(mode, () => r)!.rows[0];
expect(initial.cells).toEqual(['0/0', '—']);
expect(initial.hint).toBe('Sin pacientes en el periodo');
});
it('a group left out is not available when the counts do not add up', () => {
const r = ppv({ subsequent: cell(6, 10) }, 13);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['—', '—']);
expect(t.rows[0].hint).toBe('No disponible');
expect(t.note).toContain('no concilian');
});
it('a zero numerator over a positive denominator is 0 %, a zero denominator has no rate', () => {
const r = ppv({ initial: cell(0, 5), subsequent: cell(0, 0), no_data: cell(2, 3) }, 8);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['0/5', '0.0 %']);
expect(t.rows[1].cells).toEqual(['0/0', '—']);
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
});
it('warns when only "Sin dato" holds patients', () => {
const r = ppv({ no_data: cell(3, 7) }, 7);
const t = bars(mode, () => r)!;
expect(t.rows[2].cells).toEqual(['3/7', '42.9 %']);
expect(t.note).toContain('información no registrada');
});
it('draws nothing without patients and says "No disponible" without the stratifier', () => {
expect(bars(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 9))).toContain('No disponible');
expect(bars(mode, () => ppv({}, 9))).toBeUndefined();
});
it('a cell that is not whole or has a numerator above its denominator is not available', () => {
const r = ppv({ initial: cell(5, 3), subsequent: cell(1, 2), no_data: cell(0, 1) }, 6);
expect(bars(mode, () => r)!.rows[0].hint).toBe('No disponible');
});
it('VPH positives: groups from the crossed cells, absent ones reconciled', () => {
const r: Reading = {
populations: { 'initial-population': 12 },
strata: {
'round-category': {
'subsequent|positive': { 'initial-population': 3 },
'subsequent|negative': { 'initial-population': 7 },
'no_data|negative': { 'initial-population': 2 },
},
},
};
const t = bars(
{
kind: 'positives',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
},
() => r,
)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['0/0', '—'],
['3/10', '30.0 %'],
['0/2', '0.0 %'],
]);
});
});
describe('cytology by round', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#0a0', group: '' },
{ code: 'HSIL', label: 'LIEAG', color: '#a00', group: '' },
];
const reading = (cells: Record<string, number>, total: number): Reading => ({
populations: { 'initial-population': total },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const draw = (r: Reading) =>
scenarioBars(
r,
{ groups: [], categories: cats },
'round',
(c) =>
c === 'initial'
? 'Detección inicial'
: c === 'subsequent'
? 'Detección subsecuente'
: 'Sin dato',
['initial', 'subsequent', 'no_data'],
{ fill: true },
);
it('keeps the order and shows each bar with its n, an empty one included', () => {
const f = draw(
reading({ 'subsequent|NILM': 6, 'subsequent|HSIL': 2, 'no_data|NILM': 2 }, 10),
);
const y = (f.data[0] as any).y;
expect(y).toEqual([
'Detección inicial<br>Pacientes: 0',
'Detección subsecuente<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>Pacientes: 6']);
});
});
});
describe('shared views of cytology and HPV by genotype', () => {
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' },
{ code: 'positive_other', label: 'Positivo sin genotipo', color: '#A8C243', group: '' },
];
const reading = (cells: Record<string, number>): Reading => ({
populations: { 'initial-population': Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
category: {
negative: { 'initial-population': 5 },
positive_other: { 'initial-population': 2 },
positive_incomplete: { 'initial-population': 3 },
},
'age_group-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const counts: Mode = {
kind: 'counts',
label: 'General',
measure: 'M',
catalog: HPV,
hidden: { codes: ['positive_incomplete', 'inconsistent'], unit: 'reportes' },
};
it('does not list a hidden category but keeps it in the total and the percentages', () => {
const t = bars(counts, () => reading({}))!;
expect(t.rows.map((x) => x.label)).toEqual(['Negativo', 'Positivo sin genotipo']);
expect(t.rows.map((x) => x.cells)).toEqual([
['5', '50.0 %'],
['2', '20.0 %'],
]); // of 10 reports
expect(t.note).toBe(
'3 reportes (Positivo con genotipificación incompleta) no se muestran desglosados; están incluidos en el total y en los porcentajes.',
);
});
it('says nothing when no report is hidden', () => {
const r: Reading = {
populations: {},
strata: { category: { negative: { 'initial-population': 1 } } },
};
expect(hiddenNote(counts, () => r)).toBeUndefined();
});
it('a figure by groups is not available without its breakdown, and counts every record of the group on request', () => {
const mode = {
kind: 'figure',
label: 'Por grupo de edad',
measure: 'M',
figure: 'scenarios',
stratum: 'age_group',
catalog: HPV,
} as const;
const noBreakdown: Reading = {
populations: { 'initial-population': 4 },
strata: { category: {} },
};
expect(unavailable(mode, () => noBreakdown)).toBe(
'No disponible: el informe de este periodo no publica el desglose «Por grupo de edad».',
);
const r: Reading = {
populations: { 'initial-population': 10 },
strata: {
'age_group-category': {
'25-34|negative': { 'initial-population': 4 },
'25-34|positive_other': { 'initial-population': 1 },
'25-34|positive_incomplete': { 'initial-population': 5 },
},
},
};
const label = (c: string) => c;
const own = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34']);
const all = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34'], {
ofAll: true,
});
expect((own.data[0] as any).x).toEqual([80]); // 4 of the 5 the catalog draws
expect((all.data[0] as any).x).toEqual([40]); // 4 of the group's 10 reports
expect((all.data[0] as any).y).toEqual(['25-34<br>Reportes: 10']);
});
});
describe('independent bars by group', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#408651' },
{ code: 'HSIL', label: 'LIEAG', color: '#CE4778' },
];
const mode = (more: object = {}): Mode =>
({
kind: 'grouped',
label: 'x',
measure: 'M',
catalog: cats,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
unit: 'pacientes',
...more,
}) as Mode;
const reading = (cells: Record<string, number>, total?: number): Reading => ({
populations: { 'initial-population': total ?? Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
it('draws one bar per category in each group: count, denominator and percent over its own records', () => {
const g = grouped(mode(), () =>
reading({ 'initial|NILM': 3, 'initial|HSIL': 1, 'subsequent|NILM': 6 }),
)!;
expect(g.groups.map((x) => [x.label, x.total])).toEqual([
['Detección inicial', 4],
['Detección subsecuente', 6],
]);
expect(g.groups[0].rows.map((r) => [r.label, r.text, r.percent, r.color])).toEqual([
['Normal', '3/4 · 75.0 %', 75, '#408651'],
['LIEAG', '1/4 · 25.0 %', 25, '#CE4778'],
]);
expect(g.groups[1].rows.map((r) => r.text)).toEqual(['6/6 · 100.0 %', '0/6 · 0.0 %']); // a zero numerator is 0 %
});
it('an empty group has no percent; with complete it is drawn only when the counts reconcile', () => {
const empty = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2, 'no_data|HSIL': 1 }),
)!;
expect(empty.groups.map((x) => x.code)).toEqual(['initial', 'subsequent', 'no_data']);
expect(empty.groups[0]).toMatchObject({ total: 0, hint: 'Sin pacientes en el grupo' });
expect(empty.groups[0].rows.map((r) => [r.text, r.percent])).toEqual([
['0/0 · —', undefined],
['0/0 · —', undefined],
]);
expect(empty.note).toContain('una categoría en cero significa');
const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5),
)!;
expect(unreconciled.groups.map((x) => x.code)).toEqual(['subsequent']);
expect(unreconciled.note).toContain('no concilian');
const open = grouped(mode(), () => reading({ 'subsequent|NILM': 2 }))!;
expect(open.groups.map((x) => x.code)).toEqual(['subsequent']); // without complete: only the listed groups
});
it('each group may count all its records, hidden categories included', () => {
const r = reading({ 'initial|NILM': 2, 'initial|positive_incomplete': 2 });
const own = grouped(mode(), () => r)!;
const all = grouped(mode({ ofAll: true }), () => r)!;
expect(own.groups[0].total).toBe(2);
expect(all.groups[0].total).toBe(4);
expect(all.groups[0].rows[0].text).toBe('2/4 · 50.0 %');
});
it('is not available without the breakdown, and draws nothing without records', () => {
const none: Reading = { populations: { 'initial-population': 4 }, strata: {} };
expect(grouped(mode(), () => none)).toBeUndefined();
expect(unavailable(mode(), () => none)).toContain('No disponible');
expect(grouped(mode(), () => reading({}, 0))).toBeUndefined();
});
it('says that unclassified records leave a classified group empty, and warns when none is classified', () => {
const lone = grouped(mode({ complete: true }), () => reading({ 'no_data|NILM': 3 }))!;
expect(lone.note).toContain('información no registrada');
});
it('a proportion split into its parts shows both in units and shares', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const t = bars({ kind: 'split', label: 'x', measure: 'M', yes: 'Con', no: 'Sin' }, () => r)!;
expect(t.rows.map((x) => [x.label, ...x.cells])).toEqual([
['Con', '1', '25.0 %'],
['Sin', '3', '75.0 %'],
]);
});
it('rows with patients and no biopsy are not rows with no patients; malignant counts only graded', () => {
const r: Reading = {
populations: {},
strata: {
birads: {
'4A': { 'initial-population': 3 },
'5': { 'initial-population': 4 },
'6': { 'initial-population': 2 },
},
'birads-category': {
'4A|no_biopsy': { 'initial-population': 3 },
'5|benign': { 'initial-population': 1 },
'5|invasive': { 'initial-population': 1 },
'5|no_data': { 'initial-population': 2 },
'6|no_data': { 'initial-population': 2 },
},
},
};
const results = [
{ code: 'benign', label: 'Benigno', color: '#1' },
{ code: 'invasive', label: 'Invasor', color: '#2' },
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#3' },
{ code: 'no_data', label: 'Sin dato', color: '#4' },
];
const rows = ['4A', '5', '6', '4B'].map((code) => ({ code, label: code, color: '#0' }));
const mode = {
kind: 'outcomes',
label: 'x',
measure: 'M',
stratum: 'birads',
rows,
results,
malignant: ['invasive'],
};
const t = bars(mode as any, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '0', '0', '3', '0', 'Sin biopsias'],
['4', '1', '1', '0', '2', '1/2 (50.0 %)'],
['2', '0', '0', '0', '2', 'Sin biopsias clasificables'],
['0', '—', '—', '—', '—', '—'],
]);
expect(t.rows.map((x) => x.none)).toEqual([
undefined,
undefined,
undefined,
'Sin pacientes en el periodo',
]);
expect(t.rows[1].segments!.map((x) => x.width)).toEqual([25, 25, 0, 50]);
});
it('bars on a percent scale are as long as the shares shown', () => {
const r: Reading = {
populations: {},
strata: { category: { a: { 'initial-population': 1 }, b: { 'initial-population': 3 } } },
};
const catalog = [
{ code: 'a', label: 'A', color: '#0' },
{ code: 'b', label: 'B', color: '#1' },
{ code: 'c', label: 'C', color: '#2' },
];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, percent: true }, () => r)!;
expect(t.rows.map((x) => x.width)).toEqual([25, 75, 0]);
expect(t.rows.map((x) => x.cells)).toEqual([
['1', '25.0 %'],
['3', '75.0 %'],
['0', '0.0 %'],
]);
});
it('a split takes the colours it is given', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const mode = {
kind: 'split',
label: 'x',
measure: 'M',
yes: 'Con',
no: 'Sin',
colors: ['#a', '#b'],
};
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
});
});
+591
View File
@@ -0,0 +1,591 @@
import { CIE10 } from './cie10';
import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = {
label: string;
caption?: string;
/** said above the table: what its rows count (patients, reported biopsies…) */
heading?: string;
} & (
| {
kind: 'counts';
measure: string;
catalog: Category[];
/** The records counted in the category distribution. */
unit?: string;
/** What the share in the second column is a share of. */
percentLabel?: string;
hidden?: Hidden;
/** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
percent?: boolean;
}
| {
kind: 'shares';
measure: string;
stratum: string;
order: string[];
complete?: boolean;
colors?: Colors;
percentLabel?: string;
}
| {
kind: 'positives';
measure: string;
stratum: string;
order: string[];
complete?: boolean;
colors?: Colors;
percentLabel?: string;
}
| {
kind: 'signs';
measure: string;
strata: string[];
colors?: Colors;
percentLabel?: string;
}
| {
kind: 'grouped';
measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[];
/** 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 }
/** 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];
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 */
| {
kind: 'outcomes';
measure: string;
stratum: string;
rows: Category[];
results: Category[];
malignant: string[];
}
| {
kind: 'figure';
measure: string;
figure: 'donut' | 'scenarios';
/** a donut's colour by part (a category, or numerator and rest); none: the page's palette */
colors?: Colors;
catalog?: Category[];
/** the stratifier a scenarios figure crosses with the category (default: the follow-up status) */
stratum?: string;
order?: string[];
/** draw the groups of `order` the report leaves out as zero (see `reconciles`) */
complete?: boolean;
/** each bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
hidden?: Hidden;
}
);
/** Categories a card does not draw: their records stay in the total and in the percentages. */
export type Hidden = { codes: string[]; unit: string };
/** A colour by category code (the category decides it, not its place in the report). */
export type Colors = Record<string, string>;
/** The colours of a median bar and of the marks of its quartiles. */
export type Tint = { bar: string; mark: string };
/** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
export interface GroupRow {
label: string;
color: string;
count: number;
/** the group's records (the denominator) */
of: number;
/** none when the group has no records: a rate over nothing is not drawn */
percent?: number;
/** "2/5 · 40.0 %"; "0/0 · —" for an empty group */
text: string;
}
export interface Group {
code: string;
label: string;
/** the group's records */
total: number;
/** why the group has no figures */
hint?: string;
rows: GroupRow[];
}
export interface Groups {
groups: Group[];
note?: string;
}
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar {
label: string;
/** why the row has no figures: no patients in the group, or not available */
hint?: string;
color?: string;
width: number;
marks: number[];
cells: string[];
/** the bar in parts (in % of the bar), each with what it says when hovered */
segments?: { width: number; color: string; title: string }[];
/** said in place of the bar (a row with nothing to draw) */
none?: string;
}
export interface Bars {
head: string[];
rows: Bar[];
/** the colour of the quartile marks, when the card has its own */
markColor?: string;
/** what the reader must know to take the rows right */
note?: string;
/** the colours of the segments */
legend?: { label: string; color: string }[];
}
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.';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** A group the report does not list is zero patients only when the groups it lists add up to every
* patient of the period (the report leaves out empty groups); otherwise it is not available. */
export function reconciles(listed: number[], total: number): boolean {
return listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
}
/** The patients of a reading: its cohort, or the denominator of a proportion. */
export const patients = (r?: Reading) =>
r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
/** Why a card of a "complete" mode, or a figure by groups, has nothing to draw though its period
* has records: the report does not publish the breakdown. Undefined when there is nothing to say. */
export function unavailable(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
const groups = mode.kind === 'grouped' || (mode.kind === 'figure' && mode.figure === 'scenarios');
const complete = 'complete' in mode && mode.complete;
if (!(groups || complete) || !('stratum' in mode) || !mode.stratum) return undefined;
const r = of(mode.measure);
if (!patients(r)) return undefined;
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
return Object.keys(r?.strata[key] ?? {}).length
? undefined
: `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
}
/** What a card says about the categories it does not draw: how many records they hold and that
* they stay in the total and the percentages. Undefined when none is in the period. */
export function hiddenNote(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
if (!('hidden' in mode) || !mode.hidden) return undefined;
const { codes, unit } = mode.hidden;
const cells = of(mode.measure)?.strata['category'] ?? {};
const found = codes.filter((c) => size(cells[c]));
if (!found.length) return undefined;
const n = found.reduce((t, c) => t + size(cells[c]), 0);
const names = found.map((c) => name(c)).join(', ');
const one = n === 1;
return `${n} ${one ? unit.replace(/s$/, '') : unit} (${names}) ${one ? 'no se muestra desglosado; está incluido' : 'no se muestran desglosados; están incluidos'} en el total y en los porcentajes.`;
}
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
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);
if (!total) return undefined;
// a category outside the catalog is listed after it, so the shares add up
const hidden = mode.hidden?.codes ?? [];
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c) && !hidden.includes(c));
const all = [
...mode.catalog.filter((c) => !hidden.includes(c.code)),
...rest.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
];
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return {
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: all.map(({ code, label, color }) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
note: hiddenNote(mode, of),
};
}
case 'shares': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
if (!mode.complete)
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [
name(c),
cells[c]['numerator'] ?? 0,
cells[c]['denominator'] ?? 0,
mode.colors?.[c],
]),
mode.percentLabel,
);
if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) =>
whole(cells[c]?.['numerator']) &&
whole(cells[c]?.['denominator']) &&
cells[c]['numerator'] <= cells[c]['denominator'];
const ok = reconciles(
Object.keys(cells).map((c) => cells[c]['denominator']),
patients(r),
);
return complete(
mode.order,
Object.keys(cells),
ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors,
mode.percentLabel,
);
}
case 'positives': {
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
if (!mode.complete)
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
}),
mode.percentLabel,
);
if (!patients(r) || !found.size) return undefined;
const ok = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
return complete(
mode.order,
[...found],
ok,
(c) => {
const positive = size(cells[`${c}|positive`]);
return [positive, positive + size(cells[`${c}|negative`])];
},
mode.colors,
mode.percentLabel,
);
}
case 'signs': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}),
mode.percentLabel,
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
mode.tint,
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
mode.tint,
);
}
case 'split': {
const { numerator = 0, denominator = 0 } = of(mode.measure)?.populations ?? {};
if (!denominator) return undefined;
const parts: [string, number][] = [
[mode.yes, numerator],
[mode.no, denominator - numerator],
];
return {
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
rows: parts.map(([label, n], i) => ({
label,
color: mode.colors?.[i],
width: (100 * n) / denominator,
marks: [],
cells: [`${n}`, pct(n, denominator)],
})),
};
}
case 'outcomes': {
const r = of(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
return {
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'],
legend: mode.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),
0,
);
return {
label,
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: mode.results.map((x, i) => ({
width: n ? (100 * by[i]) / n : 0,
color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
})),
cells: [
`${n}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? den
? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')]
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
}),
};
}
default:
return undefined;
}
}
/** 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`). */
export function grouped(
mode: Mode,
of: (measure: string) => Reading | undefined,
): Groups | undefined {
if (mode.kind !== 'grouped') return undefined;
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
if (!patients(r) || !found.length) return undefined;
const n = (g: string, c: string) => size(cells[`${g}|${c}`]);
const reconciled = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
const codes = [
...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
...found.filter((g) => !mode.order.includes(g)),
];
const total = (g: string) =>
mode.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === 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 den = total(code);
return {
code,
label: name(code),
total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
rows: mode.catalog.map((c) => {
const count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined;
return {
label: c.label,
color: c.color,
count,
of: den,
percent,
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`,
};
}),
};
});
let note = hiddenNote(mode, of);
if (mode.complete) {
const unclassified = total('no_data');
const classified = groups.filter((g) => g.code !== 'no_data');
const none = classified.every((g) => !g.total);
const sentence = !reconciled
? '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;
note = [sentence, note].filter(Boolean).join(' ') || undefined;
}
return { groups, note };
}
/** Every group of a stratifier the card names, in its order: those the report lists with their
* counts; those it leaves out as no patients when the counts add up to the period's patients,
* else as not available. "Sin dato" keeps its own counts. */
function complete(
order: string[],
listed: string[],
reconciled: boolean,
counts: (code: string) => [number, number] | undefined,
colors: Colors = {},
percentLabel = 'Porcentaje',
): Bars {
const extra = listed.filter((c) => !order.includes(c));
const rows: Bar[] = [...order, ...extra].map((code) => {
const label = name(code);
const color = colors[code];
if (!listed.includes(code))
return reconciled
? { label, color, hint: NO_PATIENTS, width: 0, marks: [], cells: ['0/0', '—'] }
: { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const found = counts(code);
if (!found)
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const [n, total] = found;
return {
label,
color,
hint: total ? undefined : NO_PATIENTS,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
};
});
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0;
return {
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,
};
}
function ratios(
rows: [string, number, number, string?][],
percentLabel = 'Porcentaje',
): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', percentLabel],
rows: rows.map(([label, n, total, color]) => ({
label,
color,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = { score?: number; low?: number; high?: number };
function medians(
rows: { label: string; n: number; score?: Score }[],
tint?: Tint,
): 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 at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'Observaciones', 'Q1–Q3'],
markColor: tint?.mark,
rows: rows.map(({ label, n, score: s }) => {
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,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
};
}),
};
}
+76
View File
@@ -0,0 +1,76 @@
import { bars, Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
HPV_COLORS,
NEUTRAL,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
REQUEST_COLORS,
ROUND_COLORS,
STEEL,
} from './cacu-palette';
import type { Measure } from 'fhir/r4';
import { donut, Reading } from './measures';
const VPH = { negative: HPV_COLORS['negative'], positive: HPV_COLORS['positive_other'] };
describe('CaCu palette', () => {
it('a PPV group has the colour of its category elsewhere on the page', () => {
expect(PPV_CYTOLOGY_COLORS['ascus_plus']).toBe(CYTOLOGY_COLORS['ASC-US']);
expect(PPV_CYTOLOGY_COLORS['lsil_plus']).toBe(CYTOLOGY_COLORS['LSIL']);
expect(PPV_CYTOLOGY_COLORS['hsil_plus']).toBe(CYTOLOGY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['cin1_plus']).toBe(BIOPSY_COLORS['LSIL']);
expect(PPV_LEVEL_COLORS['cin2_plus']).toBe(BIOPSY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['carcinoma']).toBe(BIOPSY_COLORS['carcinoma']);
expect(HPV_COLORS['hpv_16']).toBe(HPV_COLORS['positive_16']);
expect(HPV_COLORS['hpv_18']).toBe(HPV_COLORS['positive_18']);
expect(HPV_COLORS['positive']).toBe(HPV_COLORS['positive_other']);
expect(REQUEST_COLORS['high_grade']).toBe(CYTOLOGY_COLORS['HSIL']);
});
it('"Sin dato" and what is not classified are neutral everywhere', () => {
for (const colors of [
CYTOLOGY_COLORS,
HPV_COLORS,
BIOPSY_COLORS,
ROUND_COLORS,
PPV_CYTOLOGY_COLORS,
])
expect(colors['no_data']).toBe(NEUTRAL);
expect(REQUEST_COLORS['pending']).toBe(NEUTRAL);
expect(PPV_DONUT['rest']).toBe(NEUTRAL);
expect(ROUND_COLORS['initial']).toBe(STEEL);
});
it('a donut colours by category, not by place in the report', () => {
const measure = { scoring: { coding: [{ code: 'cohort' }] } } as unknown as Measure;
const cells = (order: string[]): Reading => ({
populations: {},
strata: { category: Object.fromEntries(order.map((c) => [c, { 'initial-population': 1 }])) },
});
const colours = (order: string[]) =>
(donut(measure, cells(order), 'category', VPH).data[0] as any).marker.colors;
expect(colours(['negative', 'positive'])).toEqual([VPH['negative'], VPH['positive']]);
expect(colours(['positive', 'negative'])).toEqual([VPH['positive'], VPH['negative']]);
});
it('bars take their colour from the mode by group, absent groups included', () => {
const r: Reading = {
populations: { 'initial-population': 5 },
strata: { round: { subsequent: { numerator: 1, denominator: 5 } } },
};
const mode: Mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
complete: true,
colors: ROUND_COLORS,
};
expect(bars(mode, () => r)!.rows.map((x) => x.color)).toEqual([
ROUND_COLORS['initial'],
ROUND_COLORS['subsequent'],
ROUND_COLORS['no_data'],
]);
});
});
+88
View File
@@ -0,0 +1,88 @@
/** The colours of CaCu's charts, by category. A colour names a category (never a position in a
* report, never a threshold), so the same category looks the same on every card; neutral greys
* are for what is absent or not classified. They live here, not in the shared palette, so that no
* other domain (CaMa, TEA) takes them. */
/** Not classified, or no data. */
export const NEUTRAL = '#C9CDD2';
/** Not classified, a little darker: what a report names but a card does not. */
export const NEUTRAL_DARK = '#9AA3AB';
/** The steel tones of the groups that are not results: rounds, ages, follow-up status. */
export const STEEL = '#5F7F9A';
export const STEEL_MID = '#8FA7BB';
export const STEEL_LIGHT = '#B5C5D3';
/** Cytology by Bethesda category. */
export const CYTOLOGY_COLORS: Record<string, string> = {
NILM: '#408651',
'ASC-US': '#2778B8',
LSIL: '#B19525',
'ASC-H': '#7955B1',
HSIL: '#CE4778',
CIS: '#AA394D',
no_data: NEUTRAL,
};
/** HPV by genotype; `positive` (any high-risk type) is the colour of "positive other". */
export const HPV_COLORS: Record<string, string> = {
negative: '#42A77E',
positive_16: '#DF8640',
positive_18: '#C29C42',
positive_16_18: '#C24269',
positive_other: '#A8C243',
positive_incomplete: '#9C42C2',
inconsistent: '#687786',
positive: '#A8C243',
hpv_16: '#DF8640',
hpv_18: '#C29C42',
no_data: NEUTRAL,
};
/** Biopsy by the grade it states; the levels of a PPV (that grade or worse) take its colour. */
export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651',
LSIL: '#B19525',
HSIL: '#CE4778',
CIS: '#AA394D',
carcinoma: '#8D4C79',
cin1_plus: '#B19525',
cin2_plus: '#CE4778',
no_data: NEUTRAL,
};
/** What became of the biopsy requests: high grade is the colour of LIEAG, the rest steel. */
export const REQUEST_COLORS: Record<string, string> = {
high_grade: '#CE4778',
below_high_grade: STEEL_MID,
pending: NEUTRAL,
no_grade: NEUTRAL_DARK,
};
/** Detection round: steel tones; "Sin dato" is neutral. */
export const ROUND_COLORS: Record<string, string> = {
initial: STEEL,
subsequent: STEEL_MID,
no_data: NEUTRAL,
};
/** Referral PPV groups: cytology and histology levels by the colour of their category, HPV by
* genotype. */
export const PPV_CYTOLOGY_COLORS: Record<string, string> = {
ascus_plus: CYTOLOGY_COLORS['ASC-US'],
lsil_plus: CYTOLOGY_COLORS['LSIL'],
hsil_plus: CYTOLOGY_COLORS['HSIL'],
no_data: NEUTRAL,
};
export const PPV_LEVEL_COLORS: Record<string, string> = {
cin1_plus: BIOPSY_COLORS['LSIL'],
cin2_plus: BIOPSY_COLORS['HSIL'],
carcinoma: BIOPSY_COLORS['carcinoma'],
};
/** The whole of a PPV card as a donut: the colours of its two parts. */
export const PPV_DONUT: Record<string, string> = { numerator: '#6A8000', rest: NEUTRAL };
/** Median bars of the screening route, and the marks of their quartiles. */
export const DURATION = '#42A77E';
export const QUARTILE = '#17324D';
@@ -0,0 +1,46 @@
import type { CamaRow } from './follow-up';
import { camaFollowUpSheet } from './follow-up-sheet';
const row = (over: Partial<CamaRow> = {}): CamaRow =>
({
patient: { resourceType: 'Patient', id: 'abcdefghijklmnop' },
status: 'pending_biopsy',
priority: 'high',
ageGroup: '50-59',
mammogram: { date: '2026-10-26', birads: '4A' },
...over,
}) as CamaRow;
const priority = (c: string) => ({ high: 'Alta' })[c as 'high'] ?? c;
// Each test fails if the list file invented a result or lost the query it answers.
describe('CaMa follow-up list as a file', () => {
it('has CaMa columns, the query and the count', () => {
const sheet = camaFollowUpSheet([row()], [['Búsqueda', 'Ninguna']], priority);
expect(sheet.head).toEqual([
'Paciente', 'CURP', 'Grupo de edad', 'Última mastografía (BI-RADS)', 'Fecha de la mastografía',
'Última biopsia', 'Fecha de reporte de la biopsia', 'Estatus de seguimiento', 'Prioridad',
]);
expect(sheet.query).toEqual([['Búsqueda', 'Ninguna'], ['Registros', '1']]);
expect(sheet.head.join()).not.toMatch(/LIEAG|VPH|Cáncer|Etapas/);
});
it('says what is missing: no biopsy, no BI-RADS, no CURP, no priority, never a made-up value', () => {
const [r] = camaFollowUpSheet(
[row({ mammogram: { date: '' }, priority: '' })],
[],
priority,
).rows;
expect(r.slice(0, 2)).toEqual(['abcdefghij', 'No disponible']);
expect(r.slice(3, 7)).toEqual(['Sin dato', 'No disponible', 'No disponible', 'No disponible']);
expect(r[8]).toBe('No disponible');
});
it('shows a biopsy with its date, or no grade when it has none', () => {
const rows = camaFollowUpSheet(
[row({ biopsy: { date: '2026-11-30', histology: 'benign' } }), row({ biopsy: { date: '2026-11-01' } })],
[],
priority,
).rows;
expect(rows[0].slice(5, 7)).toEqual(['Benigno', '2026-11-30']);
expect(rows[1].slice(5, 7)).toEqual(['Sin resultado', '2026-11-01']);
expect(rows[0][8]).toBe('Alta');
});
});
+19
View File
@@ -0,0 +1,19 @@
/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
+55
View File
@@ -0,0 +1,55 @@
import { durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
describe('durationRows', () => {
const reads: Record<string, Reading> = {
A: reading(0, 3, 0, 1),
B: reading(6, 20, 4, 8),
C: reading(undefined, 0),
};
const rows = durationRows(
[
{ label: 'zero', measure: 'A' },
{ label: 'value', measure: 'B' },
{ label: 'nothing measured', measure: 'C' },
{ label: 'no report', measure: 'D' },
{ label: 'not in the catalog', measure: 'E' },
{ label: 'no measure' },
],
(m) => reads[m],
(m) => m !== 'E',
);
it('keeps a real zero as a value', () => {
expect(rows[0]).toEqual({
label: 'zero',
status: 'value',
median: 0,
observations: 3,
low: 0,
high: 1,
});
});
it('tells no measurements from an unpublished measure', () => {
expect(rows.map((r) => r.status)).toEqual([
'value',
'value',
'empty',
'empty',
'unpublished',
'unpublished',
]);
});
it('scales from zero to the largest median or third quartile', () => {
expect(durationMax(rows)).toBe(8);
expect(durationMax([])).toBe(0);
});
});
+46
View File
@@ -0,0 +1,46 @@
import { Reading } from './measures';
/** One step of a route: its name and the measure that times it. A step with no measure is
* not published yet. */
export interface RouteStep {
label: string;
measure?: string;
}
/** One row of a duration table: the median days, how many measurements and the quartiles.
* `empty` (published, nothing measured in the period) is not `unpublished` (no measure), and
* neither is a zero: a median of 0 days is a value. */
export interface DurationRow {
label: string;
status: 'value' | 'empty' | 'unpublished';
median?: number;
observations?: number;
low?: number;
high?: number;
}
/** The rows of a route in one reading; every step keeps its row. `published` says which
* measures the catalog has. */
export function durationRows(
steps: RouteStep[],
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' };
const r = read(measure);
if (r?.score === undefined) return { label, status: 'empty' };
return {
label,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
low: r.low,
high: r.high,
};
});
}
/** The scale of a table of durations, from zero: the largest 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)));
+43 -42
View File
@@ -1,4 +1,5 @@
import { type Figure, PALETTE } from '../plot'; import { type Figure, PALETTE } from '../plot';
import { reconciles } from './bars';
import { name, type Reading } from './measures'; import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages'; import type { Catalog, Category, HistoryPanel } from './pages';
@@ -12,38 +13,6 @@ function rgba(hex: string, alpha: number): string {
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`; return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
} }
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
/** A category's count in the report (the composition's `category` stratum). */ /** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number { function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0; return r.strata['category']?.[code]?.['initial-population'] ?? 0;
@@ -108,6 +77,8 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
labels: catalog.categories.map((c) => c.label), labels: catalog.categories.map((c) => c.label),
hole: 0.74, hole: 0.74,
domain: { x: [0, 1], y: [0, 1] }, domain: { x: [0, 1], y: [0, 1] },
// along the thin ring, so a label fits its slice
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')), text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: { marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)), colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
@@ -126,14 +97,36 @@ export function scenarioBars(
catalog: Catalog, catalog: Catalog,
stratum: string, stratum: string,
label: (code: string) => string, label: (code: string) => string,
/** the groups in this order (the ones the report lists, then any other) */
order?: string[],
options: {
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
fill?: boolean;
/** a bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
} = {},
): Figure { ): Figure {
const cells = r.strata[`${stratum}-category`] ?? {}; const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) => const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
label(a).localeCompare(label(b), 'es'), const listed = Object.values(cells).map((c) => c['initial-population']);
); const empty = reconciles(listed, r.populations['initial-population'] ?? 0);
const scenarios = order
? [
...order.filter((s) => found.includes(s) || (options.fill && empty)),
...found.filter((s) => !order.includes(s)),
]
: found.sort((a, b) => label(a).localeCompare(label(b), 'es'));
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0; const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0)); const totals = scenarios.map((s) =>
const y = scenarios.map(label); options.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === s)
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0)
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
);
const y = order
? scenarios.map((s, i) => `${label(s)}<br>${options.ofAll ? 'Reportes' : 'Pacientes'}: ${totals[i]}`)
: scenarios.map(label);
return { return {
data: catalog.categories.map((c) => ({ data: catalog.categories.map((c) => ({
type: 'bar', type: 'bar',
@@ -148,9 +141,16 @@ export function scenarioBars(
layout: { layout: {
barmode: 'stack', barmode: 'stack',
xaxis: { xaxis: {
title: { text: '% de pacientes del escenario con resultado' }, title: {
text: order
? options.ofAll
? '% de los reportes del grupo'
: '% de pacientes con resultado'
: '% de pacientes del escenario con resultado',
},
ticksuffix: ' %', ticksuffix: ' %',
range: [0, 100], range: [0, 100.5],
dtick: 20,
}, },
yaxis: { yaxis: {
type: 'category', type: 'category',
@@ -159,7 +159,6 @@ export function scenarioBars(
categoryarray: y, categoryarray: y,
automargin: true, automargin: true,
}, },
legend: { orientation: 'h', y: -0.25 },
}, },
}; };
} }
@@ -305,9 +304,11 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
line: { color: '#FFFFFF', width: 2 }, line: { color: '#FFFFFF', width: 2 },
}, },
// an empty slice says nothing (its label would sit on its neighbours') // an empty slice says nothing (its label would sit on its neighbours')
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')), texttemplate: values.map((v) =>
v ? `%{label}<br>%{percent} del total de ${center}` : '',
),
textposition: 'outside', textposition: 'outside',
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>', hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`,
} as Partial<Plotly.Data>, } as Partial<Plotly.Data>,
], ],
layout: { layout: {
+48
View File
@@ -0,0 +1,48 @@
import type { Bundle } from 'fhir/r4';
import { type Sheet, saveExcel, savePdf } from '../export';
import type { Fhir } from '../fhir';
import { windowStart } from './follow-up';
import { name } from './measures';
/** The bundle's self link carries the filters that produced the displayed page. */
function exportQuery(page: Bundle) {
const self = page.link?.find((link) => link.relation === 'self')?.url;
if (!self) throw new Error('Missing follow-up query');
const applied = new URL(self).searchParams;
const cutoff = applied.get('follow-up-cutoff');
if (!cutoff) throw new Error('Missing follow-up cut-off');
applied.delete('_offset');
applied.set('_count', '200');
const params = Object.fromEntries(
[...new Set(applied.keys())].map((key) => [key, applied.getAll(key)]),
);
const start = windowStart(cutoff, Number(applied.get('follow-up-window')));
const status = applied.get('follow-up-status');
return {
params,
cutoff,
start,
window: `${start} al ${cutoff}`,
status: status ? name(status) : 'Todos',
search: applied.get('name') ?? applied.get('identifier') ?? 'Ninguna',
horizon: Number(applied.get('risk-horizon')),
birthdates: applied.getAll('birthdate'),
};
}
export async function saveFollowUp(
fhir: Fhir,
domain: string,
page: Bundle,
kind: 'xlsx' | 'pdf',
sheetFor: (pages: Bundle[], query: ReturnType<typeof exportQuery>) => Sheet,
): Promise<void> {
const query = exportQuery(page);
const pages = await fhir.all(domain, 'Patient', query.params);
const sheet = sheetFor(pages, query);
const file = `seguimiento-${domain}`;
if (kind === 'xlsx') await saveExcel(sheet, file);
else await savePdf([sheet], file, true);
}
+89
View File
@@ -0,0 +1,89 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { CamaRow, Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
const HEAD = [
'Paciente',
'CURP',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
'LIEAG+',
'Cáncer',
'Días a diagnóstico',
];
/** A cytology's result, or why it has none. */
export function cytologyResult(c: NonNullable<Row['cytology']>): string {
if (c.result) return name(c.result);
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */
export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
return {
title: 'Resultados de seguimiento',
query: [...query, ['Registros', `${rows.length}`]],
head: HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
`${r.age ?? NONE}`,
name(r.status),
r.stages
.filter((s) => s.state !== 'unknown')
.map((s) => `${s.label}: ${s.day ?? STATES[s.state]}`)
.join('\n'),
r.cytology ? `${cytologyResult(r.cytology)} (${r.cytology.date})` : NONE,
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'} (${r.hpv.date})` : NONE,
r.biopsy ? `${name(r.biopsy.histology ?? '') || 'Sin grado'} (${r.biopsy.date})` : NONE,
percent(r.risk.cin2),
percent(r.risk.cancer),
`${r.daysToDiagnosis ?? NONE}`,
]),
};
}
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,
]),
};
}
+12 -1
View File
@@ -1,5 +1,5 @@
import type { RiskAssessment } from 'fhir/r4'; import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart } from './follow-up'; import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures'; import { periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
@@ -45,3 +45,14 @@ describe('follow-up list', () => {
]); ]);
}); });
}); });
describe('ages', () => {
it('ask for the birth dates whose completed years fall in the range', () => {
expect(bornFor('2026-06-30', 36, 40)).toEqual(['le1990-06-30', 'gt1985-06-30']);
expect(bornFor('2026-06-30', null, null)).toEqual([]);
expect(bornFor('2024-02-29', 1, null)).toEqual(['le2023-02-28']);
expect([ageAt('1990-06-30', '2026-06-30'), ageAt('1990-07-01', '2026-06-30')]).toEqual([
36, 35,
]);
});
});
+34 -6
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir'; import { code, ext, resources } from '../fhir';
import { route, Stage } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */ /** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row { export interface Row {
@@ -8,6 +9,8 @@ export interface Row {
curp?: string; curp?: string;
status: string; status: string;
ageGroup: string; ageGroup: string;
age?: number;
stages: Stage[];
cytology?: { date: string; result?: string; adequacy?: string }; cytology?: { date: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean }; hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number; daysToDiagnosis?: number;
@@ -24,15 +27,36 @@ const AGE_GROUPS: [number, number][] = [
[55, 64], [55, 64],
]; ];
/** Completed years at a day. */
export function ageAt(birth: string | undefined, at: string): number | undefined {
if (!birth) return undefined;
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
return y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
}
/** The birth dates of who has completed between `from` and `to` years at a day, as FHIR's
* `birthdate` parameter. */
export function bornFor(at: string, from: number | null, to: number | null): string[] {
const back = (years: number) => `${Number(at.slice(0, 4)) - years}${at.slice(4)}`;
return [
...(from === null ? [] : [`le${valid(back(from))}`]),
...(to === null ? [] : [`gt${valid(back(to + 1))}`]),
];
}
/** February 29th in a year without one: the 28th. */
const valid = (day: string) =>
day.endsWith('-02-29') && new Date(`${day}T00:00:00Z`).getUTCMonth() !== 1
? `${day.slice(0, 8)}28`
: day;
export function ageGroup( export function ageGroup(
birth: string | undefined, birth: string | undefined,
at: string, at: string,
groups: [number, number][] = AGE_GROUPS, groups: [number, number][] = AGE_GROUPS,
): string { ): string {
if (!birth) return 'Sin dato'; const age = ageAt(birth, at);
const [by, bm, bd] = birth.split('-').map(Number); if (age === undefined) return 'Sin dato';
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const found = groups.find(([lo, hi]) => lo <= age && age <= hi); const found = groups.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`; if (found) return `${found[0]}-${found[1]}`;
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`; return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
@@ -103,6 +127,8 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff), ageGroup: ageGroup(patient.birthDate, cutoff),
age: ageAt(patient.birthDate, cutoff),
stages: route(last, cutoff),
cytology: last && { cytology: last && {
date: last.effectiveDateTime!, date: last.effectiveDateTime!,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept), result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
@@ -146,11 +172,12 @@ export interface CamaRow {
status: string; status: string;
priority: string; priority: string;
ageGroup: string; ageGroup: string;
mammogram: { date: string; birads?: string }; /** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string }; biopsy?: { date: string; histology?: string };
} }
const CAMA_AGE_GROUPS: [number, number][] = [ export const CAMA_AGE_GROUPS: [number, number][] = [
[40, 49], [40, 49],
[50, 59], [50, 59],
[60, 69], [60, 69],
@@ -196,6 +223,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
birads: mammogram birads: mammogram
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept) ? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
: undefined, : undefined,
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
}, },
biopsy: biopsy && { biopsy: biopsy && {
date: reported(biopsy)!, date: reported(biopsy)!,
+3 -3
View File
@@ -36,7 +36,7 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else { } @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms"> <mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'"> <mat-tab label="Indicadores">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" /> <app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab> </mat-tab>
<mat-tab label="Trazabilidad"> <mat-tab label="Trazabilidad">
@@ -45,7 +45,7 @@ import { Loading } from '../loading';
</ng-template> </ng-template>
</mat-tab> </mat-tab>
@if (domain() === 'cacu') { @if (domain() === 'cacu') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="Análisis de Riesgo">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-riesgos [domain]="domain()" /> <app-tab-riesgos [domain]="domain()" />
</ng-template> </ng-template>
@@ -57,7 +57,7 @@ import { Loading } from '../loading';
</ng-template> </ng-template>
</mat-tab> </mat-tab>
} @else if (domain() === 'cama') { } @else if (domain() === 'cama') {
<mat-tab label="Análisis de riesgos"> <mat-tab label="Análisis de Riesgo">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-seguimiento [domain]="domain()" /> <app-tab-seguimiento [domain]="domain()" />
</ng-template> </ng-template>
+5 -4
View File
@@ -13,13 +13,14 @@ export const LAYOUTS: Record<string, Layout> = {
'CACU_EU7', 'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE', 'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO', 'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
'CACU_DIAS_TOMA_TRATAMIENTO', 'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
], ],
route: [ route: [
{ {
label: 'Resultado de citología', label: 'Días de toma de citología a resultado',
step: 'Toma a resultado de citología', step: 'Días de toma de citología a resultado',
fromSample: 'CACU_EU_TIEMPO_REPORTE', fromSample: 'CACU_EU_TIEMPO_REPORTE',
fromStep: 'CACU_EU_TIEMPO_REPORTE', fromStep: 'CACU_EU_TIEMPO_REPORTE',
}, },
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA', fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
}, },
{ {
label: 'Diagnóstico', label: 'Diagnóstico tras biopsia',
step: 'Del resultado de biopsia al diagnóstico', step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO', fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO', fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
}, },
], ],
+49 -6
View File
@@ -50,6 +50,8 @@ export interface Reading {
high?: number; high?: number;
unit?: string; unit?: string;
strata: Record<string, Record<string, Record<string, number>>>; strata: Record<string, Record<string, Record<string, number>>>;
/** A stratum value's own score (a median and its quartiles). */
scores?: Record<string, Record<string, { score?: number; low?: number; high?: number }>>;
} }
function counts(group: { function counts(group: {
@@ -65,6 +67,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined; if (!group) return undefined;
const score = group.measureScore; const score = group.measureScore;
const strata: Reading['strata'] = {}; const strata: Reading['strata'] = {};
const scores: NonNullable<Reading['scores']> = {};
for (const s of group.stratifier ?? []) { for (const s of group.stratifier ?? []) {
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`. // A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
@@ -76,6 +79,13 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
counts(x), counts(x),
]), ]),
); );
for (const { value, measureScore: own } of s.stratum ?? [])
if (own)
(scores[name] ??= {})[value?.text ?? ''] = {
score: own.value,
low: ext(own, 'q1')?.valueDecimal,
high: ext(own, 'q3')?.valueDecimal,
};
} }
return { return {
populations: counts(group), populations: counts(group),
@@ -84,6 +94,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit, unit: score?.unit,
strata, strata,
scores,
}; };
} }
@@ -95,6 +106,7 @@ export const LABELS: Record<string, string> = {
normal: 'Normal', normal: 'Normal',
carcinoma: 'Carcinoma', carcinoma: 'Carcinoma',
no_data: 'Sin dato', no_data: 'Sin dato',
'<25': '<25 años (sin límite inferior)',
no_biopsy: 'Sin biopsia', no_biopsy: 'Sin biopsia',
pre_colposcopy: 'Pre colposcopia', pre_colposcopy: 'Pre colposcopia',
post_colposcopy: 'Post colposcopia', post_colposcopy: 'Post colposcopia',
@@ -122,6 +134,22 @@ export const LABELS: Record<string, string> = {
good: 'Bueno', good: 'Bueno',
bad: 'Malo', bad: 'Malo',
not_analyzed: 'Sin analizar', not_analyzed: 'Sin analizar',
initial: 'Detección inicial',
subsequent: 'Detección subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
positive_incomplete: 'Positivo con genotipificación incompleta',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries( ...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
), ),
@@ -134,6 +162,13 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento', follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado', result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía', birads: 'BI-RADS de la mastografía',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}; };
export const name = (value: string) => LABELS[value] ?? value; export const name = (value: string) => LABELS[value] ?? value;
@@ -149,14 +184,14 @@ export function formatScore(measure: Measure, r: Reading | undefined): string {
} }
} }
export function detail(measure: Measure, r: Reading | undefined): string { export function detail(measure: Measure, r: Reading | undefined, unit = 'pacientes'): string {
if (!r) return ''; if (!r) return '';
const p = r.populations; const p = r.populations;
switch (scoring(measure)) { switch (scoring(measure)) {
case 'proportion': case 'proportion':
return r.score === undefined return r.score === undefined
? 'Sin pacientes en el periodo.' ? `Sin ${unit} en el periodo.`
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`; : `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable': case 'continuous-variable':
return r.score === undefined return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.` ? `${p['initial-population'] ?? 0} sin medición en el periodo.`
@@ -169,15 +204,23 @@ export function detail(measure: Measure, r: Reading | undefined): string {
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`); const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */ /** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure { export function donut(
let labels: string[], values: number[]; measure: Measure,
r: Reading,
stratifier = 'category',
/** a colour by category code (a proportion: `numerator` and `rest`); a part without one takes the palette's */
colors?: Record<string, string>,
): Figure {
let labels: string[], values: number[], codes: string[];
if (scoring(measure) === 'proportion') { if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations; const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto']; labels = ['Numerador', 'Resto'];
codes = ['numerator', 'rest'];
values = [numerator, denominator - numerator]; values = [numerator, denominator - numerator];
} else { } else {
const cells = Object.entries(r.strata[stratifier] ?? {}); const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v)); labels = cells.map(([v]) => name(v));
codes = cells.map(([v]) => v);
values = cells.map(([, c]) => c['initial-population'] ?? 0); values = cells.map(([, c]) => c['initial-population'] ?? 0);
} }
return { return {
@@ -189,7 +232,7 @@ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Fi
values, values,
sort: false, sort: false,
textinfo: 'value+percent', textinfo: 'value+percent',
marker: { colors: PALETTE }, marker: { colors: codes.map((c, i) => colors?.[c] ?? PALETTE[i % PALETTE.length]) },
}, },
], ],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } }, layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
+361
View File
@@ -0,0 +1,361 @@
import type { Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
DURATION,
HPV_COLORS,
PPV_CYTOLOGY_COLORS,
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';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: CYTOLOGY_COLORS['NILM'], group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: CYTOLOGY_COLORS['ASC-US'], group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: CYTOLOGY_COLORS['LSIL'], group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: BIOPSY_COLORS['HSIL'], group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
{
code: 'carcinoma',
label: 'Carcinoma invasor',
color: BIOPSY_COLORS['carcinoma'],
group: 'high',
},
],
faded: ['normal', 'LSIL'],
};
/** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [
{ code: 'negative', label: 'Negativo', color: HPV_COLORS['negative'] },
{ code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
{ code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
{ code: 'positive_other', label: 'Positivo sin genotipo', color: HPV_COLORS['positive_other'] },
];
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 };
/** The screening rounds, in the order the cards draw them. */
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». ' +
'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 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'],
unit: 'reportes',
};
/** One measure's breakdowns by group, each as stacked bars of the categories of `catalog`. */
const groupViews = (
measure: string,
catalog: { code: string; label: string; color: string }[],
unit: string,
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {},
): 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: more.ofAll
? '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,
percentLabel: string,
...more: Mode[]
): ReadingsCard => ({
kind: 'readings',
title,
headline: measure,
footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT, percentLabel },
{
kind: 'shares',
label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure,
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',
label: 'VPH previo',
caption: 'Los grupos se traslapan.',
measure,
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',
label: 'Nivel de histología',
measure,
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',
caption: ROUND_CAPTION,
measure,
stratum: 'round',
colors: ROUND_COLORS,
order: ROUNDS,
complete: true,
percentLabel: 'Porcentaje de pacientes de cada ronda',
},
...more,
],
});
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
export const CACU: Page = {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Días de toma de citología a resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Días de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Días de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Días de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempos de tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [
{
kind: 'days',
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 colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{
label: 'Diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
},
{
kind: 'days',
tint: TINT,
label: 'Por ventana de tiempo',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
{
label: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE',
},
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
],
},
{
kind: 'days',
tint: TINT,
label: 'Primer diagnóstico',
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
},
{
kind: 'days',
tint: TINT,
label: 'Diagnóstico tras biopsia',
steps: [
{
label: 'Toma a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
},
],
},
],
},
],
clinical: [
{
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],
sections: [
{
kind: 'readings',
follows: true,
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,
unit: 'Pacientes',
percentLabel: 'Porcentaje de pacientes',
},
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'),
],
},
{
kind: 'readings',
follows: true,
title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.',
modes: [
{
kind: 'counts',
label: GENERAL,
measure: 'CACU_VPH_GENOTIPO',
catalog: HPV,
unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de VPH',
hidden: HPV_HIDDEN,
},
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
ofAll: true,
hidden: HPV_HIDDEN,
}),
],
},
{
kind: 'readings',
title: 'Resultados de biopsia cervical',
note: 'Reportes, por fecha de reporte.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories,
unit: 'Reportes',
percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
],
},
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
choices: [
{
label: 'Colposcopía',
section: ppv(
'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',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
'Tasa de confirmación histopatológica de referencia a biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
'Porcentaje de biopsias reportadas',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
unit: 'Solicitudes',
percentLabel: 'Porcentaje de solicitudes',
},
),
},
],
},
],
};
+145 -168
View File
@@ -1,3 +1,7 @@
import type { Mode } from './bars';
import { CACU } from './pages-cacu';
import type { RouteStep } from './durations';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui): /** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures. * the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */ * Measures are named by their code (`Measure.name`). */
@@ -17,8 +21,44 @@ export interface Kpi {
value?: string; value?: string;
note?: string; note?: string;
} }
/** A card read one mode at a time; `headline` is the measure its score comes from. */
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;
modes: Mode[];
/** in a `columns` section with `views`: takes the mode whose label the section's selector chose */
follows?: boolean;
}
export type Section = export type Section =
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] } | ReadingsCard
/** A screening route as one compact card: a bar per step with its median, observations and
* quartiles. `sample` reads each step from the sample (its own measure, never a sum of
* medians); `step` reads each from the previous step. A reading with no steps is not offered. */
| { kind: 'route'; title: string; sample: RouteStep[]; step: RouteStep[] }
/** Cards side by side; the last one alone when odd. */
| {
kind: 'columns';
title: string;
sections: ReadingsCard[];
/** one selector for the cards that `follow` it: the labels of their modes, the first by default */
views?: string[];
viewsLabel?: string;
}
/** One section at a time. */
/** `card`: the title, the tabs and the chosen reading in one card (the reading's own title is
* left out: its tab names it) */
| {
kind: 'choice';
title: string;
choices: { label: string; section: ReadingsCard }[];
card?: boolean;
}
| { kind: 'figures'; title?: string; figures: FigureSpec[] } | { kind: 'figures'; title?: string; figures: FigureSpec[] }
| { | {
kind: 'boxes'; kind: 'boxes';
@@ -80,47 +120,10 @@ export interface Catalog {
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
],
faded: ['normal', 'LSIL'],
};
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = { const CAMA_DAYS = {
value: '{median} días (mediana)', value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.', note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
}; };
const PENDING = 'Este indicador aún no está publicado por el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */ /** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = { const BIRADS: Catalog = {
@@ -134,17 +137,22 @@ const BIRADS: Catalog = {
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' }, { code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
], ],
}; };
const BREAST_BIOPSY: Catalog = {
groups: [ /** A breast biopsy's grades, and what stands in their place when there is none. */
{ id: 'benign', label: 'No maligno', color: '#42C29C' }, const BIOPSY_GRADES = [
{ id: 'malignant', label: 'Maligno', color: ROSE }, { code: 'benign', label: 'Benigno', color: '#A8C243' },
], { code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2' },
categories: [ { code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2' },
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' }, ];
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' }, /** What «Sin biopsia» says, whatever the contract's category is called. */
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' }, const NO_BIOPSY_MEANS =
], '«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.';
}; const INSTITUTIONAL = '#A8C243';
const NEUTRAL = '#C9CDD2';
const NO_RESULT = [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
];
export const PAGES: Record<string, Page> = { export const PAGES: Record<string, Page> = {
tea: { tea: {
@@ -250,43 +258,43 @@ export const PAGES: Record<string, Page> = {
}, },
{ {
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA', measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de confirmación histopatológica', title: 'Tasa de detección histopatológica',
value: '{pct} %', value: '{pct} %',
note: '{num} de {den} biopsias con riesgo a carcinoma.', note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
}, },
{ {
measure: 'CAMA_EU38A', measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica', title: 'Días de toma de mastografía a interpretación radiológica',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{ {
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico', title: 'Días de interpretación radiológica a diagnóstico',
...CAMA_DAYS, ...CAMA_DAYS,
}, },
{
title: 'Tiempo de diagnóstico a tratamiento',
value: 'Indicador no disponible',
note: PENDING,
},
], ],
opportunity: [ opportunity: [
{ {
kind: 'boxes', kind: 'route',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a diagnóstico',
subtitles: true, // from the mammography: only the two measures that start at it
cards: [ sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
measure: 'CAMA_EU38A', label: 'Diagnóstico (días de tamizaje a diagnóstico)',
title: 'Tiempo de toma de mastografía a interpretación radiológica', measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
}, },
],
step: [
{ label: 'Toma de mastografía a interpretación radiológica', measure: 'CAMA_EU38A' },
{ {
label: 'Interpretación radiológica a diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO', measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
}, },
{ title: 'Tiempo de interpretación radiológica a resultado de biopsia' }, {
{ title: 'Tiempo de diagnóstico a tratamiento' }, label: 'Interpretación radiológica a resultado de biopsia',
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' }, measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
},
], ],
}, },
], ],
@@ -311,122 +319,86 @@ export const PAGES: Record<string, Page> = {
], ],
}, },
{ {
kind: 'figures', kind: 'readings',
title: 'Resultado histopatológico por categoría BI-RADS', title: 'Resultado histopatológico por categoría BI-RADS',
figures: [ 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.',
modes: [
{ {
kind: 'rates', kind: 'outcomes',
title: 'Por categoría BI-RADS, {p}', label: 'Por categoría BI-RADS',
heading: 'Resultados por paciente',
caption: NO_BIOPSY_MEANS,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads', stratum: 'birads',
rows: BIRADS.categories, rows: BIRADS.categories,
colored: true, results: [...BIOPSY_GRADES, ...NO_RESULT],
positive: ['in_situ', 'invasive'], malignant: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
}, },
{ {
kind: 'donut', kind: 'counts',
title: 'Resultado de la biopsia, {p}', label: 'Todas las categorías',
heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
measure: 'CAMA_HISTOPATOLOGIA_BIRADS', measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: BREAST_BIOPSY, catalog: [...BIOPSY_GRADES, ...NO_RESULT],
center: 'con resultado', percent: true,
percentLabel: 'Porcentaje de pacientes',
}, },
], ],
}, },
{ {
kind: 'card', kind: 'choice',
measure: 'CAMA_CONFIRMACION_BIRADS45', title: 'Confirmación histopatológica',
title: 'Tasa de confirmación histopatológica', card: true,
value: '{pct} %', choices: [
note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
},
],
},
cacu: {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
clinical: [
{
kind: 'route',
title: 'Tiempos de la ruta del tamizaje',
steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
],
},
{
kind: 'figures',
title: 'Distribución de resultados citológicos',
figures: [
{ {
kind: 'donut', label: 'Resultado de biopsias',
title: 'Distribución de resultados, {p}', section: {
measure: 'CACU_EU7', kind: 'readings',
catalog: CYTOLOGY, title: 'Resultado de biopsias',
center: 'pacientes', headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
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.',
modes: [
{
kind: 'counts',
label: 'Biopsias reportadas',
heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
percent: true,
percentLabel: 'Porcentaje de reportes de biopsia',
},
],
},
}, },
{ {
kind: 'scenario-bars', label: 'Mastografías con biopsia',
title: 'TOTAL por escenario clínico, {p}', section: {
measure: 'CACU_EU7', kind: 'readings',
catalog: CYTOLOGY, title: 'Mastografías con biopsia',
stratum: 'follow_up_status', 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.',
}, modes: [
{ {
kind: 'figures', kind: 'split',
title: 'Tasa de confirmación histopatológica', label: 'Con y sin biopsia',
figures: [ measure: 'CAMA_CONFIRMACION_BIRADS45',
{ yes: 'Con reporte de biopsia',
kind: 'rates', no: 'Sin reporte de biopsia',
title: 'Por resultado de la citología, {p}', colors: [INSTITUTIONAL, NEUTRAL],
measure: 'CACU_CONFIRMACION_CITOLOGIA', unit: 'Mastografías',
stratum: 'result', percentLabel: 'Porcentaje de mastografías',
rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)), },
positive: ['HSIL', 'CIS', 'carcinoma'], ],
axis: 'Verdaderos positivos (valor predictivo positivo)', },
},
{
kind: 'donut',
title: 'Resultado de la biopsia, {p}',
measure: 'CACU_CONFIRMACION_CITOLOGIA',
catalog: BIOPSY,
center: 'con biopsia',
}, },
], ],
}, },
], ],
}, },
cacu: CACU,
}; };
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a /** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
@@ -503,22 +475,27 @@ export const HISTORY: Record<string, History> = {
], ],
), ),
{ {
title: 'Días de la toma de la citología a su resultado', title: 'Días de toma de citología a resultado',
measure: 'CACU_EU_TIEMPO_REPORTE', measure: 'CACU_EU_TIEMPO_REPORTE',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a diagnóstico', title: 'Días de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de tamizaje a tratamiento', title: 'Días de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median',
},
{
title: 'Días de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO', measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
{ {
title: 'Tiempo de diagnóstico a tratamiento', title: 'Días de diagnóstico a tratamiento',
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO', measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
kind: 'median', kind: 'median',
}, },
@@ -0,0 +1,19 @@
import { matchesSearch, patientSearch } from './patient-search';
describe('patient search', () => {
it('asks the API by identifier for one word with a digit, else by name', () => {
expect(patientSearch(' IARM800101MNLBVR09 ')).toEqual({ identifier: 'IARM800101MNLBVR09' });
expect(patientSearch('0451A')).toEqual({ identifier: '0451A' });
expect(patientSearch('martha ibarra')).toEqual({ name: 'martha ibarra' });
expect(patientSearch('')).toEqual({});
});
it('matches in the browser by word starts, case and accents ignored', () => {
const texts = ['IBARRA RIVERA MARTHA', 'd5a6a924-f2ad', 'N0183'];
expect(matchesSearch('már riv', texts)).toBe(true);
expect(matchesSearch('d5a6', texts)).toBe(true);
expect(matchesSearch('n0183', texts)).toBe(true);
expect(matchesSearch('arth', texts)).toBe(false);
expect(matchesSearch('', texts)).toBe(true);
});
});
+83
View File
@@ -0,0 +1,83 @@
import { Component, model, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
/** A search box's text as FHIR Patient search parameters: one word with a digit is an
* identifier (a CURP or a record number); anything else is her name. */
export function patientSearch(text: string): { name?: string; identifier?: string } {
const t = text.trim();
if (!t) return {};
return /\d/.test(t) && !/\s/.test(t) ? { identifier: t } : { name: t };
}
const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
/** Whether a row matches the search in the browser (lists loaded whole): each word starts a
* word of one of its texts (a name, an identifier, the pseudonymous id). */
export function matchesSearch(text: string, texts: (string | undefined)[]): boolean {
const words = fold(text).split(/\s+/).filter(Boolean);
if (!words.length) return true;
const known = texts.filter((t): t is string => !!t).map((t) => fold(t).split(/\s+/));
return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w))));
}
/** "Buscar paciente": applied on Enter or the search button, cleared with the cross. */
@Component({
selector: 'app-patient-search',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="patient-search">
<mat-label>Buscar paciente</mat-label>
<input
matInput
type="search"
name="patient-search"
[placeholder]="hint"
[ngModel]="draft()"
[ngModelOptions]="{ standalone: true }"
(ngModelChange)="draft.set($event)"
(keydown.enter)="$event.preventDefault(); apply()"
/>
@if (value()) {
<button
mat-icon-button
matSuffix
type="button"
aria-label="Limpiar búsqueda"
(click)="clear()"
>
<mat-icon>close</mat-icon>
</button>
} @else {
<button mat-icon-button matSuffix type="button" aria-label="Buscar" (click)="apply()">
<mat-icon>search</mat-icon>
</button>
}
</mat-form-field>
`,
styles: `
.patient-search {
min-width: 18rem;
}
`,
})
export class PatientSearch {
/** The search as applied. */
readonly value = model('');
readonly searched = output<string>();
protected readonly draft = signal('');
protected readonly hint = 'Nombre, CURP o expediente';
protected apply(): void {
const text = this.draft().trim();
this.value.set(text);
this.searched.emit(text);
}
protected clear(): void {
this.draft.set('');
this.apply();
}
}
+391
View File
@@ -0,0 +1,391 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars. */
@Component({
selector: 'app-readings',
host: { '[class.cama]': 'camaStyle()' },
imports: [Loading, MatButtonToggleModule, Plot],
template: `
@if (!hideTitle()) {
<h3 class="title">{{ title() }}</h3>
}
@if (headline()) {
<p class="headline">{{ headline() }}</p>
}
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1 && !view()) {
<mat-button-toggle-group
[attr.aria-label]="title()"
[value]="mode().label"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.label) {
<mat-button-toggle [value]="m.label">{{ m.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
@if (mode().heading) {
<h4 class="heading">{{ mode().heading }}</h4>
}
@if (mode().caption) {
<p class="state">{{ mode().caption }}</p>
}
@if (loading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (missing(); as why) {
<p class="state" role="status">{{ why }}</p>
} @else if (groups(); as g) {
<div class="axis" aria-hidden="true">
<span></span>
<span class="ticks">
<span style="left: 0">0 %</span><span style="left: 25%">25 %</span
><span style="left: 50%">50 %</span><span style="left: 75%">75 %</span
><span style="left: 100%">100 %</span>
</span>
<span></span>
</div>
@for (group of g.groups; track group.code) {
<section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label">
<h4>
{{ group.label }} <span class="n">{{ countUnit() }}: {{ group.total }}</span>
@if (group.hint) {
<span class="hint">{{ group.hint }}</span>
}
</h4>
@for (row of group.rows; track row.label) {
<div class="row" [attr.data-category]="row.label">
<span class="name">{{ row.label }}</span>
<span class="track" aria-hidden="true">
<span
class="fill"
[style.width.%]="row.percent ?? 0"
[style.background]="row.color"
></span>
</span>
<span class="value">{{ row.text }}</span>
</div>
}
</section>
}
@if (g.note) {
<p class="state">{{ g.note }}</p>
}
} @else if (figure(); as f) {
<app-plot [figure]="f" [height]="height()" />
@if (hidden(); as why) {
<p class="state">{{ why }}</p>
}
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
<tr>
<th></th>
@for (h of t.head; track h) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
@if (row.hint) {
<span class="hint">{{ row.hint }}</span>
}
@if (row.none) {
<span class="none">{{ row.none }}</span>
} @else {
<span class="track" [class.parts]="!!row.segments" aria-hidden="true">
@if (row.segments; as parts) {
@for (p of parts; track $index) {
<span
class="bar"
[style.width.%]="p.width"
[style.background]="p.color"
[attr.title]="p.title"
></span>
}
} @else {
<span
class="bar"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
}
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m" [style.background]="t.markColor"></span>
}
</span>
}
</th>
@for (c of row.cells; track $index) {
<td>{{ c }}</td>
}
</tr>
}
</tbody>
</table>
@if (t.note) {
<p class="state">{{ t.note }}</p>
}
@if (t.legend; as legend) {
<p class="legend">
@for (l of legend; track l.label) {
<span><i [style.background]="l.color"></i>{{ l.label }}</span>
}
</p>
}
} @else {
<p class="state">Sin datos en el periodo.</p>
}
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`,
styles: `
:host {
display: block;
min-width: 0;
}
:host(.cama) {
overflow-x: auto;
}
.title {
margin: 0 0 8px;
}
:host(.cama) .title {
font-size: 18px;
font-weight: 500;
}
.heading {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
.headline {
font-weight: 500;
}
:host(.cama) .headline {
margin: 8px 0;
}
:host(.cama) .state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
mat-button-toggle-group {
flex-wrap: wrap;
margin: 4px 0;
}
table {
border-collapse: collapse;
width: 100%;
}
:host(.cama) table {
font-size: 13px;
}
:host(.cama) thead th {
font-weight: 500;
}
th,
td {
font-weight: 400;
padding: 4px 6px;
text-align: right;
white-space: nowrap;
}
th[scope='row'] {
text-align: left;
white-space: normal;
width: 60%;
}
.axis {
column-gap: 8px;
display: grid;
font-size: 12px;
grid-template-columns: var(--name-width) 1fr var(--value-width);
margin: 12px 0 2px;
}
.ticks {
height: 1.2em;
position: relative;
}
.ticks span {
white-space: nowrap;
position: absolute;
transform: translateX(-50%);
}
.ticks span:first-child {
transform: none;
}
.ticks span:last-child {
transform: translateX(-100%);
}
.group {
margin: 6px 0 14px;
}
.group h4 {
font-size: 0.95rem;
margin: 0 0 4px;
}
.group .n,
.group .hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
font-size: 0.8em;
font-weight: 400;
margin-left: 8px;
}
.row {
align-items: center;
column-gap: 8px;
display: grid;
font-size: 0.9rem;
grid-template-columns: var(--name-width) 1fr var(--value-width);
min-height: 22px;
}
.row .track {
background:
linear-gradient(to right, #d8dde1 1px, transparent 1px) 25% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 50% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 75% 0 / 1px 100% no-repeat,
rgba(0, 0, 0, 0.06);
display: block;
height: 10px;
}
.row .fill {
display: block;
height: 100%;
}
.row .value {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
:host {
--name-width: 8.5rem;
--value-width: 8.5rem;
}
@media (max-width: 600px) {
:host {
--name-width: 0px;
--value-width: 0px;
}
.axis {
grid-template-columns: 1fr;
}
.axis > span:not(.ticks) {
display: none;
}
.row {
grid-template-areas: 'name value' 'track track';
grid-template-columns: 1fr auto;
padding-bottom: 4px;
}
.row .name {
grid-area: name;
}
.row .value {
grid-area: value;
}
.row .track {
grid-area: track;
}
}
.hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
display: block;
font-size: 0.8em;
}
.track {
background: rgba(0, 0, 0, 0.06);
display: block;
height: 8px;
position: relative;
}
.bar {
background: #a8c243;
display: block;
height: 100%;
}
.parts {
display: flex;
}
.none {
color: rgba(0, 0, 0, 0.6);
display: block;
font-size: 12px;
font-weight: 400;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 16px;
margin: 8px 0 0;
}
.legend i {
display: inline-block;
height: 10px;
margin-right: 6px;
width: 10px;
}
.mark {
background: #333;
height: 12px;
position: absolute;
top: -2px;
width: 2px;
}
`,
})
export class Readings {
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);
readonly modes = input.required<Mode[]>();
/** The label of the mode a section's selector chose, for the cards that follow it. */
readonly view = input<string>();
readonly loading = input(false);
/** A measure's reading in the applied period, and the figure of a mode that has one. */
readonly read = input.required<(measure: string) => Reading | undefined>();
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal('');
protected readonly 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],
);
protected readonly groups = computed(() => grouped(this.mode(), this.read()));
protected readonly table = computed(() => bars(this.mode(), this.read()));
/** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => {
const m = this.mode();
if (m.kind !== 'figure' || m.figure !== 'scenarios') return 300;
const groups = (this.figure()?.data[0] as { y?: unknown[] } | undefined)?.y?.length ?? 3;
return Math.max(360, 190 + 44 * groups); // a slim bar per group, and room for legend and axis
});
/** What the card says about the categories it does not draw. */
protected readonly hidden = computed(() => hiddenNote(this.mode(), this.read()));
/** Patients in the period but no classification published: say it, do not draw nothing. */
protected readonly missing = computed(() => unavailable(this.mode(), this.read()));
protected readonly figure = computed(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
);
}
+183
View File
@@ -0,0 +1,183 @@
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';
/** A screening route as one compact card: a bar per step with its median, its observations
* and its quartiles, read step by step or cumulatively from the sample. A step that is not
* published, or has no measurements in the period, keeps its row and says so. */
@Component({
selector: 'app-route-card',
imports: [Loading, MatButtonToggleModule, MatCardModule],
template: `
<mat-card appearance="outlined">
<mat-card-content>
<div class="head">
<h3>{{ title() }}</h3>
@if (sample().length && step().length) {
<mat-button-toggle-group
aria-label="Lectura de los tiempos"
[value]="mode()"
(change)="mode.set($event.value)"
>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (loading()) {
<app-loading what="los tiempos" [figure]="true" />
} @else {
@let rows = mode() === 'sample' ? sample() : 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.
}
Las marcas indican el primer y tercer cuartil.
@if (max) {
Escala: 0 a {{ max }} días.
}
</p>
<table [attr.aria-label]="title()">
<thead>
<tr>
<th>{{ mode() === 'sample' ? 'Etapa' : 'Paso' }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr [attr.data-status]="row.status">
<th scope="row">
{{ row.label }}
@if (row.status === 'value') {
<span class="track" aria-hidden="true">
<span
class="bar"
[style.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"
></span>
<span
class="mark"
[style.left.%]="max ? (100 * row.high) / max : 0"
></span>
}
</span>
} @else {
<span class="none">
{{
row.status === 'empty'
? 'Sin mediciones en el periodo'
: 'Indicador no publicado'
}}
</span>
}
</th>
<td>{{ row.status === 'value' ? row.median + ' días' : '—' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{
row.low === undefined || row.high === undefined
? '—'
: row.low + '–' + row.high
}}
</td>
</tr>
}
</tbody>
</table>
}
</mat-card-content>
</mat-card>
`,
styles: `
:host {
display: block;
margin-top: 24px;
}
.head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
h3 {
font-size: 18px;
font-weight: 500;
margin: 0;
}
.state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
table {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
th {
font-weight: 500;
text-align: left;
}
th[scope='row'] {
padding: 5px 0;
}
td,
thead th:not(:first-child) {
font-variant-numeric: tabular-nums;
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
position: relative;
}
.bar {
background: #42a77e;
display: block;
height: 100%;
}
.mark {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.none {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
`,
})
export class RouteCard {
readonly title = input.required<string>();
/** The rows from the sample, and the rows step by step. */
readonly sample = input.required<DurationRow[]>();
readonly step = input.required<DurationRow[]>();
readonly loading = input(false);
protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax;
}
+189
View File
@@ -0,0 +1,189 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure } from 'fhir/r4';
import { Mode } from './bars';
import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { ReadingsCard, Section } from './pages';
import { Readings } from './readings';
/** The applied period's readings and the measures they are of. */
export interface Source {
loading: boolean;
reading: (measure: string) => Reading | undefined;
measure: (name: string) => Measure | undefined;
}
type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
/** A card of readings, several side by side, or one of several at a time. */
@Component({
selector: 'app-section',
imports: [MatButtonToggleModule, MatCardModule, Readings],
template: `
@let s = section();
@if (s.kind === 'readings') {
<mat-card appearance="outlined">
<mat-card-content>
<app-readings
[title]="s.title"
[camaStyle]="hasCamaHeading(s)"
[headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''"
[modes]="s.modes"
[view]="view()"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
</mat-card-content>
</mat-card>
} @else if (s.kind === 'choice' && s.card) {
@let open = chosen() || s.choices[0].label;
<mat-card appearance="outlined" class="choice-card">
<mat-card-content>
<h3 class="title">{{ s.title }}</h3>
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-readings
[title]="c.section.title"
[hideTitle]="true"
[camaStyle]="true"
[headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''"
[modes]="c.section.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
}
}
</mat-card-content>
</mat-card>
} @else {
<h2>{{ s.title }}</h2>
@if (s.kind === 'columns') {
@if (s.views) {
<mat-button-toggle-group
class="views"
[attr.aria-label]="s.viewsLabel ?? s.title"
[value]="picked() || s.views[0]"
(change)="picked.set($event.value)"
>
@for (v of s.views; track v) {
<mat-button-toggle [value]="v">{{ v }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
<div class="columns">
@for (inner of s.sections; track $index) {
<app-section
[section]="inner"
[of]="of()"
[view]="inner.follows ? picked() || s.views?.[0] : undefined"
/>
}
</div>
} @else {
@let open = chosen() || s.choices[0].label;
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-section [section]="c.section" [of]="of()" />
}
}
}
}
`,
styles: `
:host {
display: block;
margin-top: 24px;
min-width: 0;
}
.views {
flex-wrap: wrap;
margin: 4px 0 8px;
}
.title {
font-size: 18px;
font-weight: 500;
margin: 0 0 8px;
}
.choice-card app-readings {
margin-top: 8px;
}
.columns {
display: grid;
column-gap: 16px;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 480px), 1fr));
}
.columns > :last-child:nth-child(odd) {
grid-column: 1 / -1;
}
`,
})
export class ReadingsSection {
readonly section = input.required<Shown>();
readonly of = input.required<Source>();
/** The mode a card of a `columns` section takes from the section's selector (its label). */
readonly view = input<string>();
/** The view a columns section's selector has chosen. */
protected readonly picked = signal('');
protected readonly chosen = signal('');
protected hasCamaHeading(s: ReadingsCard): boolean {
return s.modes.some((mode) => !!mode.heading);
}
/** A reading card's headline: its measure's score and its counts, in its own units. */
protected headlineOf(s: ReadingsCard): string {
const code = s.headline;
const measure = code && this.of().measure(code);
const r = code && this.of().reading(code);
if (!measure || !r) return '';
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);
const measure = this.of().measure(mode.measure);
if (!measure || !r?.populations['initial-population']) return undefined;
if (mode.figure === 'donut') return donut(measure, r, 'category', mode.colors);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(
r,
{ groups: [], categories },
mode.stratum ?? 'follow_up_status',
name,
mode.order,
{ fill: mode.complete, ofAll: mode.ofAll },
);
});
}
+32 -13
View File
@@ -34,7 +34,7 @@
@if (reports.error()) { @if (reports.error()) {
<div class="load-error" role="alert"> <div class="load-error" role="alert">
<p>No se pudieron leer los indicadores del periodo. Vuelve a intentar.</p> <p>No se obtuvieron los indicadores del periodo.</p>
<button mat-stroked-button (click)="reports.reload()">Reintentar</button> <button mat-stroked-button (click)="reports.reload()">Reintentar</button>
</div> </div>
} }
@@ -45,7 +45,11 @@
<h2 id="opportunity-title">Indicadores de oportunidad</h2> <h2 id="opportunity-title">Indicadores de oportunidad</h2>
<span class="period">Periodo {{ period }}</span> <span class="period">Periodo {{ period }}</span>
</div> </div>
<div class="kpis"> <div
class="kpis"
[style.--kpi-cols-md]="pg.kpis.length < 3 ? pg.kpis.length : 3"
[style.--kpi-cols-lg]="pg.kpis.length < 5 ? pg.kpis.length : 5"
>
@for (k of pg.kpis; track k.title) { @for (k of pg.kpis; track k.title) {
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null"> <mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
<mat-card-content> <mat-card-content>
@@ -53,7 +57,13 @@
@if (reports.isLoading() && k.measure) { @if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" /> <app-loading [what]="k.title.toLowerCase()" />
} @else { } @else {
<div class="kpi-value" [class.pending]="!k.measure">{{ kpiValue(k) }}</div> <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> <div class="kpi-detail">{{ kpiNote(k) }}</div>
} }
</mat-card-content> </mat-card-content>
@@ -79,15 +89,18 @@
<ng-template #sectionView let-section let-period="period"> <ng-template #sectionView let-section let-period="period">
@switch (section.kind) { @switch (section.kind) {
@case ('readings')
@case ('columns')
@case ('choice') {
<app-section [section]="section" [of]="of()" />
}
@case ('route') { @case ('route') {
<h3 class="route-title">{{ section.title }}</h3> <app-route-card
@if (reports.isLoading()) { [title]="section.title"
<app-loading what="los tiempos de la ruta" [figure]="true" /> [sample]="stepRows(section, 'sample')"
} @else if (routeOf(section); as fig) { [step]="stepRows(section, 'step')"
<app-plot [figure]="fig" [height]="300" /> [loading]="reports.isLoading()"
} @else { />
<p class="state">Sin tiempos publicados en el periodo.</p>
}
} }
@case ('tea-summary') { @case ('tea-summary') {
@if (teaSummary(); as t) { @if (teaSummary(); as t) {
@@ -152,7 +165,7 @@
<mat-card-content> <mat-card-content>
<h2 class="box-title">{{ b.title }}</h2> <h2 class="box-title">{{ b.title }}</h2>
@if (!b.measure) { @if (!b.measure) {
<p class="state"><strong>Integración pendiente.</strong> {{ pending }}</p> <p class="state">{{ pending }}</p>
<div class="empty-figure">Sin datos publicados</div> <div class="empty-figure">Sin datos publicados</div>
} @else { } @else {
<p class="state">Filtro general aplicado: {{ period }}</p> <p class="state">Filtro general aplicado: {{ period }}</p>
@@ -177,7 +190,13 @@
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure"> <mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
<mat-card-content> <mat-card-content>
<h3 class="kpi-title">{{ section.title }}</h3> <h3 class="kpi-title">{{ section.title }}</h3>
<div class="kpi-value">{{ kpiValue(section) }}</div> <div class="kpi-value">
@let w = kpiParts(kpiValue(section));
{{ w[0] }}
@if (w[1]) {
<span class="kpi-qualifier">{{ w[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(section) }}</div> <div class="kpi-detail">{{ kpiNote(section) }}</div>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+10 -2
View File
@@ -42,13 +42,13 @@ h2 {
@media (min-width: 1000px) { @media (min-width: 1000px) {
.kpis { .kpis {
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(var(--kpi-cols-md, 3), 1fr);
} }
} }
@media (min-width: 1350px) { @media (min-width: 1350px) {
.kpis { .kpis {
grid-template-columns: repeat(5, 1fr); grid-template-columns: repeat(var(--kpi-cols-lg, 5), 1fr);
} }
} }
@@ -61,6 +61,14 @@ h2 {
font-size: 2rem; font-size: 2rem;
font-weight: 500; font-weight: 500;
margin: var(--space-2) 0; margin: var(--space-2) 0;
line-height: 1.15;
}
.kpi-qualifier {
display: block;
font-size: 14px;
font-weight: 400;
color: var(--color-text-secondary);
} }
.kpi-detail { .kpi-detail {
+30 -9
View File
@@ -8,6 +8,7 @@ import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4'; import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { DurationRow, durationRows } from './durations';
import { LAYOUTS } from './layout'; import { LAYOUTS } from './layout';
import { import {
ageShare, ageShare,
@@ -17,7 +18,6 @@ import {
fill, fill,
nestedDonut, nestedDonut,
rateDots, rateDots,
routeFigure,
scenarioBars, scenarioBars,
shareDonut, shareDonut,
} from './figures'; } from './figures';
@@ -38,6 +38,8 @@ import {
strataBars, strataBars,
} from './measures'; } from './measures';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { RouteCard } from './route-card';
import { ReadingsSection, Source } from './section';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per /** The period's indicators: the timeliness KPIs, the screening route, and a card per
* clinical measure with its figures. */ * clinical measure with its figures. */
@@ -52,6 +54,8 @@ import { Loading } from '../loading';
MatCardModule, MatCardModule,
MatSelectModule, MatSelectModule,
Plot, Plot,
ReadingsSection,
RouteCard,
], ],
templateUrl: './tab-indicadores.html', templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss', styleUrl: './tab-indicadores.scss',
@@ -71,8 +75,7 @@ export class TabIndicadores {
protected readonly layout = computed( protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
); );
protected readonly pending = protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
'Este indicador aún no está publicado por el catálogo institucional.';
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */ /** The old app's page for this domain, when it is rebuilt as it was (else today's). */
protected readonly page = computed(() => PAGES[this.domain()]); protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m]))); private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
@@ -194,6 +197,15 @@ export class TabIndicadores {
} }
protected readonly name = name; protected readonly name = name;
protected stepRows(section: Section, mode: 'sample' | 'step'): DurationRow[] {
if (section.kind !== 'route') return [];
return durationRows(
section[mode],
(code) => this.rd(code),
(code) => this.byName().has(code),
);
}
/** A measure's reading in the applied period, by code. */ /** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined { protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code); return this.loaded()?.get(code);
@@ -202,6 +214,12 @@ export class TabIndicadores {
return this.byName().get(code); return this.byName().get(code);
} }
/** A card's value and note, from its templates (a card with no measure: its words). */ /** A card's value and note, from its templates (a card with no measure: its words). */
/** "27 días (mediana)" as the value and its qualifier, shown smaller beneath it. */
protected kpiParts(text: string): [string, string] {
const found = /^(.*?)\s*(\([^)]*\))$/.exec(text);
return found ? [found[1], found[2]] : [text, ''];
}
protected kpiValue(k: Kpi): string { protected kpiValue(k: Kpi): string {
if (!k.measure) return k.value ?? ''; if (!k.measure) return k.value ?? '';
const r = this.rd(k.measure); const r = this.rd(k.measure);
@@ -259,12 +277,15 @@ export class TabIndicadores {
protected measureTitle(code: string | undefined): string { protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || ''; return (code && this.byName().get(code)?.title) || '';
} }
/** A clinical section's route or figures, drawn from the applied period's reports. */ /** What a section of readings is drawn from. */
protected routeOf(section: Section): Figure | undefined { protected readonly of = computed<Source>(() => {
if (section.kind !== 'route') return undefined; const found = this.loaded();
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) })); return {
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined; loading: this.reports.isLoading(),
} reading: (code) => found?.get(code),
measure: (code) => this.byName().get(code),
};
});
protected figureOf(spec: FigureSpec): Figure | undefined { protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure); const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined; if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
+2 -1
View File
@@ -1,6 +1,7 @@
<section class="card risk-tea" aria-labelledby="tea-risk-title"> <section class="card risk-tea" aria-labelledby="tea-risk-title">
<h2 id="tea-risk-title" class="risk-title">Alteraciones de EEG relacionadas al TEA</h2> <h2 id="tea-risk-title" class="risk-title">Alteraciones de EEG relacionadas al TEA</h2>
<div class="filters"> <div class="filters">
<app-patient-search [(value)]="search" (searched)="pageIndex.set(0)" />
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" /> <input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" />
@@ -147,7 +148,7 @@
</tr> </tr>
} @empty { } @empty {
<tr> <tr>
<td colspan="7" class="muted">Nadie en la lista con estos filtros.</td> <td colspan="7" class="muted">No hay registros para los filtros aplicados.</td>
</tr> </tr>
} }
</tbody> </tbody>
+17 -3
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { KeyValuePipe } from '@angular/common'; import { KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
@@ -11,6 +12,7 @@ import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { ageLabel } from './figures'; import { ageLabel } from './figures';
import { name } from './measures'; import { name } from './measures';
import { matchesSearch, PatientSearch } from './patient-search';
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */ /** One child on TEA's list, as the list shows her (core.tea.follow_up). */
export interface TeaRow { export interface TeaRow {
@@ -67,14 +69,18 @@ const CASE: Record<string, string> = {
not_confirmed: 'Sin TEA', not_confirmed: 'Sin TEA',
}; };
/** `theta_power:above` → "theta_power (aumentado)". */ /** `theta_power:above` → "theta_power (aumentado)". */
export const alteration = (a: string) => export const alteration = (a: string) => {
a.replace(/:(above|below)$/, (_, s) => (s === 'above' ? ' (aumentado)' : ' (disminuido)')); const [metric, side] = a.split(':');
const shown = (METRIC_NAMES[metric] ?? metric).replace(/ \(.*\)$/, '');
return side ? `${shown} (${side === 'above' ? 'aumentado' : 'disminuido'})` : shown;
};
/** "Análisis de Riesgo" for TEA: the children active in the window, what their EEGs show, /** "Análisis de Riesgo" for TEA: the children active in the window, what their EEGs show,
* filtered as the old page filtered them. */ * filtered as the old page filtered them. */
@Component({ @Component({
selector: 'app-tab-riesgos-tea', selector: 'app-tab-riesgos-tea',
imports: [ imports: [
PatientSearch,
FormsModule, FormsModule,
KeyValuePipe, KeyValuePipe,
Loading, Loading,
@@ -100,6 +106,8 @@ export class TabRiesgosTea {
protected readonly caseState = signal(''); protected readonly caseState = signal('');
protected readonly altered = signal(''); protected readonly altered = signal('');
protected readonly size = signal(50); protected readonly size = signal(50);
/** "Buscar paciente": the pseudonymous id, a record number or a name. */
protected readonly search = signal('');
protected readonly pageIndex = signal(0); protected readonly pageIndex = signal(0);
/** The query as last asked for ("Consultar"). */ /** The query as last asked for ("Consultar"). */
private readonly asked = signal({ cutoff: '', window: 3 }); private readonly asked = signal({ cutoff: '', window: 3 });
@@ -141,7 +149,13 @@ export class TabRiesgosTea {
(!band || (r.mchat !== undefined && band.test(r.mchat))) && (!band || (r.mchat !== undefined && band.test(r.mchat))) &&
(!level || (r.css !== undefined && level.test(r.css))) && (!level || (r.css !== undefined && level.test(r.css))) &&
(!this.caseState() || r.case === this.caseState()) && (!this.caseState() || r.case === this.caseState()) &&
(!this.altered() || r.alterations.includes(this.altered())), (!this.altered() || r.alterations.includes(this.altered())) &&
matchesSearch(this.search(), [
r.name,
r.patient.id,
...(r.patient.name ?? []).map((n) => n.text),
...(r.patient.identifier ?? []).map((i) => i.value),
]),
); );
}); });
protected readonly shown = computed(() => protected readonly shown = computed(() =>
+73 -13
View File
@@ -1,4 +1,5 @@
<form class="filters card" (submit)="$event.preventDefault()"> <form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input <input
@@ -9,6 +10,30 @@
name="cutoff" name="cutoff"
/> />
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad mínima</mat-label>
<input
matInput
type="number"
min="0"
max="120"
[ngModel]="ageFrom()"
(ngModelChange)="setAge(ageFrom, $event)"
name="ageFrom"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad máxima</mat-label>
<input
matInput
type="number"
min="0"
max="120"
[ngModel]="ageTo()"
(ngModelChange)="setAge(ageTo, $event)"
name="ageTo"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana de meses</mat-label> <mat-label>Ventana de meses</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)"> <mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@@ -50,7 +75,26 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form> </form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) { @if (error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
@@ -71,8 +115,9 @@
<thead> <thead>
<tr> <tr>
<th>Paciente</th> <th>Paciente</th>
<th>Grupo de edad</th> <th>Edad</th>
<th>Estatus de seguimiento</th> <th>Estatus de seguimiento</th>
<th>Etapas</th>
<th>Última citología</th> <th>Última citología</th>
<th>Último resultado de VPH</th> <th>Último resultado de VPH</th>
<th>Última biopsia</th> <th>Última biopsia</th>
@@ -86,24 +131,34 @@
@for (row of rows(); track row.patient.id) { @for (row of rows(); track row.patient.id) {
<tr> <tr>
<td> <td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{ <a
row.name ?? row.patient.id!.slice(0, 10) [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
}}</a> [queryParams]="{ corte: applied(), citologia: row.cytology?.date }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
>
@if (row.curp) { @if (row.curp) {
<div class="muted curp">{{ row.curp }}</div> <div class="muted curp">{{ row.curp }}</div>
} }
</td> </td>
<td>{{ row.ageGroup }}</td> <td>
{{ row.age ?? 'No disponible' }}
<small>Grupo: {{ name(row.ageGroup) }}</small>
</td>
<td>{{ name(row.status) }}</td> <td>{{ name(row.status) }}</td>
<td>
<app-stages [stages]="row.stages" />
<button
mat-button
type="button"
[attr.aria-expanded]="opened() === row.patient.id"
(click)="toggle(row)"
>
Detalle
</button>
</td>
<td> <td>
@if (row.cytology; as c) { @if (row.cytology; as c) {
{{ {{ result(c) }}
c.result
? name(c.result)
: c.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}}
<small>Fecha: {{ c.date }}</small> <small>Fecha: {{ c.date }}</small>
<small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small> <small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
} @else { } @else {
@@ -153,10 +208,15 @@
<td>{{ latest(row) ?? 'No disponible' }}</td> <td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td> <td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr> </tr>
@if (opened() === row.patient.id) {
<tr class="stage-detail">
<td colspan="11"><app-stages [stages]="row.stages" [detail]="true" /></td>
</tr>
}
} @empty { } @empty {
@if (page() && !loading()) { @if (page() && !loading()) {
<tr> <tr>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td> <td colspan="11" class="muted">No hay registros para los filtros aplicados.</td>
</tr> </tr>
} }
} }
+6
View File
@@ -10,6 +10,11 @@
margin-bottom: var(--space-4); margin-bottom: var(--space-4);
} }
// a field as wide as its label ("Horizonte de la probabilidad")
.filters mat-form-field {
min-width: 14.5rem;
}
.table-wrap { .table-wrap {
overflow-x: auto; overflow-x: auto;
padding: 0; padding: 0;
@@ -43,6 +48,7 @@ a {
.worklist td small { .worklist td small {
display: block; display: block;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant); color: var(--mat-sys-on-surface-variant);
font-size: 0.8em; font-size: 0.8em;
} }
+81 -17
View File
@@ -1,5 +1,13 @@
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import {
Component,
computed,
inject,
input,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
@@ -8,7 +16,11 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { Row, rows, windowStart } from './follow-up'; 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';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { name } from './measures'; import { name } from './measures';
@@ -19,6 +31,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
@Component({ @Component({
selector: 'app-tab-riesgos', selector: 'app-tab-riesgos',
imports: [ imports: [
PatientSearch,
DecimalPipe, DecimalPipe,
FormsModule, FormsModule,
Loading, Loading,
@@ -27,6 +40,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
MatInputModule, MatInputModule,
MatSelectModule, MatSelectModule,
RouterLink, RouterLink,
Stages,
], ],
templateUrl: './tab-riesgos.html', templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss', styleUrl: './tab-riesgos.scss',
@@ -41,29 +55,39 @@ export class TabRiesgos {
protected readonly horizon = signal(5); protected readonly horizon = signal(5);
protected readonly sort = signal('-recent'); protected readonly sort = signal('-recent');
protected readonly size = signal(20); protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
/** Completed years at the cut-off (none: no limit). */
protected readonly ageFrom = signal<number | null>(null);
protected readonly ageTo = signal<number | null>(null);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** Whose stages are shown in full. */
protected readonly opened = signal<string | undefined>(undefined);
/** A page the user moved to (`next`/`previous`), else the first. */ /** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined); private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
protected readonly name = name; protected readonly name = name;
protected readonly result = cytologyResult;
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
birthdate: bornFor(this.cutoff(), this.ageFrom(), this.ageTo()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({ private readonly first = resource({
params: () => ({ params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
domain: this.domain(), loader: ({ params: { domain, query, size } }) => {
'follow-up-window': this.window(),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined); this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', { return this.fhir.search(domain, 'Patient', { ...query, _count: size });
...params,
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
}, },
}); });
protected readonly loading = signal(false); protected readonly loading = signal(false);
@@ -108,6 +132,46 @@ export class TabRiesgos {
this.first.reload(); this.first.reload();
} }
/** Ages are told at the cut-off: the one shown becomes the one asked for. */
protected setAge(age: WritableSignal<number | null>, years: number | null): void {
if (!this.cutoff()) this.cutoff.set(this.applied());
age.set(years);
}
/** 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) => {
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 {
this.saving.set(false);
}
}
protected toggle(row: Row): void {
this.opened.set(this.opened() === row.patient.id ? undefined : row.patient.id);
}
protected has(relation: 'next' | 'previous'): boolean { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
+25 -3
View File
@@ -1,4 +1,5 @@
<form class="filters card" (submit)="$event.preventDefault()"> <form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input <input
@@ -34,7 +35,26 @@
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form> </form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) { @if (error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
@@ -66,9 +86,11 @@
@for (row of rows(); track row.patient.id) { @for (row of rows(); track row.patient.id) {
<tr> <tr>
<td> <td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{ <a
row.name ?? row.patient.id!.slice(0, 10) [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
}}</a> [queryParams]="{ ventana: window(), corte: applied() }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
>
@if (row.curp) { @if (row.curp) {
<div class="muted curp">{{ row.curp }}</div> <div class="muted curp">{{ row.curp }}</div>
} }
+45 -13
View File
@@ -7,7 +7,10 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { saveFollowUp } from './follow-up-export';
import { camaFollowUpSheet } from './follow-up-sheet';
import { camaRows, windowStart } from './follow-up'; import { camaRows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { name, PRIORITY } from './measures'; import { name, PRIORITY } from './measures';
@@ -18,6 +21,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy
@Component({ @Component({
selector: 'app-tab-seguimiento', selector: 'app-tab-seguimiento',
imports: [ imports: [
PatientSearch,
FormsModule, FormsModule,
Loading, Loading,
MatButtonModule, MatButtonModule,
@@ -37,27 +41,30 @@ export class TabSeguimiento {
protected readonly window = signal(3); protected readonly window = signal(3);
protected readonly status = signal<string>(''); protected readonly status = signal<string>('');
protected readonly size = signal(20); protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
private readonly moved = signal<Bundle | undefined>(undefined); private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
protected readonly name = name; protected readonly name = name;
protected readonly priority = (code: string) => PRIORITY[code] ?? code; protected readonly priority = (code: string) => PRIORITY[code] ?? code;
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({ private readonly first = resource({
params: () => ({ params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
domain: this.domain(), loader: ({ params: { domain, query, size } }) => {
'follow-up-window': this.window(),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined); this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', { return this.fhir.search(domain, 'Patient', { ...query, _count: size });
...params,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
}, },
}); });
protected readonly loading = signal(false); protected readonly loading = signal(false);
@@ -90,6 +97,31 @@ export class TabSeguimiento {
this.first.reload(); this.first.reload();
} }
/** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
const page = this.page();
if (!page) return;
this.saving.set(true);
this.saveError.set('');
try {
await saveFollowUp(this.fhir, this.domain(), page, kind, (pages, query) =>
camaFollowUpSheet(
pages.flatMap((p) => camaRows(p, query.cutoff)),
[
['Ventana consultada', query.window],
['Estatus de seguimiento', query.status],
['Búsqueda', query.search],
],
this.priority,
),
);
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected has(relation: 'next' | 'previous'): boolean { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
+2 -2
View File
@@ -33,10 +33,10 @@ interface Drawn {
</mat-button-toggle-group> </mat-button-toggle-group>
</section> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" /> <app-loading what="el histórico" text="Cargando histórico…" />
} @else if (series.error()) { } @else if (series.error()) {
<p class="muted" role="alert"> <p class="muted" role="alert">
No se pudo cargar la trazabilidad. No se pudo cargar el histórico.
<button type="button" class="retry" (click)="series.reload()">Reintentar</button> <button type="button" class="retry" (click)="series.reload()">Reintentar</button>
</p> </p>
} @else { } @else {
@@ -0,0 +1,57 @@
import { camaRecordSheets } from './cama-record-sheets';
const sheets = (over: Partial<Parameters<typeof camaRecordSheets>> = []) =>
camaRecordSheets(
(over[0] as any) ?? [['Nombre', 'Ana'], ['CURP', undefined]],
(over[1] as any) ?? [['Categoría BI-RADS de la última mastografía', '4B'], ['Resultado histopatológico', undefined]],
(over[2] as any) ?? [{ date: '2025-01-02', kind: 'Procedimiento', text: 'Mastectomía' }],
(over[3] as any) ?? [{ date: '2025-01-01', kind: 'Mastografía', reported: undefined, results: ['BI-RADS: 4B'], findings: [] }],
(over[4] as any) ?? [],
(over[5] as any) ?? [],
);
const by = (s: ReturnType<typeof sheets>, title: string) => s.find((x) => x.title.startsWith(title))!;
// Each test fails if the PDF made up a value, kept a section of CaCu or dropped what CaMa publishes.
describe('the CaMa record as a PDF', () => {
it('has only CaMa sections and says a missing value as such', () => {
const s = sheets();
expect(s.map((x) => x.title)).toEqual([
'Datos de la paciente',
'Última mastografía y resultado histopatológico',
'Historial médico',
'Pruebas y resultados',
'Riesgos y recomendaciones publicados',
]);
expect(s.some((x) => /citolog|VPH|NCI|ASCCP|Etapas/i.test(x.title + x.head.join()))).toBe(false);
expect(by(s, 'Datos').rows).toEqual([['Nombre', 'Ana'], ['CURP', 'No disponible']]);
expect(by(s, 'Última').rows[1]).toEqual(['Resultado histopatológico', 'No disponible']);
expect(by(s, 'Pruebas').rows[0].slice(0, 3)).toEqual(['2025-01-01', 'Mastografía', 'Pendiente']);
});
it('without published estimates it says there are none, with no probability', () => {
expect(by(sheets(), 'Riesgos').rows).toEqual([
['Sin estimaciones publicadas', 'No disponible', 'No disponible', 'No disponible', 'No disponible'],
]);
});
it('publishes each estimate by horizon with its interval, and a zero is a value', () => {
const s = sheets([
undefined, undefined, undefined, undefined,
[{ text: 'Supervivencia v2', index: '2026-01-01', predictions: [{ years: 0, p: 0, low: 0, high: 0.01 }, { years: 5, p: 0.8 }] }],
] as any);
expect(by(s, 'Riesgos').rows).toEqual([
['Supervivencia v2', '2026-01-01', 'Al índice', '0.00 %', '0.00 % a 1.00 %'],
['Supervivencia v2', '2026-01-01', '5 años', '80.00 %', 'No disponible'],
]);
});
it('lists the scenario curves, the ones without a curve and the group nature of the estimates', () => {
const s = sheets([
undefined, undefined, undefined, undefined, [],
[{ title: 'Supervivencia', scenarios: ['A', 'B'], figures: ['A (n = 9, fallecidos = 6)'], undrawn: ['B'] }],
] as any);
const sheet = by(s, 'Supervivencia y recurrencia');
expect(sheet.title).toContain('no predicciones individuales');
expect(sheet.rows).toEqual([
['Supervivencia', 'A (n = 9, fallecidos = 6)', 'Curva publicada'],
['Supervivencia', 'B', 'No disponible: datos insuficientes'],
]);
});
});
+106
View File
@@ -0,0 +1,106 @@
import type { Sheet } from '../export';
const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
interface Event {
date: string;
kind: string;
text: string;
}
interface Test {
date: string;
kind: string;
reported?: string;
results: string[];
findings: string[];
}
/** A published estimate (risk, survival or recurrence) of one model, by horizon. */
interface Estimate {
text: string;
index: string;
predictions: { years: number; p: number; low?: number; high?: number }[];
}
/** The curves of a patient's clinical scenarios, as the page lists them. */
interface Analysis {
title: string;
scenarios: string[];
/** the figures' titles (scenario, members and events) */
figures: string[];
/** her scenarios the report draws no curve for */
undrawn: string[];
}
const horizon = (years: number) =>
years === 0 ? 'Al índice' : `${years} ${years === 1 ? 'año' : 'años'}`;
/** A CaMa patient's record as the tables of her PDF, in the page's order. Only what CaMa publishes:
* a value that is absent says so and no estimate is made up. */
export function camaRecordSheets(
facts: [string, string | undefined][],
studies: [string, string | undefined][],
history: Event[],
tests: Test[],
estimates: Estimate[],
analyses: Analysis[],
): Sheet[] {
const risks = estimates.flatMap((m) =>
m.predictions.map((p) => [
m.text,
m.index || NONE,
horizon(p.years),
percent(p.p),
p.low === undefined || p.high === undefined ? NONE : `${percent(p.low)} a ${percent(p.high)}`,
]),
);
const curves = analyses.flatMap((a) => [
...a.figures.map((f) => [a.title, f, 'Curva publicada']),
...a.undrawn.map((s) => [a.title, s, 'No disponible: datos insuficientes']),
...(a.figures.length || a.undrawn.length
? []
: [[a.title, a.scenarios.join('; ') || NONE, NONE]]),
]);
return [
{
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Última mastografía y resultado histopatológico',
head: ['Dato', 'Valor'],
rows: studies.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos'],
rows: tests.map((t) => [
t.date,
t.kind,
t.reported ?? 'Pendiente',
t.results.join(' · '),
t.findings.join(' · '),
]),
},
{
title: 'Riesgos y recomendaciones publicados',
head: ['Estimación', 'Fecha índice', 'Horizonte', 'Probabilidad', 'IC 95 %'],
rows: risks.length ? risks : [['Sin estimaciones publicadas', NONE, NONE, NONE, NONE]],
},
...(curves.length
? [
{
title:
'Supervivencia y recurrencia por escenario clínico (estimaciones del grupo, no predicciones individuales)',
head: ['Análisis', 'Escenario', 'Estado'],
rows: curves,
},
]
: []),
];
}
+10
View File
@@ -0,0 +1,10 @@
import { figureChoices } from './curve-chooser';
describe('figureChoices', () => {
it('keeps each band with its line, one choice per curve', () => {
const data = [{ showlegend: false }, { name: 'Kaplan-Meier' }, { name: 'Weibull' }];
const { choices, draw } = figureChoices({ data: data as never });
expect(choices.map((c) => c.name)).toEqual(['Kaplan-Meier', 'Weibull']);
expect(draw(new Set(['Kaplan-Meier'])).data.length).toBe(2);
});
});
+86
View File
@@ -0,0 +1,86 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { Figure, Plot } from '../plot';
export interface Choice {
id: string;
name: string;
/** drawn before the user touches it */
on: boolean;
}
/** A figure's curves as choices, all on: a band has no name of its own and goes with the line
* after it. */
export function figureChoices(figure: Figure): { choices: Choice[]; draw: Draw } {
const groups = new Map<string, Figure['data']>();
let pending: Figure['data'] = [];
for (const trace of figure.data) {
pending.push(trace);
const { name, showlegend } = trace as { name?: string; showlegend?: boolean };
if (name && showlegend !== false) {
groups.set(name, pending);
pending = [];
}
}
return {
choices: [...groups.keys()].map((name) => ({ id: name, name, on: true })),
draw: (ids) => ({ ...figure, data: [...ids].flatMap((id) => groups.get(id) ?? []) }),
};
}
export type Draw = (ids: Set<string>) => Figure;
/** Curves chosen or not, to compare them on one plot: the record's risk and survival curves. */
@Component({
selector: 'app-curve-chooser',
imports: [MatCheckboxModule, Plot],
template: `
<div class="choices">
@for (c of choices(); track c.id) {
<mat-checkbox [checked]="chosen().has(c.id)" (change)="toggle(c.id)">
{{ c.name }}
</mat-checkbox>
}
</div>
@if (chosen().size) {
@for (note of notes()(chosen()); track note) {
<p class="muted">{{ note }}</p>
}
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
}
`,
styles: `
:host {
display: block;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
margin-bottom: 8px;
}
`,
})
export class CurveChooser {
readonly choices = input.required<Choice[]>();
readonly draw = input.required<Draw>();
/** what the chosen curves assume, said under the choices */
readonly notes = input<(ids: Set<string>) => string[]>(() => []);
/** what the user toggled away from its default */
private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed(
() =>
new Set(
this.choices()
.filter((c) => c.on !== this.toggled().has(c.id))
.map((c) => c.id),
),
);
protected readonly figure = computed(() => this.draw()(this.chosen()));
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
}
+130
View File
@@ -0,0 +1,130 @@
import { HttpErrorResponse } from '@angular/common/http';
import type { Parameters } from 'fhir/r4';
import { eligibilityFailure, eligibilityView } from './eligibility';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
const candidate = (
scenario: string,
date: string,
eligible: boolean,
criteria: string[] = [],
sample?: string,
display?: string,
) =>
part('candidate', {
part: [
part('scenario', { valueCoding: { system: SCENARIOS, code: scenario, display } }),
part('index-date', { valueDate: date }),
...(sample ? [part('index-sample-id', { valueString: sample })] : []),
part('eligible', { valueBoolean: eligible }),
...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERIA, code: c } })),
],
});
const answer = (status: string, ...candidates: object[]): Parameters =>
({
resourceType: 'Parameters',
parameter: [
part('status', { valueCode: status }),
part('patient', { valueReference: { reference: 'Patient/p' } }),
part('cutoff', { valueDate: '2026-12-02' }),
...candidates,
],
}) as Parameters;
// Each test fails if the section merged visits, dropped a reason or read silence as eligibility.
describe('the eligibility answer as the section shows it', () => {
it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate(
'post_colposcopy',
'2020-08-10',
false,
['cancer_history', 'outcome_by_index', 'prior_treatment'],
'2020-08-10',
),
candidate('surveillance', '2024-01-05', true, [], 'a'),
candidate('surveillance', '2025-03-01', false, ['no_index_result'], 'b'),
candidate('post_colposcopy', '2022-02-02', true, [], '2022-02-02'),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.cutoff).toBe('2026-12-02');
expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([
['post_colposcopy', 'Postcolposcopia', 2],
['surveillance', 'Vigilancia', 2],
]);
const post = view.groups[0].visits; // newest visit first
expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([
['2022-02-02', true, []],
['2020-08-10', false, ['cancer_history', 'outcome_by_index', 'prior_treatment']],
]);
expect(post[1].reasons[0].text).toBe('Antecedente de cáncer cervicouterino');
expect(view.groups[1].visits.map((v) => v.sampleId)).toEqual(['b', 'a']);
});
it('the backend decides: a visit it calls eligible is eligible, one with reasons is not derived', () => {
const view = eligibilityView(answer('evaluated', candidate('survival', '2025-01-01', true)));
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups[0].visits[0]).toMatchObject({
eligible: true,
reasons: [],
sampleId: undefined,
});
});
it('without candidates it says so, which is not eligibility', () => {
expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' });
});
it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => {
for (const bad of [
null,
undefined,
{} as any,
{ resourceType: 'Bundle' } as any,
answer('evaluated'),
answer('other', candidate('survival', '2025-01-01', true)),
answer('evaluated', part('candidate', { part: [] })),
])
expect(eligibilityView(bad)).toEqual({ kind: 'unavailable' });
});
it('unknown codes show the display the API gave, else the code, and keep the code', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'),
candidate('other_scenario', '2025-01-02', false, ['another_rule']),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups.map((g) => [g.code, g.text])).toEqual([
['new_scenario', 'Escenario nuevo'],
['other_scenario', 'other_scenario'],
]);
expect(view.groups[1].visits[0].reasons).toEqual([
{ code: 'another_rule', text: 'another_rule' },
]);
});
});
describe('what a failed call is', () => {
const failure = (status: number, error: unknown = null) =>
eligibilityFailure(new HttpErrorResponse({ status, error }));
it('a 409 asks for the gold update and keeps the backend diagnostics', () => {
expect(
failure(409, {
resourceType: 'OperationOutcome',
issue: [{ code: 'conflict', diagnostics: 'rebuild gold.cacu_eligibility' }],
}),
).toEqual({ kind: 'gold', text: 'rebuild gold.cacu_eligibility' });
expect(failure(409)).toEqual({ kind: 'gold', text: undefined });
});
it('404 and 422 are "unavailable"; any other status or no connection is a communication error', () => {
expect(failure(404)).toEqual({ kind: 'unavailable' });
expect(failure(422)).toEqual({ kind: 'unavailable' });
expect(failure(500)).toEqual({ kind: 'error' });
expect(failure(0)).toEqual({ kind: 'error' });
expect(eligibilityFailure(new Error('boom'))).toEqual({ kind: 'error' });
});
});
+253
View File
@@ -0,0 +1,253 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */
export const SCENARIO_TEXT: Record<string, string> = {
surveillance: 'Vigilancia',
pre_colposcopy: 'Precolposcopia',
post_colposcopy: 'Postcolposcopia',
post_colposcopy_second_visit: 'Segunda visita postcolposcopia',
post_treatment: 'Postratamiento',
survival: 'Supervivencia',
};
/** The exclusion criteria the backend publishes, as the screens say them. */
export const CRITERION_TEXT: Record<string, string> = {
hysterectomy: 'Histerectomía previa al índice',
under_18: 'Edad menor de 18 años al índice',
prior_outcome: 'Resultado CIN2+ previo al índice',
no_index_result: 'Sin resultado de citología o VPH en la visita índice',
unreported_biopsy: 'Biopsia solicitada sin resultado',
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
cancer_history: 'Antecedente de cáncer cervicouterino',
prior_treatment: 'Tratamiento previo a la visita índice',
no_referral: 'Sin citología de referencia previa a la colposcopia',
referral_not_graded: 'Citología de referencia de bajo grado sin VPH positivo',
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
no_birth_date: 'Fecha de nacimiento desconocida',
died_by_index: 'Defunción en o antes de la visita índice',
};
export interface Reason {
/** the API's code, untouched */
code: string;
text: string;
}
export interface Visit {
indexDate: string;
/** the sample the visit is evaluated at, when the backend names one */
sampleId?: string;
/** the backend's decision; it is never derived from the reasons */
eligible: boolean;
reasons: Reason[];
}
export interface ScenarioGroup {
code: string;
text: string;
visits: Visit[];
}
/** What the section can be in; none of them says "eligible" unless the backend did. */
export type EligibilityState =
| { kind: 'loading' }
| { kind: 'error' }
| { kind: 'unavailable' }
| { kind: 'gold'; text?: string }
| { kind: 'none'; cutoff?: string }
| { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] };
type Part = ParametersParameter;
const value = (p?: Part): unknown =>
p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueBoolean ?? undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const coding = (p?: Part) => p?.valueCoding;
/** The answer of `$eligibility`, grouped by scenario and keeping the visits apart: each visit has
* its own decision and its own reasons. A code the screens do not know shows the display the API
* gave, else the code itself. An answer that is not what the contract says is "unavailable". */
export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
const top = answer?.parameter;
if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' };
const status = value(named(top, 'status')[0]);
const cutoff = value(named(top, 'cutoff')[0]) as string | undefined;
const candidates = named(top, 'candidate');
if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff };
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
const groups = new Map<string, ScenarioGroup>();
for (const c of candidates) {
const scenario = coding(named(c.part, 'scenario')[0]);
const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined;
const eligible = value(named(c.part, 'eligible')[0]);
if (!scenario?.code || !indexDate || typeof eligible !== 'boolean')
return { kind: 'unavailable' };
const group = groups.get(scenario.code) ?? {
code: scenario.code,
text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code,
visits: [],
};
groups.set(scenario.code, group);
group.visits.push({
indexDate,
sampleId: value(named(c.part, 'index-sample-id')[0]) as string | undefined,
eligible,
reasons: named(c.part, 'criterion').flatMap((r) => {
const k = coding(r);
return k?.code
? [{ code: k.code, text: CRITERION_TEXT[k.code] ?? k.display ?? k.code }]
: [];
}),
});
}
for (const g of groups.values()) g.visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate));
return { kind: 'evaluated', cutoff, groups: [...groups.values()] };
}
/** What the answer's failure says: the gold must be updated (409), the patient has no such
* operation (404, 422), or the call itself failed (anything else, including no connection). */
export function eligibilityFailure(error: unknown): EligibilityState {
if (error instanceof HttpErrorResponse) {
if (error.status === 409) {
const issue = (error.error as { issue?: { diagnostics?: string }[] } | null)?.issue?.[0];
return { kind: 'gold', text: issue?.diagnostics };
}
if (error.status === 404 || error.status === 422) return { kind: 'unavailable' };
}
return { kind: 'error' };
}
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
/** "Elegibilidad por escenario clínico": the decisions the backend publishes for each indexed visit,
* one scenario at a time. It shows them; it decides nothing. */
@Component({
selector: 'app-eligibility',
template: `
@let s = state();
@switch (s.kind) {
@case ('loading') {
<p class="state" role="status" data-state="loading">Consultando la elegibilidad…</p>
}
@case ('error') {
<p class="state" role="alert" data-state="error">
No se pudo consultar la elegibilidad. Intente de nuevo más tarde.
</p>
}
@case ('unavailable') {
<p class="state" role="status" data-state="unavailable">
Información de elegibilidad no disponible para esta paciente.
</p>
}
@case ('gold') {
<p class="state" role="status" data-state="gold">
La elegibilidad requiere actualizar la capa gold del servidor; todavía no está disponible.
</p>
@if (s.text) {
<p class="muted detail">{{ s.text }}</p>
}
}
@case ('none') {
<p class="state" role="status" data-state="none">
Sin candidatos: la paciente no tiene visitas indexadas en estos escenarios
@if (s.cutoff) {
a la fecha de corte {{ s.cutoff }}
}
. Esto no significa que sea elegible.
</p>
}
@case ('evaluated') {
@for (g of s.groups; track g.code) {
<details class="scenario" [attr.data-scenario]="g.code" [open]="g.visits.length <= 2">
<summary>
<strong>{{ g.text }}</strong>
<span class="muted">
· {{ plural(g.visits.length, 'visita', 'visitas') }} ·
{{ plural(count(g, true), 'elegible', 'elegibles') }},
{{ plural(count(g, false), 'no elegible', 'no elegibles') }}
</span>
</summary>
<ul class="visits">
@for (v of g.visits; track $index) {
<li class="visit" [attr.data-eligible]="v.eligible">
<p class="head">
<span class="badge" [class.ok]="v.eligible">{{
v.eligible ? 'Elegible' : 'No elegible'
}}</span>
Fecha índice {{ v.indexDate }}
<span class="muted"
>· {{ v.sampleId ? 'Muestra ' + v.sampleId : 'Sin muestra asociada' }}</span
>
</p>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivos de exclusión">
@for (r of v.reasons; track r.code) {
<li [attr.data-code]="r.code">{{ r.text }}</li>
}
</ul>
}
</li>
}
</ul>
</details>
}
@if (s.cutoff) {
<p class="muted note">Visitas hasta la fecha de corte {{ s.cutoff }}.</p>
}
}
}
`,
styles: `
.note,
.detail {
font-size: 12px;
}
.state {
margin: 8px 0;
}
.scenario {
border-top: 1px solid #dce3e7;
padding: 6px 0;
}
.scenario summary {
cursor: pointer;
}
.visits {
list-style: none;
margin: 6px 0 0;
padding: 0;
}
.visit {
padding: 4px 0 4px 12px;
}
.head {
margin: 0;
}
.badge {
background: #f3d6dc;
border-radius: 10px;
color: #7a1f36;
font-size: 12px;
font-weight: 500;
margin-right: 6px;
padding: 1px 8px;
}
.badge.ok {
background: #dcefe4;
color: #1d5a3b;
}
.why {
margin: 2px 0 0;
padding-left: 22px;
}
`,
})
export class Eligibility {
readonly state = input.required<EligibilityState>();
protected plural = plural;
protected count(g: ScenarioGroup, eligible: boolean) {
return g.visits.filter((v) => v.eligible === eligible).length;
}
}
+128
View File
@@ -0,0 +1,128 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
/** One scenario's row of a model's scenario summary (models.factors.scenario_row). */
export interface ScenarioFactors {
escenario: string;
n_escenario: number;
horizonte_meses?: number;
riesgo_definitorios: string;
riesgo_mayoritarios: string;
incluye_factor_riesgo: boolean;
}
interface Entry {
text: string;
robust: boolean;
}
/** A listing cell, `variable=category (robusto|sugerente, share)` separated by `;`. */
export function entries(cell: string | null | undefined): Entry[] {
return (cell ?? '')
.split(';')
.map((e) => e.trim())
.filter(Boolean)
.map((text) => ({ text, robust: /\(\s*robusto\b/i.test(text) }));
}
/** "Factores de riesgo de este escenario", as the old record: per scenario of hers, the risk
* factors present in at least 95 % of it and those in 50 to 95 %, a robust one solid and a
* suggestive one outlined; with a horizon to choose when the model has several. */
@Component({
selector: 'app-factores',
imports: [MatFormFieldModule, MatSelectModule],
template: `
<h3>Factores de riesgo</h3>
@if (horizons().length > 1) {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="horizon">
<mat-label>Horizonte</mat-label>
<mat-select [value]="horizon()" (selectionChange)="chosen.set($event.value)">
@for (h of horizons(); track h) {
<mat-option [value]="h">{{ h }} meses</mat-option>
}
</mat-select>
</mat-form-field>
}
@for (s of shown(); track s.escenario) {
<h4>
{{ s.escenario }} <span class="muted">(n = {{ s.n }})</span>
</h4>
@if (s.defining.length || s.majority.length) {
@if (s.defining.length) {
<p class="level">Presentes en al menos 95 % del escenario</p>
<ul class="factors">
@for (e of s.defining; track e.text) {
<li [class.robust]="e.robust">{{ e.text }}</li>
}
</ul>
}
@if (s.majority.length) {
<p class="level">Presentes en 50 a 95 % del escenario</p>
<ul class="factors">
@for (e of s.majority; track e.text) {
<li [class.robust]="e.robust">{{ e.text }}</li>
}
</ul>
}
} @else {
<p class="muted">Sin factores de riesgo identificados en este escenario.</p>
}
} @empty {
<p class="muted">El informe del modelo no describe factores de sus escenarios.</p>
}
`,
styles: `
.horizon {
margin: 4px 0 8px;
}
.level {
margin: 6px 0 2px;
font-size: 0.85rem;
color: var(--mat-sys-on-surface-variant);
}
.factors {
list-style: none;
padding: 0;
margin: 0 0 6px;
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.factors li {
padding: 2px 10px;
border-radius: 12px;
border: 1px solid var(--mat-sys-primary);
font-size: 0.85rem;
}
.factors li.robust {
background: var(--mat-sys-primary);
color: var(--mat-sys-on-primary);
}
`,
})
export class Factores {
/** Her scenarios' rows (every horizon when the model has several). */
readonly rows = input.required<ScenarioFactors[]>();
protected readonly chosen = signal<number | undefined>(undefined);
protected readonly horizons = computed(() =>
[
...new Set(
this.rows()
.map((r) => r.horizonte_meses)
.filter((h) => h !== undefined),
),
].sort((a, b) => a! - b!),
);
protected readonly horizon = computed(() => this.chosen() ?? this.horizons().at(-1));
protected readonly shown = computed(() =>
this.rows()
.filter((r) => r.horizonte_meses === undefined || r.horizonte_meses === this.horizon())
.map((r) => ({
escenario: r.escenario,
n: r.n_escenario,
defining: entries(r.riesgo_definitorios),
majority: entries(r.riesgo_mayoritarios),
})),
);
}
+31
View File
@@ -0,0 +1,31 @@
import type { EligibilityState, Visit } from './eligibility';
import { ineligibility } from './ineligibility';
const visit = (indexDate: string, ...reasons: string[]): Visit => ({
indexDate,
eligible: !reasons.length,
reasons: reasons.map((text) => ({ code: text, text })),
});
const state: EligibilityState = {
kind: 'evaluated',
groups: [
{
code: 'pre_colposcopy',
text: 'Precolposcopia',
visits: [visit('2025-01-01', 'Histerectomía previa al índice'), visit('2024-01-01')],
},
{ code: 'post_treatment', text: 'Postratamiento', visits: [visit('2025-01-01', 'Otro')] },
],
};
describe('ineligibility', () => {
it('speaks only when she is not eligible in her own scenario', () => {
expect(ineligibility(state, 'pre_colposcopy', '2025-06-01')).toBe(
'No disponible por: Histerectomía previa al índice.',
);
expect(ineligibility(state, 'pre_colposcopy', '2024-06-01')).toBeUndefined();
expect(ineligibility(state, 'post_colposcopy', '2025-06-01')).toBeUndefined();
expect(ineligibility(state, 'case', '2025-06-01')).toBeUndefined();
expect(ineligibility({ kind: 'error' }, 'pre_colposcopy', '2025-06-01')).toBeUndefined();
});
});
+31
View File
@@ -0,0 +1,31 @@
import type { EligibilityState } from './eligibility';
/** The `$eligibility` scenarios that stand for each follow-up status, the first that has a
* visit speaking for her. A case has no disease-risk estimate to be eligible for. */
const SCENARIOS: Record<string, string[]> = {
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
post_colposcopy: ['post_colposcopy'],
post_treatment: ['post_treatment'],
};
/** What the risk section says when she is not eligible in her clinical scenario, from its latest
* visit indexed by `day`; nothing when she is eligible or the backend has no visit of it. */
export function ineligibility(
state: EligibilityState,
status: string,
day: string,
): string | undefined {
if (state.kind !== 'evaluated') return undefined;
for (const scenario of SCENARIOS[status] ?? []) {
// visits come latest first
const latest = state.groups
.find((g) => g.code === scenario)
?.visits.find((v) => v.indexDate <= day);
if (latest) {
return latest.eligible
? undefined
: `No disponible por: ${latest.reasons.map((r) => r.text).join('; ')}.`;
}
}
return undefined;
}
+347 -90
View File
@@ -5,9 +5,21 @@
@if (error()) { @if (error()) {
<p class="muted" role="alert">No se encontró la paciente.</p> <p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) { } @else if (patient(); as p) {
<h1> <div class="record-head">
{{ identity().name ?? 'Paciente' }} <code class="muted">{{ p.id!.slice(0, 10) }}</code> <h1>
</h1> {{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1>
@if (cama()) {
<div class="head-actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
}
</div>
@if (cama() && saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<dl class="summary"> <dl class="summary">
<div> <div>
<dt>CURP</dt> <dt>CURP</dt>
@@ -21,16 +33,49 @@
<dt>Fecha de nacimiento</dt> <dt>Fecha de nacimiento</dt>
<dd>{{ p.birthDate ?? 'Sin dato' }}</dd> <dd>{{ p.birthDate ?? 'Sin dato' }}</dd>
</div> </div>
@if (stages()) {
<div>
<dt>Edad</dt>
<dd>{{ age() ?? 'Sin dato' }}</dd>
</div>
}
<div> <div>
<dt>Sexo</dt> <dt>Sexo</dt>
<dd> <dd>
{{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }} {{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }}
</dd> </dd>
</div> </div>
<div> @if (cama(); as c) {
<dt>Estatus de seguimiento</dt> <div>
<dd>{{ status() }}</dd> <dt>Grupo de edad</dt>
</div> <dd>{{ c.ageGroup || 'No disponible' }}</dd>
</div>
<div>
<dt>Escenario clínico</dt>
<dd>{{ c.scenario }}</dd>
</div>
<div>
<dt>Estatus de seguimiento</dt>
<dd>
{{ c.status ?? 'Fuera de la lista (' + c.window + ' meses al ' + c.cutoff + ')' }}
</dd>
</div>
<div>
<dt>Prioridad</dt>
<dd>{{ c.priority ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Días de mastografía a diagnóstico</dt>
<dd>{{ c.days ?? 'No disponible' }}</dd>
</div>
} @else {
@if (status()) {
<div>
<dt>Estatus de seguimiento</dt>
<dd>{{ status() }}</dd>
</div>
}
}
@if (p.deceasedDateTime) { @if (p.deceasedDateTime) {
<div> <div>
<dt>Defunción</dt> <dt>Defunción</dt>
@@ -40,9 +85,56 @@
</dl> </dl>
<div class="cards"> <div class="cards">
@if (cama(); as c) {
<mat-card appearance="outlined" data-section="mastografia">
<mat-card-header><mat-card-title>Mastografía</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Última mastografía</h3>
<dl class="facts">
<div>
<dt>Categoría BI-RADS</dt>
<dd>{{ c.birads ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Fecha</dt>
<dd>{{ c.mammogram ?? 'No disponible' }}</dd>
</div>
</dl>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" data-section="histopatologia">
<mat-card-header><mat-card-title>Histopatología</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Resultado histopatológico</h3>
<dl class="facts">
<div>
<dt>Resultado</dt>
<dd>{{ c.histology ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Fecha de reporte de la biopsia</dt>
<dd>{{ c.biopsy ?? 'No disponible' }}</dd>
</div>
</dl>
</mat-card-content>
</mat-card>
}
<mat-card appearance="outlined"> <mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content> <mat-card-content>
@if (stages(); as s) {
<div class="export-actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<div data-section="etapas">
<app-stages [stages]="s" [detail]="true" />
</div>
}
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
@@ -91,7 +183,19 @@
<td class="nowrap">{{ t.date }}</td> <td class="nowrap">{{ t.date }}</td>
<td>{{ t.kind }}</td> <td>{{ t.kind }}</td>
<td class="nowrap">{{ t.reported ?? 'Pendiente' }}</td> <td class="nowrap">{{ t.reported ?? 'Pendiente' }}</td>
<td>{{ t.results.join(' · ') || '—' }}</td> <td>
{{ t.results.join(' · ') || '—' }}
@if (t.findings.length) {
<details class="findings">
<summary>Hallazgos ({{ t.findings.length }})</summary>
<ul>
@for (f of t.findings; track $index) {
<li>{{ f }}</li>
}
</ul>
</details>
}
</td>
</tr> </tr>
} @empty { } @empty {
<tr> <tr>
@@ -103,50 +207,119 @@
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
<mat-card appearance="outlined" class="wide"> @if (forms().length) {
<mat-card-header <mat-card appearance="outlined" class="wide" data-section="antecedentes">
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header <mat-card-header
> ><mat-card-title
<mat-card-content> >Antecedentes y evaluación ginecológica</mat-card-title
@if (models().length) { ></mat-card-header
<table class="plain"> >
<thead> <mat-card-content>
<tr> <p class="muted route-note">
<th>Modelo</th> Datos declarados en el formulario de la citología: no son diagnósticos confirmados.
<th>Fecha índice</th> Cada dato pertenece al formulario de la toma que se indica.
<th>Horizonte</th> </p>
<th>Probabilidad</th> @let f = forms()[0];
<th>IC 95 %</th> <h3>Citología cervical · toma {{ f.date }}</h3>
</tr> <dl class="facts">
</thead> @for (a of antecedents; track a.field) {
<tbody> <div>
@for (m of models(); track m.model) { <dt>{{ a.title }}</dt>
@for (p of m.predictions; track p.years) { <dd>{{ f.values[a.field] ?? 'No documentado' }}</dd>
</div>
}
</dl>
@if (forms().length > 1) {
<details class="findings">
<summary>Formularios anteriores ({{ forms().length - 1 }})</summary>
<table class="plain">
<thead>
<tr> <tr>
<td>{{ $first ? m.text : '' }}</td> <th>Toma</th>
<td>{{ $first ? m.index : '' }}</td> @for (a of antecedents; track a.field) {
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td> <th>{{ a.title }}</th>
<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> </tr>
} </thead>
} <tbody>
</tbody> @for (o of forms().slice(1); track o.date) {
</table> <tr>
<app-plot [figure]="curve()" [height]="300" /> <td class="nowrap">{{ o.date }}</td>
} @else { @for (a of antecedents; track a.field) {
<p class="muted">Ningún modelo vigente la ha evaluado.</p> <td>{{ o.values[a.field] ?? 'No documentado' }}</td>
} }
</mat-card-content> </tr>
</mat-card> }
</tbody>
</table>
</details>
}
</mat-card-content>
</mat-card>
}
@if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) {
<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 (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" [toolbar]="false" />
}
</details>
}
@if (!riskModels().length && !riskExclusion()) {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
</mat-card-content>
</mat-card>
}
@if (domain() === 'tea') { @if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea"> <mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -178,16 +351,14 @@
Estudio del {{ st.study_date }}: Estudio del {{ st.study_date }}:
<strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong> <strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong>
@if (st.level) { @if (st.level) {
({{ st.level }}) ({{ levelNames[st.level] ?? st.level }})
} }
</p> </p>
<h3>Alteraciones del EEG</h3> <h3>Alteraciones del EEG</h3>
@if (!st.valid) { @if (!st.valid) {
<p class="muted">Un EEG no aceptable no se compara con la norma por edad.</p> <p class="muted">EEG no aceptable: no se compara con la norma por edad.</p>
} @else if (!scored()) { } @else if (!scored()) {
<p class="muted"> <p class="muted">Sin curva por edad en producción para este EEG.</p>
Ninguna curva por edad vigente ha evaluado este EEG (se promueven en Gobernanza).
</p>
} @else if (alterations().length) { } @else if (alterations().length) {
<table class="plain"> <table class="plain">
<thead> <thead>
@@ -266,10 +437,7 @@
> >
<h3>Relación con el ADOS-2</h3> <h3>Relación con el ADOS-2</h3>
@if (!eeg.value()?.analysis?.relation?.length) { @if (!eeg.value()?.analysis?.relation?.length) {
<p class="muted"> <p class="muted">Sin modelo de asociación en producción para este EEG.</p>
Ningún modelo de asociación vigente ha evaluado este EEG (se promueven en
Gobernanza).
</p>
} @else if (!related().length) { } @else if (!related().length) {
<p> <p>
Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara
@@ -288,7 +456,7 @@
<th>Aspecto del ADOS-2</th> <th>Aspecto del ADOS-2</th>
<th>Asociación en la cohorte</th> <th>Asociación en la cohorte</th>
<th>Probabilidad para este paciente</th> <th>Probabilidad para este paciente</th>
<th>Lo que muestra su ADOS-2</th> <th>Resultado en su ADOS-2</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -352,41 +520,13 @@
</mat-card> </mat-card>
} }
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header
><mat-card-title>Análisis de supervivencia</mat-card-title></mat-card-header
>
<mat-card-content>
@if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas.
</p>
}
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
}
</mat-card-content>
</mat-card>
}
@if (recurrenceModel(); as rm) { @if (recurrenceModel(); as rm) {
<mat-card appearance="outlined" class="wide" data-section="recurrencia"> <mat-card appearance="outlined" class="wide" data-section="recurrencia">
<mat-card-header <mat-card-header
><mat-card-title>Análisis de recurrencia</mat-card-title></mat-card-header ><mat-card-title>Pronóstico y recomendaciones</mat-card-title></mat-card-header
> >
<mat-card-content> <mat-card-content>
<h3>Análisis de recurrencia</h3>
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
@@ -417,15 +557,132 @@
<app-plot [figure]="f.figure" [height]="340" /> <app-plot [figure]="f.figure" [height]="340" />
} @empty { } @empty {
<p class="muted"> <p class="muted">
Sus escenarios tienen menos recaídas de las necesarias para trazar curvas. Sus escenarios no tienen recaídas suficientes para trazar curvas.
</p> </p>
} }
<app-factores [rows]="s.factors" />
} @else if (recurrence.error()) { } @else if (recurrence.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} }
@if (models().some((m) => m.model.endsWith('.survival'))) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header>
<mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
}}</mat-card-title>
</mat-card-header>
<mat-card-content>
@if (domain() !== 'cacu') {
<h3>Análisis de supervivencia</h3>
}
@if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
@for (g of survivalScales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
v.risk!.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
</tbody>
</table>
</details>
}
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.curves) {
<p class="muted">
Ajustes sobre las pacientes con sus mismos valores (Kaplan-Meier con IC 95 %
Greenwood; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p>
<app-curve-chooser [choices]="c.curves.choices" [draw]="c.curves.draw" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3>
<ul class="scenarios">
@for (name of s.scenarios; track name) {
<li>{{ name }}</li>
}
</ul>
@if (s.methods.length) {
<details>
<summary>Métodos</summary>
<ul class="scenarios methods">
@for (name of s.methods; track name) {
<li>{{ name }}</li>
}
</ul>
</details>
}
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
}
@for (name of s.unavailable; track name) {
<h4>{{ name }}</h4>
<p class="muted">No disponible: datos insuficientes.</p>
}
@for (u of s.insufficient; track u.name) {
<h4>{{ u.name }}</h4>
<p class="muted" data-state="insuficiente">{{ insufficientText(u) }}</p>
}
@for (name of s.missing; track name) {
<h4>{{ name }}</h4>
<p class="muted" data-state="sin-informacion">
Sin información de este escenario en el informe del modelo.
</p>
}
<app-factores [rows]="s.factors" />
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else {
<p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
}
</mat-card-content>
</mat-card>
}
</div> </div>
} @else if (loading()) { } @else if (loading()) {
<app-loading what="el expediente" /> <app-loading what="el expediente" />
+69 -3
View File
@@ -1,16 +1,19 @@
.summary { .summary,
.facts {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-6); gap: var(--space-6);
margin: var(--space-3) 0 var(--space-4); margin: var(--space-3) 0 var(--space-4);
} }
.summary dt { .summary dt,
.facts dt {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: 12px; font-size: 12px;
} }
.summary dd { .summary dd,
.facts dd {
font-weight: 500; font-weight: 500;
margin: 0; margin: 0;
} }
@@ -88,3 +91,66 @@ tr.chosen td {
font-size: 0.8em; font-size: 0.8em;
} }
} }
h1 .id {
font-size: 14px;
font-weight: 400;
margin-left: var(--space-2);
vertical-align: middle;
}
.export-actions {
display: flex;
justify-content: flex-end;
margin-bottom: var(--space-3);
}
.route-note {
font-size: 12px;
margin: var(--space-2) 0 var(--space-3);
}
.findings {
margin-top: 4px;
summary {
color: var(--color-text-secondary);
cursor: pointer;
font-size: 13px;
}
ul {
margin: 4px 0 0;
padding-left: 18px;
}
}
.curves {
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 12px;
padding: 8px 12px;
summary {
cursor: pointer;
font-weight: 500;
}
}
.curve-text {
margin: 8px 0;
padding-left: 18px;
}
/* The name and, in CaMa, the export of the record on the same line; narrow screens put the button under the name. */
.record-head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
justify-content: space-between;
}
.record-head h1 {
min-width: 0;
overflow-wrap: anywhere;
}
.head-actions {
flex: none;
}
+426 -65
View File
@@ -13,14 +13,31 @@ import type {
RiskAssessment, RiskAssessment,
} from 'fhir/r4'; } from 'fhir/r4';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
import { studies as eegStudies } from '../api/fn/eeg/studies'; import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study'; import { study as eegStudy } from '../api/fn/eeg/study';
import { readReport$Json } from '../api/fn/models/read-report-json'; import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures'; import { scenarioFigure } from '../gobernanza/figures';
import { CURP } from '../indicadores/follow-up'; import { savePdf } from '../export';
import { LABELS, name } from '../indicadores/measures'; import { camaRecordSheets } from './cama-record-sheets';
import { recordSheets } from './record-sheets';
import { HttpClient } from '@angular/common/http';
import type { Parameters as FhirParameters } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve';
import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationOf, noCurveText, survivalFigure } from './survival-combination';
import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
import { import {
BIOMARKER_NAMES, BIOMARKER_NAMES,
byDeviation, byDeviation,
@@ -28,10 +45,13 @@ import {
METRIC_NAMES, METRIC_NAMES,
OUTCOME_NAMES, OUTCOME_NAMES,
ZONE_NAMES, ZONE_NAMES,
LEVEL_NAMES,
} from '../eeg-labels'; } from '../eeg-labels';
import type { Relation } from '../api/models/relation'; import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot'; import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores';
import { CurveChooser, figureChoices } from './curve-chooser';
/** An Observation's value as the screens say it, whatever its type. */ /** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string { function shown(o: Observation): string {
@@ -45,19 +65,73 @@ function shown(o: Observation): string {
return o.valueString ?? o.valueDateTime ?? ''; return o.valueString ?? o.valueDateTime ?? '';
} }
/** A report's Observations as facts of its study's form (record-groups). */
function facts(observations: Observation[]): Fact[] {
return observations.map((o) => ({
...split(code(o.code) ?? ''),
title: label(o.code),
value: shown(o),
}));
}
/** One patient: her history (conditions, procedures), her tests and results, and the /** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */ * champion models' risks with their curves. Everything read from the FHIR API. */
/** The names of the methods the figures draw, each once. */
function methods(figures: { figure: { data: unknown[] } }[]): string[] {
const names = figures.flatMap((f) => f.figure.data.map((t) => (t as { name?: string }).name));
return [...new Set(names.filter((n): n is string => !!n))];
}
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [Loading, DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot], imports: [
Factores,
CurveChooser,
Loading,
DecimalPipe,
MatButtonModule,
MatCardModule,
MatIconModule,
RouterLink,
Plot,
RiskScales,
RiskSeries,
Stages,
],
templateUrl: './paciente.html', templateUrl: './paciente.html',
styleUrl: './paciente.scss', styleUrl: './paciente.scss',
}) })
export class Paciente { export class Paciente {
private readonly fhir = inject(Fhir); private readonly fhir = inject(Fhir);
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly id = input.required<string>(); readonly id = input.required<string>();
/** The follow-up list she was opened from: its window (months) and cut-off. */
readonly ventana = input<string>();
readonly corte = input<string>();
/** CaCu: the day of the cytology the list showed of her. */
readonly citologia = input<string>();
private readonly data = resource({ private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }), params: () => ({ domain: this.domain(), id: this.id() }),
@@ -94,7 +168,8 @@ export class Paciente {
date: c.recordedDate ?? '', date: c.recordedDate ?? '',
kind: 'Diagnóstico', kind: 'Diagnóstico',
text: label(c.code), text: label(c.code),
code: code(c.code), // the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid)
code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code,
})), })),
...d.procedures.map((p) => ({ ...d.procedures.map((p) => ({
date: p.performedDateTime ?? '', date: p.performedDateTime ?? '',
@@ -104,24 +179,254 @@ export class Paciente {
})), })),
].sort((a, b) => b.date.localeCompare(a.date)); ].sort((a, b) => b.date.localeCompare(a.date));
}); });
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
* hysterectomy of her record is still held against her when the backend does not report it,
* as with evidence loaded without the day it was available. */
protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined;
const patient = this.patient();
const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
const reported = ineligibility(this.eligibility(), status, index);
if (reported) return reported;
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index
? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined;
});
/** CaCu: 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(
(r) => code(r.code) === 'cervical_cytology',
);
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
});
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
);
/** 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' && (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() }
: undefined,
loader: async ({ params }): Promise<Series[] | undefined> => {
try {
const answer = await firstValueFrom(
this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
{
params: Object.fromEntries(
Object.entries({
cutoff: params.cutoff,
sample: params.sample?.slice(0, 10),
}).filter((e): e is [string, string] => !!e[1]),
),
},
),
);
return parseSeries(answer);
} catch {
return undefined;
}
},
});
/** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a
* state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */
private readonly eligibilityData = resource({
params: () => (this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined),
loader: async ({ params }): Promise<EligibilityState> => {
try {
const answer = await this.api.invoke(cacuEligibility, {
domain: 'cacu' as Domain,
id: params.id,
cutoff: params.cutoff,
});
return eligibilityView(answer as FhirParameters);
} catch (error) {
return eligibilityFailure(error);
}
},
});
protected readonly eligibility = computed<EligibilityState>(() =>
this.eligibilityData.isLoading()
? { kind: 'loading' }
: (this.eligibilityData.value() ?? { kind: 'loading' }),
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** 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],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', this.patient()?.birthDate],
['Edad', this.age()?.toString()],
['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()],
];
if (this.riskExclusion()) facts.push(['Evaluación de riesgo', this.riskExclusion()]);
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.forms(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
/** CaMa: her record as a PDF, with what CaMa publishes of her. */
private async saveCama(): Promise<void> {
const c = this.cama();
const { name: who, curp, numbers } = this.identity();
const p = this.patient();
const facts: [string, string | undefined][] = [
['Nombre', who],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', p?.birthDate],
['Sexo', p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined],
['Grupo de edad', c?.ageGroup],
['Escenario clínico', c?.scenario],
['Fecha de corte', c?.cutoff],
[
'Estatus de seguimiento',
c ? (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`) : undefined,
],
['Prioridad', c?.priority],
['Días de mastografía a diagnóstico', c?.days?.toString()],
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as [string, string][]) : []),
];
const studies: [string, string | undefined][] = [
['Categoría BI-RADS de la última mastografía', c?.birads],
['Fecha de la última mastografía', c?.mammogram],
['Resultado histopatológico', c?.histology],
['Fecha de reporte de la biopsia', c?.biopsy],
];
const analysis = (title: string, r: typeof this.survival) => {
// a report that failed to load is no analysis: its absence is said, the file is still made
const v = r.hasValue() ? r.value() : undefined;
return v
? [{ title, scenarios: v.scenarios, figures: v.figures.map((f) => f.title), undrawn: v.unavailable }]
: [];
};
const sheets = camaRecordSheets(
facts,
studies,
this.history(),
this.tests(),
this.models(),
[...analysis('Supervivencia', this.survival), ...analysis('Recurrencia', this.recurrence)],
);
await savePdf(sheets, 'expediente-cama');
}
protected readonly tests = computed(() => { protected readonly tests = computed(() => {
const d = this.data.value(); const d = this.data.value();
if (!d) return []; if (!d) return [];
return d.reports.map((r) => { return d.reports.flatMap((r) => {
const results = (r.result ?? []) const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1])) .map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[]; .filter((o) => !!o) as Observation[];
return { // the study's own results; the form's antecedents are in their own section and the extra
// findings are collapsed (record-groups)
const { hpv, rest } = hpvApart(facts(results));
const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '', date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate, reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code), kind: label(r.code),
status: r.status, status: r.status,
results: [...results.map((o) => `${label(o.code)}: ${shown(o)}`)], results: found.results,
findings: found.findings,
}; };
// an HPV result is a study of its own: its own row, only when there is one
return hpv.length
? [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]
: [row];
}); });
}); });
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
* opened at first, each with its day. They are statements of the form, not confirmed diagnoses. */
protected readonly forms = computed(() => {
const d = this.data.value();
if (!d || this.domain() !== 'cacu') return [];
const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology');
const first = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return [first, ...cytologies.filter((r) => r !== first)]
.filter((r) => !!r)
.map((r) => {
const found = group(
facts(
(r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[],
),
).antecedents;
return {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
values: found,
};
})
.filter((f) => ANTECEDENTS.some((a) => f.values[a.field]));
});
protected readonly antecedents = ANTECEDENTS;
/** One model's latest risk assessment per model. */ /** One model's latest risk assessment per model. */
protected readonly models = computed(() => { protected readonly models = computed(() => {
if (this.riskExclusion()) return [];
const latest = new Map<string, RiskAssessment>(); const latest = new Map<string, RiskAssessment>();
for (const r of this.data.value()?.risks ?? []) { for (const r of this.data.value()?.risks ?? []) {
const key = code(r.method) ?? ''; const key = code(r.method) ?? '';
@@ -136,6 +441,9 @@ export class Paciente {
text: r.method?.text ?? '', text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '', index: r.occurrenceDateTime ?? '',
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in // the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? []) scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico') .filter((e) => e.url === EXT + 'escenario-clinico')
@@ -174,8 +482,21 @@ export class Paciente {
const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario)); const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
if (name === 'recurrence') { if (name === 'recurrence') {
const r = (report?.['recurrencia'] ?? {}) as any; const r = (report?.['recurrencia'] ?? {}) as any;
// The risk factors of her scenarios, by horizon (the development tables).
const technical = (await this.api.invoke(readReport$Json, {
domain: domain as Domain,
name,
version: m.version,
report: 'technical_validation',
})) as any;
const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen'];
return { return {
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
scenarios: m.scenarios, scenarios: m.scenarios,
unavailable: [] as string[],
insufficient: [] as Insufficient[],
missing: [] as string[],
methods: [] as string[],
figures: mine(r['escenarios'] ?? []).map((e) => figures: mine(r['escenarios'] ?? []).map((e) =>
scenarioFigure( scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`, `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
@@ -186,16 +507,29 @@ export class Paciente {
), ),
}; };
} }
return { const drawn = mine((report?.['escenarios'] ?? []) as any[]);
scenarios: m.scenarios, const figures = drawn.map((e) =>
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) => scenarioFigure(
scenarioFigure( `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, e,
e, e.horizons_months,
e.horizons_months, 'Supervivencia S(t)',
'Supervivencia S(t)',
),
), ),
);
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
// CaCu: the report says which scenarios lack deaths (`escenarios_sin_curvas`); one it does not
// mention is not "insufficient", it is absent from the report. Other domains keep one list.
const { insufficient, missing } =
domain === 'cacu' ? sortUndrawn(report, undrawn) : { insufficient: [], missing: [] };
return {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
scenarios: m.scenarios,
figures,
// her scenarios the report draws no curve for
unavailable: domain === 'cacu' ? [] : undrawn,
insufficient,
missing,
methods: methods(figures),
}; };
}, },
}); });
@@ -303,66 +637,93 @@ export class Paciente {
if (f.observed === null || f.observed === undefined) return undefined; if (f.observed === null || f.observed === undefined) return undefined;
const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8; const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8;
return present === f.probability >= 0.5 return present === f.probability >= 0.5
? 'Coincide con lo que el modelo esperaba' ? 'Coincide con la asociación de la cohorte'
: 'No coincide con lo que el modelo esperaba'; : 'No coincide con la asociación de la cohorte';
} }
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? [])); protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? [])); protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
protected readonly curve = computed<Figure>(() => { /** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
const models = this.models().filter((m) => m.predictions.length > 1); protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
return {
data: models.flatMap((m, i) => {
const x = m.predictions.map((p) => p.years);
const color = PALETTE[i % PALETTE.length];
return [
{
x,
y: m.predictions.map((p) => (p.high ?? p.p) * 100),
mode: 'lines',
line: { width: 0 },
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: m.predictions.map((p) => (p.low ?? p.p) * 100),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
fillcolor: color + '33',
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: m.predictions.map((p) => p.p * 100),
mode: 'lines+markers',
name: m.model.replace('cacu.', ''),
line: { color },
},
];
}),
layout: {
xaxis: { title: { text: 'Años desde la fecha índice' }, dtick: 1 },
// At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: {
title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, this.top() * 110)],
tickformat: '.1f',
},
},
};
});
private top(): number { private top(): number {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); return Math.max(
0,
...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)),
);
} }
protected readonly insufficientText = insufficientText;
protected readonly name = name; protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES;
protected readonly identity = computed(() => { protected readonly identity = computed(() => {
const p = this.patient(); const p = this.patient();
return { return {
name: p?.name?.[0]?.text, name: p?.name?.[0]?.text,
curp: p?.identifier?.find((i) => i.system === CURP)?.value, curp: p?.identifier?.find((i) => i.system === CURP)?.value,
numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value), // each record number once (several sources may carry the same one)
numbers: [
...new Set(
(p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''),
),
].filter(Boolean),
};
});
/** CaMa: her row on the follow-up list (window and cut-off as opened, else the widest
* window up to the last day with data), as the list shows it: the old record's card. */
private readonly listed = resource({
params: () =>
this.domain() === 'cama'
? {
domain: this.domain(),
id: this.id(),
window: Number(this.ventana()) || 12,
cutoff: this.corte() || undefined,
}
: undefined,
loader: async ({ params: { domain, id, window, cutoff } }) => {
const page = await this.fhir.search(domain, 'Patient', {
_id: id,
'follow-up-window': window,
'follow-up-cutoff': cutoff,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
const self = page.link?.find((l) => l.relation === 'self')?.url;
const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
return { window, cutoff: applied, row: camaRows(page, applied)[0] };
},
});
protected readonly cama = computed(() => {
const found = this.listed.value();
const d = this.data.value();
if (!found || !d) return undefined;
// Her own latest mammogram and biopsy, on the list or not.
const latest = (study: string) =>
d.reports
.filter((r) => code(r.code) === study)
.sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''))
.at(-1);
const value = (r: DiagnosticReport | undefined, field: string) => {
const o = (r?.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.find((x) => code(x?.code) === field);
return o ? shown(o) : undefined;
};
const mammogram = latest('mammography');
const biopsy = latest('breast_biopsy');
const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff);
const r = found.row;
return {
...found,
ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS),
scenario: treated ? 'Post-tratamiento' : 'En observación',
status: r ? name(r.status) : undefined,
priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined,
birads: value(mammogram, 'mammography.birads'),
mammogram: mammogram?.effectiveDateTime?.slice(0, 10),
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
histology: value(biopsy, 'breast_biopsy.histology'),
biopsy: biopsy
? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime)
: undefined,
}; };
}); });
protected readonly status = computed(() => { protected readonly status = computed(() => {
+77
View File
@@ -0,0 +1,77 @@
import { ANTECEDENTS, group, split } from './record-groups';
const fact = (study: string, field: string, title: string, value: string) => ({
study,
field,
title,
value,
});
describe('the record of a cytology by what its facts are', () => {
it('splits a catalog code into its study and its field', () => {
expect(split('cervical_cytology.hpv_16')).toEqual({
study: 'cervical_cytology',
field: 'hpv_16',
});
expect(split('plain')).toEqual({ study: '', field: 'plain' });
});
it('keeps the form antecedents apart from the results and the findings', () => {
const found = group([
fact(
'cervical_cytology',
'screening_history',
'Detección de cáncer de cérvix',
'Primera vez en la vida',
),
fact(
'cervical_cytology',
'gynecologic_condition',
'Condición ginecoobstétrica a la detección',
'DIU in situ',
),
fact('cervical_cytology', 'presenting_symptom', 'Actualmente presenta', 'Flujo'),
fact('cervical_cytology', 'cervix_appearance', 'A la exploración se observa', 'Cuello sano'),
fact('cervical_cytology', 'adequacy', 'Calidad de la muestra', 'Satisfactoria'),
fact(
'cervical_cytology',
'result',
'Resultado (Bethesda)',
'Negativo para lesión intraepitelial o malignidad',
),
fact('cervical_cytology', 'hpv', 'VPH de alto riesgo', 'negativo'),
fact('cervical_cytology', 'findings', 'Hallazgos adicionales', 'Inflamación.'),
fact('cervical_cytology', 'finding_inflammation', 'Hallazgo: inflamación', 'positivo'),
]);
expect(Object.keys(found.antecedents)).toEqual(ANTECEDENTS.map((a) => a.field));
expect(found.antecedents['gynecologic_condition']).toBe('DIU in situ');
expect(found.results).toEqual([
'Calidad de la muestra: Satisfactoria',
'Resultado (Bethesda): Negativo para lesión intraepitelial o malignidad',
'VPH de alto riesgo: negativo',
]);
expect(found.findings).toEqual(['Texto del informe: Inflamación.', 'Inflamación']);
});
it('nothing is lost: every fact lands in exactly one place', () => {
const facts = [
fact('cervical_cytology', 'screening_history', 'a', '1'),
fact('cervical_cytology', 'result', 'b', '2'),
fact('cervical_cytology', 'finding_atrophy', 'Hallazgo: atrofia', 'positivo'),
fact('cervical_biopsy', 'histology', 'Histología', 'LIEAG'),
];
const found = group(facts);
expect(
Object.keys(found.antecedents).length + found.results.length + found.findings.length,
).toBe(facts.length);
});
it('a study that is not the cytology has no antecedents and no collapsed findings', () => {
const found = group([fact('cervical_biopsy', 'histology', 'Histología', 'LIEAG (CIN 2 y 3)')]);
expect(found.antecedents).toEqual({});
expect(found.findings).toEqual([]);
expect(found.results).toEqual(['Histología: LIEAG (CIN 2 y 3)']);
});
it('a stated finding keeps a value that is not simply "positivo"', () => {
expect(
group([fact('cervical_cytology', 'finding_none', 'Hallazgo: ninguno', 'negativo')]).findings,
).toEqual(['Ninguno: negativo']);
});
});
+56
View File
@@ -0,0 +1,56 @@
/** One field of a study's form as the report's Observation carries it: the catalog's field
* (`cervical_cytology.screening_history`), its title and its value as the screens say it. */
export interface Fact {
study: string;
field: string;
title: string;
value: string;
}
/** What the cytology's form declares of her before and at the sample: her screening history, the
* gynecologic condition she reports, what she presents and what the exploration observed. These are
* statements of the form (not diagnoses), each with its form and day. */
export const ANTECEDENTS: { field: string; title: string }[] = [
{ field: 'screening_history', title: 'Detección de cáncer de cérvix' },
{ field: 'gynecologic_condition', title: 'Condición ginecoobstétrica a la detección' },
{ field: 'presenting_symptom', title: 'Actualmente presenta' },
{ field: 'cervix_appearance', title: 'A la exploración se observa' },
];
/** `cervical_cytology.hpv` as its study and its field. */
export function split(code: string): { study: string; field: string } {
const at = code.indexOf('.');
return at < 0
? { study: '', field: code }
: { study: code.slice(0, at), field: code.slice(at + 1) };
}
/** A report's facts by what they are: the form's antecedents (by field), the results of the study
* itself, and the extra findings (collapsible): the cytologist's text and each stated finding. */
export function group(facts: Fact[]) {
const antecedents: Record<string, string> = {};
const results: string[] = [];
const findings: string[] = [];
for (const f of facts) {
const cytology = f.study === 'cervical_cytology';
if (cytology && ANTECEDENTS.some((a) => a.field === f.field)) antecedents[f.field] = f.value;
else if (cytology && f.field === 'findings') findings.unshift(`Texto del informe: ${f.value}`);
else if (cytology && f.field.startsWith('finding_')) {
const named = f.title.replace(/^Hallazgo: /, '');
const text = named.charAt(0).toUpperCase() + named.slice(1);
findings.push(f.value === 'positivo' ? text : `${text}: ${f.value}`);
} else {
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
results.push(f.value.startsWith(f.title) ? f.value : `${f.title}: ${f.value}`);
}
}
return { antecedents, results, findings };
}
const HPV_FIELDS = ['hpv', 'hpv_16', 'hpv_18'];
/** The cytology report's HPV results, apart from the cytology's own facts. */
export function hpvApart(facts: Fact[]) {
const isHpv = (f: Fact) => f.study === 'cervical_cytology' && HPV_FIELDS.includes(f.field);
return { hpv: facts.filter(isHpv), rest: facts.filter((f) => !isHpv(f)) };
}
+92
View File
@@ -0,0 +1,92 @@
import { recordSheets } from './record-sheets';
describe('the PDF of a record', () => {
const sheets = recordSheets(
[['Nombre', 'Ana']],
[
{
label: 'Toma de muestra',
day: '2026-01-10',
state: 'recorded',
sources: ['cytology-form'],
},
{
label: 'Colposcopía',
day: '2026-02-01',
state: 'inferred',
sources: ['clinical-note', 'biopsy-order'],
},
{
label: 'Reporte de biopsia',
state: 'pending',
requested: '2026-02-05',
sources: ['date-association'],
},
{ label: 'Diagnóstico', state: 'unknown' },
],
[{ date: '2026-03-01', kind: 'Diagnóstico', text: 'N87.9' }],
[
{
date: '2026-01-10',
kind: 'Citología cervical',
reported: '2026-01-20',
results: ['Resultado (Bethesda): LIEAG'],
findings: ['Texto del informe: Inflamación.', 'Inflamación'],
},
],
[
{
date: '2026-01-10',
values: { screening_history: 'Primera vez en la vida', cervix_appearance: 'Cuello sano' },
},
],
[],
);
const by = (title: string) => sheets.find((s) => s.title.startsWith(title))!;
it('keeps every section, in the page order', () => {
expect(sheets.map((s) => s.title.split(' (')[0])).toEqual([
'Datos de la paciente',
'Etapas del tamizaje',
'Historial médico',
'Antecedentes y evaluación ginecológica',
'Pruebas y resultados',
'Riesgos',
]);
});
it('writes each stage with its state, its day or its request, and where it comes from', () => {
expect(by('Etapas').head).toEqual(['Etapa', 'Estado', 'Fecha', 'Procedencia']);
expect(by('Etapas').rows).toEqual([
['Toma de muestra', 'Registrada', '2026-01-10', 'Formulario de citología'],
['Colposcopía', 'Inferida por fechas', '2026-02-01', 'Nota clínica · Orden de biopsia'],
['Reporte de biopsia', 'Pendiente', 'Solicitada el 2026-02-05', 'Asociación por fechas'],
['Diagnóstico', 'Sin dato', '', ''],
]);
});
it('gives the declared antecedents their own sheet, said as declared, with what is not documented', () => {
const s = by('Antecedentes');
expect(s.title).toContain('no son diagnósticos confirmados');
expect(s.head).toEqual([
'Toma',
'Detección de cáncer de cérvix',
'Condición ginecoobstétrica a la detección',
'Actualmente presenta',
'A la exploración se observa',
]);
expect(s.rows).toEqual([
['2026-01-10', 'Primera vez en la vida', 'No documentado', 'No documentado', 'Cuello sano'],
]);
});
it('keeps the results and the extra findings of each test in their own columns', () => {
expect(by('Pruebas').head).toEqual(['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos']);
expect(by('Pruebas').rows).toEqual([
[
'2026-01-10',
'Citología cervical',
'2026-01-20',
'Resultado (Bethesda): LIEAG',
'Texto del informe: Inflamación. · Inflamación',
],
]);
});
});
+87
View File
@@ -0,0 +1,87 @@
import type { Sheet } from '../export';
import type { RiskScale } from './risk-scales';
import { ANTECEDENTS } from './record-groups';
import { SOURCES, Stage, STATES } from './stages';
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[];
/** the extra findings (collapsed on the page) */
findings: string[];
}
interface Form {
date: string;
values: Record<string, string | undefined>;
}
/** A patient's record as the tables of her PDF, in the page's order. */
export function recordSheets(
facts: [string, string | undefined][],
stages: Stage[],
history: Event[],
tests: Test[],
forms: Form[],
scales: RiskScale[],
): Sheet[] {
return [
{
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Etapas del tamizaje',
head: ['Etapa', 'Estado', 'Fecha', 'Procedencia'],
rows: stages.map((s) => [
s.label,
STATES[s.state],
s.day ?? (s.requested ? `Solicitada el ${s.requested}` : ''),
(s.sources ?? []).map((c) => SOURCES[c]).join(' · '),
]),
},
{
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{
title:
'Antecedentes y evaluación ginecológica (declarados en el formulario de la citología; no son diagnósticos confirmados)',
head: ['Toma', ...ANTECEDENTS.map((a) => a.title)],
rows: forms.map((f) => [
f.date,
...ANTECEDENTS.map((a) => f.values[a.field] ?? 'No documentado'),
]),
},
{
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',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [
label,
risk ? percent(risk.p) : NONE,
risk?.low === undefined ? NONE : `${percent(risk.low)} a ${percent(risk.high!)}`,
]),
},
];
}
+260
View File
@@ -0,0 +1,260 @@
import type { Parameters } from 'fhir/r4';
import { groupReference, horizonLabel, outcomeText, referenceView } from './reference-risk';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const answer = (...parameter: object[]): Parameters =>
({ resourceType: 'Parameters', parameter }) as Parameters;
const resolved = (comparison: object[] = []) =>
answer(
part('status', { valueCode: 'resolved' }),
part('cutoff', { valueDate: '2026-11-30' }),
part('scenario', {
part: [
part('table', { valueCode: 'screening' }),
part('label', { valueString: 'Tamizaje' }),
part('key', {
part: [
part('name', { valueCode: 'history' }),
part('value', { valueString: 'Cotest-negative' }),
],
}),
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0 }),
...comparison,
],
}),
part('horizon', {
part: [part('years', { valueInteger: 5 }), part('published', { valueBoolean: false })],
}),
);
describe('the reference answer as the section shows it', () => {
it('names the horizons and never calls a year the immediate risk', () => {
expect(horizonLabel(0)).toBe('Inmediato (al índice)');
expect(horizonLabel(1)).toBe('1 año');
expect(horizonLabel(5)).toBe('5 años');
});
it('keeps a published zero as zero and a blank as absent', () => {
const view = referenceView(resolved());
expect(view.horizons.map((h) => [h.years, h.reference, h.published])).toEqual([
[0, 0, true],
[5, undefined, false],
]);
expect(view.scenario).toEqual({
label: 'Tamizaje',
keys: [{ name: 'Antecedente más reciente', value: 'Cotest-negative' }],
});
});
it('reads a comparison with its model, its figures and its reasons, and a difference only when one is given', () => {
const view = referenceView(
resolved([
part('comparison', {
part: [
part('model', { valueCode: 'cacu.cin2_pim' }),
part('title', { valueString: 'Riesgo LIEAG+' }),
part('institutional', { valueDecimal: 0.05 }),
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'outcome_differs' }),
],
}),
]),
);
const [c] = view.horizons[0].comparisons;
expect(c).toMatchObject({
model: 'cacu.cin2_pim',
institutional: 0.05,
status: 'not_comparable',
reasons: ['outcome_differs'],
});
expect(c.differencePp).toBeUndefined();
});
it('an unresolved answer has its state and reasons and no horizons', () => {
const view = referenceView(
answer(
part('status', { valueCode: 'history_not_demonstrable' }),
part('reason', { valueCode: 'no_earlier_test_registered' }),
),
);
expect(view).toMatchObject({
status: 'history_not_demonstrable',
reasons: ['no_earlier_test_registered'],
horizons: [],
used: [],
});
});
});
const cmp = (
model: string,
outcome: string,
status: string,
reasons: string[],
extra: object[] = [],
) =>
part('comparison', {
part: [
part('model', { valueCode: model }),
part('title', { valueString: model }),
part('outcome', { valueString: outcome }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const two = (a: object[], b: object[]) =>
answer(
part('status', { valueCode: 'resolved' }),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.001 }),
...a,
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 5 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.0027 }),
...b,
],
}),
);
describe('outcome names', () => {
it('translates the known outcomes for display and leaves the API identifier untouched', () => {
expect(outcomeText('cancer')).toBe('Cáncer');
expect(outcomeText('CIN2+ within one year')).toBe('CIN2+ en un año');
expect(outcomeText('CIN3+')).toBe('CIN3 o más grave (CIN3+)');
expect(outcomeText('something new')).toBe('something new');
expect(outcomeText(undefined)).toBe('');
const view = referenceView(
two([cmp('m', 'cancer', 'not_comparable', ['outcome_differs'])], []),
);
expect(view.horizons[0].comparisons[0].outcome).toBe('cancer');
});
});
describe('grouping the comparison', () => {
const reasons = ['outcome_differs', 'population_not_verified'];
it('keeps every model, horizon, value and interval, and says shared reasons once', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN2+',
'not_comparable',
[...reasons, 'index_date_differs'],
[part('institutional', { valueDecimal: 0.05 })],
),
cmp('b', 'cancer', 'not_comparable', reasons),
],
[
cmp('a', 'CIN2+', 'not_comparable', reasons, [
part('institutional', { valueDecimal: 0.07 }),
part('institutional-low', { valueDecimal: 0.05 }),
part('institutional-high', { valueDecimal: 0.09 }),
]),
cmp('b', 'cancer', 'not_comparable', [...reasons, 'horizon_not_published_by_model']),
],
),
),
);
expect(g.reference.map((r) => [r.years, r.reference])).toEqual([
[0, 0.001],
[5, 0.0027],
]);
expect(g.common).toEqual(reasons); // every model gives them
expect(g.models.map((m) => [m.model, m.outcome, m.rows.length])).toEqual([
['a', 'CIN2+', 2],
['b', 'cancer', 2],
]);
expect(g.models[0].reasons).toEqual([]); // nothing else shared by both of a's horizons
expect(g.models[0].rows[0].reasons).toEqual(['index_date_differs']);
expect(g.models[0].rows[1]).toMatchObject({
institutional: 0.07,
low: 0.05,
high: 0.09,
reasons: [],
});
expect(g.models[1].rows[1].reasons).toEqual(['horizon_not_published_by_model']);
});
it('never merges across outcomes: reasons are only shared where every compared row has them', () => {
const g = groupReference(
referenceView(
two(
[
cmp('a', 'CIN2+', 'not_comparable', ['outcome_differs']),
cmp('b', 'cancer', 'not_comparable', ['no_reference']),
],
[],
),
),
);
expect(g.common).toEqual([]);
expect(g.models.flatMap((m) => m.rows.flatMap((r) => r.reasons))).toEqual([
'outcome_differs',
'no_reference',
]);
});
it('a comparable row keeps its difference and a missing interval stays missing', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN3+',
'comparable',
[],
[
part('institutional', { valueDecimal: 0.01 }),
part('difference-pp', { valueDecimal: 0.9 }),
],
),
],
[],
),
),
);
expect(g.models[0].rows[0]).toMatchObject({
status: 'comparable',
differencePp: 0.9,
low: undefined,
});
});
it('without a model it says so once, with its reasons', () => {
const g = groupReference(
referenceView(
two(
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
),
),
);
expect(g.models).toEqual([]);
expect(g.withoutModel).toEqual(['no_institutional_model']);
});
});
+615
View File
@@ -0,0 +1,615 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The states a resolution ends in, as the screens say them. */
export const STATUS_TEXT: Record<string, string> = {
resolved: 'Referencia disponible',
not_published: 'Riesgo no publicado en las tablas',
missing_data: 'Falta un dato clínico',
history_not_demonstrable: 'Antecedente no demostrable',
not_applicable: 'Escenario no aplicable',
contradictory: 'Resultados contradictorios',
ambiguous: 'Escenario ambiguo',
scenario_not_implemented: 'Escenario aún no resuelto',
unverifiable_correspondence: 'Correspondencia no verificable',
no_published_row: 'Sin fila publicada para esta combinación',
};
/** Why a resolution or a comparison has no value. */
export const REASON_TEXT: Record<string, string> = {
no_cytology_reported_by_cutoff: 'No hay citología con resultado a la fecha de corte.',
sample_not_reported_by_cutoff: 'La citología pedida no tenía resultado a la fecha de corte.',
no_birth_date: 'Falta la fecha de nacimiento.',
age_outside_25_65: 'La edad está fuera del rango de las tablas (25 a 65 años).',
cytology_not_in_tables: 'El resultado citológico no está en las tablas.',
missing_hpv: 'La citología no tiene resultado de VPH.',
contradictory_hpv: 'El VPH es negativo pero se reporta un genotipo positivo.',
hpv_positive_row:
'Las tablas muestran «VPH positivo» junto a VPH 16 y VPH 18; no se verificó si esa fila es el total o los otros tipos, y no se asume.',
no_earlier_test_registered:
'La plataforma no tiene una prueba anterior con VPH; no demuestra que no haya antecedente.',
earlier_test_older_than_5_years: 'La prueba anterior es de hace más de 5 años.',
colposcopy_or_treatment_before:
'Hay una colposcopía, biopsia o tratamiento previo: es un escenario posterior a colposcopía o tratamiento, aún no resuelto.',
history_is_a_surveillance_scenario:
'El antecedente anormal corresponde a la tabla de vigilancia, aún no resuelta.',
registered_cin2_plus_before: 'Hay un CIN2+ registrado antes: las tablas lo excluyen.',
hysterectomy_declared: 'El formulario declara una histerectomía: las tablas la excluyen.',
procedure_after_without_named_referral:
'Hay una colposcopía o biopsia posterior, pero ningún registro la nombra como derivada de esta citología (una asociación por fechas no basta).',
several_biopsies_name_the_cytology: 'Varias biopsias nombran esta citología.',
not_a_referral_result_in_the_tables:
'La citología no es un resultado de derivación de las tablas.',
hsil_cin2_cin3: 'La histología «LIEAG» no distingue CIN2 de CIN3, que las tablas separan.',
cis_ais: 'El carcinoma in situ no distingue el adenocarcinoma in situ, que las tablas separan.',
biopsy_without_histology: 'La biopsia no tiene histología.',
risk_blank_in_the_tables: 'Las tablas dejan este riesgo en blanco.',
no_row_for_the_combination: 'Las tablas no publican esa combinación.',
several_rows: 'Más de una fila podría corresponder.',
no_institutional_model: 'Ningún modelo institucional ha evaluado a la paciente.',
outcome_differs: 'El desenlace del modelo no es el de la tabla (CIN3+).',
unknown_model: 'El desenlace del modelo no está registrado para comparar.',
horizon_not_published_by_model: 'El modelo no publica una predicción a este horizonte.',
index_date_differs: 'La fecha índice del modelo no es la de la citología evaluada.',
population_not_verified:
'No se verificó que la población y el escenario del modelo coincidan con los de la tabla.',
no_reference: 'Las tablas no dan un riesgo a este horizonte.',
};
const KEY_TEXT: Record<string, string> = {
history: 'Antecedente más reciente',
hpv: 'VPH actual',
cytology: 'Citología actual',
referral: 'Resultado de tamizaje que originó la colposcopía',
biopsy: 'Resultado de biopsia',
};
const USED_TEXT: Record<string, string> = {
'sample-date': 'toma',
'report-date': 'reporte',
'request-date': 'solicitud',
result: 'resultado',
hpv: 'VPH',
'hpv-16': 'VPH 16',
'hpv-18': 'VPH 18',
histology: 'histología',
};
const usedValue = (v: unknown) => (v === true ? 'positivo' : v === false ? 'negativo' : String(v));
export interface ComparisonView {
model?: string;
title?: string;
outcome?: string;
/** probabilities, 0 to 1 */
institutional?: number;
low?: number;
high?: number;
status: string;
/** percentage points, institutional minus reference */
differencePp?: number;
reasons: string[];
}
export interface HorizonView {
years: number;
label: string;
published: boolean;
/** probability, 0 to 1; none when the tables leave it blank */
reference?: number;
comparisons: ComparisonView[];
}
export interface ReferenceView {
status: string;
reasons: string[];
cutoff?: string;
scenario?: { label: string; keys: { name: string; value: string }[] };
index?: { sampleDate?: string; reportDate?: string; result?: string; age?: number };
evaluationDate?: string;
source?: { id?: string; file?: string; sha256?: string; outcome?: string; status?: string };
row?: { sheet?: string; number?: number; officialCheck?: string; matchedVia?: string };
used: { label: string; details: string }[];
assumptions: string[];
horizons: HorizonView[];
}
type Part = ParametersParameter;
const value = (p?: Part) =>
p?.valueCode ??
p?.valueString ??
p?.valueDate ??
p?.valueInteger ??
p?.valueDecimal ??
p?.valueBoolean ??
undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const one = (parts: Part[] | undefined, name: string) => value(named(parts, name)[0]);
/** The horizon's name; the colposcopy table's one year is a year, never "immediate". */
export function horizonLabel(years: number): string {
return years === 0 ? 'Inmediato (al índice)' : years === 1 ? '1 año' : `${years} años`;
}
/** The result of `$reference-risk` as the section shows it. A value absent from the answer stays
* absent: no zero is made of a blank, and no difference is made of a comparison that is not one. */
export function referenceView(answer: Parameters): ReferenceView {
const top = answer.parameter ?? [];
const scenario = named(top, 'scenario')[0];
const index = named(top, 'index')[0]?.part;
const row = named(top, 'row')[0]?.part;
const source = named(top, 'source')[0]?.part;
const view: ReferenceView = {
status: String(one(top, 'status') ?? 'missing_data'),
reasons: named(top, 'reason').map((r) => String(value(r))),
cutoff: one(top, 'cutoff') as string | undefined,
evaluationDate: one(top, 'evaluation-date') as string | undefined,
used: named(top, 'used').map((u) => ({
label: String(one(u.part, 'label') ?? ''),
details: (u.part ?? [])
.filter((p) => p.name !== 'label')
.map((p) => `${USED_TEXT[p.name ?? ''] ?? p.name}: ${usedValue(value(p))}`)
.join(' · '),
})),
assumptions: named(top, 'assumption').map((a) => String(value(a))),
horizons: named(top, 'horizon').map((h) => {
const years = Number(one(h.part, 'years'));
return {
years,
label: horizonLabel(years),
published: one(h.part, 'published') === true,
reference: one(h.part, 'reference') as number | undefined,
comparisons: named(h.part, 'comparison').map((c) => ({
model: one(c.part, 'model') as string | undefined,
title: one(c.part, 'title') as string | undefined,
outcome: one(c.part, 'outcome') as string | undefined,
institutional: one(c.part, 'institutional') as number | undefined,
low: one(c.part, 'institutional-low') as number | undefined,
high: one(c.part, 'institutional-high') as number | undefined,
status: String(one(c.part, 'status')),
differencePp: one(c.part, 'difference-pp') as number | undefined,
reasons: named(c.part, 'reason').map((r) => String(value(r))),
})),
};
}),
};
if (scenario?.part)
view.scenario = {
label: String(one(scenario.part, 'label') ?? ''),
keys: named(scenario.part, 'key').map((k) => ({
name: KEY_TEXT[String(one(k.part, 'name'))] ?? String(one(k.part, 'name')),
value: String(one(k.part, 'value')),
})),
};
if (index)
view.index = {
sampleDate: one(index, 'sample-date') as string | undefined,
reportDate: one(index, 'report-date') as string | undefined,
result: one(index, 'result') as string | undefined,
age: one(index, 'age') as number | undefined,
};
if (row)
view.row = {
sheet: one(row, 'sheet') as string | undefined,
number: one(row, 'number') as number | undefined,
officialCheck: one(row, 'official-check') as string | undefined,
matchedVia: one(row, 'matched-via') as string | undefined,
};
if (source)
view.source = {
id: one(source, 'id') as string | undefined,
file: one(source, 'file') as string | undefined,
sha256: one(source, 'sha256') as string | undefined,
outcome: one(source, 'outcome') as string | undefined,
status: one(source, 'status') as string | undefined,
};
return view;
}
/** Outcome names as the screens say them; presentation only: the API's identifiers stay as they are
* (an outcome this map does not know is shown as the API gave it). */
export const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3 o más grave (CIN3+)',
'CIN2+': 'CIN2 o más grave (CIN2+)',
cancer: 'Cáncer',
'CIN2+ within one year': 'CIN2+ en un año',
'not stated as a histology outcome': 'No expresado como desenlace histológico',
};
export const outcomeText = (outcome?: string) => (outcome ? (OUTCOME_TEXT[outcome] ?? outcome) : '');
export interface ModelRow extends Omit<ComparisonView, 'reasons'> {
years: number;
label: string;
/** the reasons of this horizon that its model's other horizons do not share */
reasons: string[];
}
export interface ModelBlock {
model?: string;
title?: string;
outcome?: string;
/** reasons shared by every non-comparable horizon of this model, said once */
reasons: string[];
rows: ModelRow[];
}
export interface Grouped {
/** the reference by horizon: one table, whatever the models */
reference: { years: number; label: string; published: boolean; reference?: number }[];
/** reasons shared by every non-comparable comparison of every model, said once */
common: string[];
models: ModelBlock[];
/** no institutional model evaluated her: said once, with its reasons */
withoutModel: string[];
}
const shared = (lists: string[][]) =>
lists.length > 1 ? lists[0].filter((r) => lists.every((l) => l.includes(r))) : [];
/** Groups only what is equivalent: the reference once per horizon; a reason that every non-comparable
* comparison of a model (or of all models) gives, once; everything else stays where it is. Nothing is
* dropped, and a difference is never made: it is only the API's, on a comparable row. */
export function groupReference(v: ReferenceView): Grouped {
const reference = v.horizons.map((h) => ({
years: h.years,
label: h.label,
published: h.published,
reference: h.reference,
}));
const byModel = new Map<string, ModelBlock>();
const withoutModel: string[] = [];
for (const h of v.horizons)
for (const c of h.comparisons) {
if (!c.model) {
for (const r of c.reasons) if (!withoutModel.includes(r)) withoutModel.push(r);
continue;
}
const block = byModel.get(c.model) ?? {
model: c.model,
title: c.title,
outcome: c.outcome,
reasons: [],
rows: [],
};
byModel.set(c.model, block);
block.rows.push({ ...c, years: h.years, label: h.label });
}
const models = [...byModel.values()];
const notComparable = (b: ModelBlock) => b.rows.filter((r) => r.status !== 'comparable');
const common = shared(models.flatMap(notComparable).map((r) => r.reasons));
const everyModel = models.length > 1 ? common : [];
for (const b of models) {
const own = shared(notComparable(b).map((r) => r.reasons.filter((x) => !everyModel.includes(x))));
b.reasons = own;
for (const r of b.rows)
if (r.status !== 'comparable')
r.reasons = r.reasons.filter((x) => !everyModel.includes(x) && !own.includes(x));
}
return { reference, common: everyModel, models, withoutModel };
}
const OFFICIAL: Record<string, string> = {
match: 'coincide con la tabla del NCI',
'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo',
differs: 'no coincide con la tabla del NCI',
not_found_in_official: 'sin fila equivalente en la tabla del NCI consultada',
blank_in_both: 'en blanco en ambas',
no_official_file: 'sin tabla del NCI para cotejar',
};
/** Comparison with the NCI's reference risks (experimental): the reference by horizon beside the
* institutional models', the difference only where the two are the same estimate. */
@Component({
selector: 'app-reference-risk',
imports: [DecimalPipe],
template: `
@let v = view();
<section
class="reference"
data-section="referencia-nci"
aria-label="Comparación de riesgos de referencia"
>
<h3>Comparación de riesgos de referencia</h3>
<dl class="meta">
<div>
<dt>Estado</dt>
<dd [attr.data-status]="v.status">{{ statusText(v.status) }}</dd>
</div>
@if (v.scenario; as s) {
<div>
<dt>Escenario clínico</dt>
<dd>{{ s.label }}</dd>
</div>
}
@if (v.source?.outcome; as out) {
<div>
<dt>Desenlace de la referencia</dt>
<dd [attr.data-outcome]="out">{{ outcomeText(out) }}</dd>
</div>
}
@if (v.evaluationDate ?? v.index?.sampleDate; as day) {
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ day }}</dd>
</div>
}
@if (v.cutoff) {
<div>
<dt>Fecha de corte</dt>
<dd>{{ v.cutoff }}</dd>
</div>
}
@if (v.source; as src) {
<div>
<dt>Fuente y versión</dt>
<dd>Tablas NCI (libro {{ src.file }}, {{ src.id }}); no validadas</dd>
</div>
}
</dl>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivo">
@for (r of v.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (v.horizons.length) {
@let g = grouped();
<table class="plain" aria-label="Referencia NCI por horizonte">
<thead>
<tr>
<th>Horizonte</th>
<th>Referencia NCI</th>
</tr>
</thead>
<tbody>
@for (h of g.reference; track h.years) {
<tr [attr.data-years]="h.years">
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
<td class="nowrap" data-label="Referencia NCI">
@if (h.reference !== undefined) {
<strong>{{ h.reference * 100 | number: '1.2-2' }} %</strong>
} @else {
<span>No publicado</span>
}
</td>
</tr>
}
</tbody>
</table>
<h4>Modelos institucionales</h4>
@if (g.withoutModel.length || !g.models.length) {
<p class="nomodel">
<strong>No disponible</strong>
</p>
<ul class="why" aria-label="Motivo">
@for (r of g.withoutModel; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (g.common.length) {
<p class="muted">Motivos que comparten todas las comparaciones no válidas:</p>
<ul class="why" aria-label="Motivos comunes">
@for (r of g.common; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@for (m of g.models; track m.model) {
<section class="model" [attr.data-model]="m.model" [attr.aria-label]="m.title">
<h5>
{{ m.title }}
<span class="muted" [attr.data-outcome]="m.outcome">{{ outcomeText(m.outcome) }}</span>
</h5>
@if (m.reasons.length) {
<p class="muted">No comparable en estos horizontes:</p>
<ul class="why" aria-label="Motivos del modelo">
@for (r of m.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
<table class="plain" [attr.aria-label]="'Comparación de ' + m.title">
<thead>
<tr>
<th>Horizonte</th>
<th>Modelo institucional</th>
<th>Diferencia (puntos porcentuales)</th>
</tr>
</thead>
<tbody>
@for (c of m.rows; track c.years) {
<tr [attr.data-years]="c.years">
<td class="nowrap" data-label="Horizonte">{{ c.label }}</td>
<td data-label="Modelo institucional">
@if (c.institutional !== undefined) {
{{ c.institutional * 100 | number: '1.2-2' }} %
@if (c.low !== undefined && c.high !== undefined) {
<span class="muted"
>(IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{
c.high * 100 | number: '1.2-2'
}}
%)</span
>
}
} @else {
<span>No disponible</span>
}
</td>
<td data-label="Diferencia (puntos porcentuales)">
@if (c.status === 'comparable' && c.differencePp !== undefined) {
<strong
>{{ c.differencePp > 0 ? '+' : ''
}}{{ c.differencePp | number: '1.2-2' }}</strong
>
} @else {
<span>No comparable</span>
@if (c.reasons.length) {
<ul class="why">
@for (r of c.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
}
</td>
</tr>
}
</tbody>
</table>
</section>
}
<p class="muted note">
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
</p>
}
@if (v.used.length || v.assumptions.length || v.scenario || v.row) {
<details class="used">
<summary>Antecedentes utilizados</summary>
@if (v.scenario; as s) {
<ul>
@for (k of s.keys; track k.name) {
<li>{{ k.name }}: {{ k.value }}</li>
}
</ul>
}
@if (v.index; as i) {
<p>
Citología evaluada: toma {{ i.sampleDate }}, reporte {{ i.reportDate }}, resultado
{{ i.result }}
@if (i.age !== undefined) {
, edad {{ i.age }} años
}
.
</p>
}
<ul>
@for (u of v.used; track $index) {
<li>
<strong>{{ u.label }}</strong>: {{ u.details }}
</li>
}
</ul>
@if (v.row; as r) {
<p class="muted">
Fila de origen: «{{ r.sheet }}», fila {{ r.number }}
@if (r.matchedVia === 'table_group') {
(categoría agrupada definida por la propia tabla)
}
— {{ official(r.officialCheck) }}.
</p>
}
@for (a of v.assumptions; track a) {
<p class="muted">Sin verificar: {{ a }}</p>
}
</details>
}
</section>
`,
styles: `
.reference {
border: 1px dashed #9aa3ab;
border-radius: 6px;
margin: 16px 0;
padding: 12px 16px;
}
h3 {
margin: 0 0 8px;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
margin: 0 0 8px;
}
.meta dt {
color: var(--color-text-secondary);
font-size: 12px;
}
.meta dd {
font-weight: 500;
margin: 0;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th,
td {
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
.model {
border-top: 1px solid #dce3e7;
margin-top: 8px;
padding-top: 4px;
}
h4,
h5 {
margin: 12px 0 4px;
}
h5 .muted {
font-weight: 400;
margin-left: 8px;
}
.why {
margin: 4px 0;
padding-left: 18px;
}
.note {
font-size: 12px;
}
.used {
margin-top: 8px;
}
.used summary {
cursor: pointer;
}
@media (max-width: 700px) {
.reference {
padding: 8px 10px;
}
table,
thead,
tbody,
tr,
th,
td {
display: block;
}
thead {
display: none;
}
tr {
border-bottom: 1px solid #dce3e7;
padding: 6px 0;
}
td {
padding: 2px 0;
}
td::before {
color: var(--color-text-secondary);
content: attr(data-label);
display: block;
font-size: 12px;
}
}
`,
})
export class ReferenceRisk {
readonly view = input.required<ReferenceView>();
protected readonly grouped = computed(() => groupReference(this.view()));
protected outcomeText(outcome?: string) {
return outcomeText(outcome);
}
protected statusText(status: string) {
return STATUS_TEXT[status] ?? status;
}
protected reasonText(reason: string) {
return REASON_TEXT[reason] ?? reason;
}
protected official(check?: string) {
return OFFICIAL[check ?? ''] ?? 'sin cotejo';
}
}
+100
View File
@@ -0,0 +1,100 @@
import { curveFigure, curveText } from './risk-curve';
const model = (text: string, predictions: object[], index = '2026-06-01') => ({
text,
index,
predictions: predictions as { years: number; p: number; low?: number; high?: number }[],
});
const traces = (models: ReturnType<typeof model>[]) => curveFigure(models, 0.4).data as any[];
describe('the institutional curves', () => {
it('draws one series per model, named as the model, at the horizons it publishes only', () => {
const found = traces([
model('Riesgo LIEAG+ v3', [
{ years: 1, p: 0.08 },
{ years: 3, p: 0.21 },
{ years: 5, p: 0.34 },
]),
model('Riesgo cáncer v2', [{ years: 5, p: 0.015 }]),
]);
const lines = found.filter((t) => !t.name?.startsWith('IC'));
expect(lines.map((t) => t.name)).toEqual(['Riesgo LIEAG+', 'Riesgo cáncer']);
expect(lines[0].x).toEqual([1, 3, 5]);
expect(lines[0].y.map((y: number) => Math.round(y))).toEqual([8, 21, 34]);
expect(lines[1].x).toEqual([5]); // a single horizon is a point, not a line to nowhere
expect(lines[1].mode).toBe('markers');
expect(lines[0].color ?? lines[0].line.color).not.toBe(lines[1].line.color);
});
it('puts the axis ticks on the published horizons and invents none between them', () => {
const f = curveFigure(
[
model('M v1', [
{ years: 0, p: 0.01 },
{ years: 5, p: 0.05 },
]),
],
0.05,
);
expect((f.layout!.xaxis as any).tickvals).toEqual([0, 5]);
expect((f.layout!.xaxis as any).title.text).toBe(
'Horizonte (años desde la fecha índice (2026-06-01))',
);
const mixed = curveFigure(
[model('A v1', [{ years: 1, p: 0.1 }]), model('B v1', [{ years: 3, p: 0.2 }], '2026-07-01')],
0.2,
);
expect((mixed.layout!.xaxis as any).tickvals).toEqual([1, 3]);
expect((mixed.layout!.xaxis as any).title.text).toBe('Horizonte (años desde la fecha índice)'); // two index dates: none is named
});
it('draws a band only where intervals are published, with its own legend entry, and no band without them', () => {
const none = traces([
model('Sin IC v1', [
{ years: 1, p: 0.1 },
{ years: 5, p: 0.3 },
]),
]);
expect(none).toHaveLength(1);
expect(none[0].fill).toBeUndefined();
const withBand = traces([
model('Con IC v1', [
{ years: 1, p: 0.1, low: 0.05, high: 0.12 },
{ years: 3, p: 0.2, low: 0.15, high: 0.28 },
{ years: 5, p: 0.3, low: 0.26, high: 0.44 },
]),
]);
expect(withBand.map((t) => t.name)).toEqual([undefined, 'IC 95 % Con IC', 'Con IC']);
expect(withBand[1].fill).toBe('tonexty');
expect(withBand[1].y.map((y: number) => Math.round(y))).toEqual([5, 15, 26]);
});
it('a horizon without an interval is a gap in the band, never filled with the probability', () => {
const [high, low] = traces([
model('Hueco v1', [
{ years: 1, p: 0.1, low: 0.05, high: 0.12 },
{ years: 3, p: 0.2 },
{ years: 5, p: 0.3, low: 0.26, high: 0.44 },
]),
]);
expect(high.y[1]).toBeNull();
expect(low.y[1]).toBeNull();
expect(low.connectgaps).toBe(false);
});
it('one published interval is an error bar, not a band', () => {
const found = traces([model('Uno v1', [{ years: 5, p: 0.34, low: 0.26, high: 0.44 }])]);
expect(found).toHaveLength(1);
expect(found[0].error_y.array[0]).toBeCloseTo(10);
expect(found[0].error_y.arrayminus[0]).toBeCloseTo(8);
});
it('says each model, its index date and every horizon it publishes, with intervals only where there are', () => {
expect(
curveText([
model('Riesgo LIEAG+ v3', [
{ years: 5, p: 0.34, low: 0.26, high: 0.44 },
{ years: 1, p: 0.08 },
]),
model('Vacío v1', []),
]),
).toEqual([
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 %; 5 años: 34.0 % (IC 95 %: 26.0–44.0 %).',
]);
});
});
+126
View File
@@ -0,0 +1,126 @@
import { Figure, PALETTE } from '../plot';
export interface CurvePrediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface CurveModel {
/** the model's own title, with its version */
text: string;
/** the model's index date */
index: string;
predictions: CurvePrediction[];
}
const percent = (n: number) =>
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 });
const title = (m: CurveModel) => m.text.replace(/ v\d+$/, '');
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
* publishes (a model with one horizon is a point), its 95 % interval as a band where it publishes
* one at two or more horizons and as an error bar at a single one. No horizon, interval or
* probability is made up: between published horizons the line joins them and nothing else. The
* NCI reference is not here. */
export function curveFigure(models: CurveModel[], top: number): Figure {
const shown = models.filter((m) => m.predictions.length);
const years = [...new Set(shown.flatMap((m) => m.predictions.map((p) => p.years)))].sort(
(a, b) => a - b,
);
const dates = [...new Set(shown.map((m) => m.index))];
return {
data: shown.flatMap((m, i) => {
const color = PALETTE[i % PALETTE.length];
const sorted = [...m.predictions].sort((a, b) => a.years - b.years);
const x = sorted.map((p) => p.years);
const name = title(m);
const bounded = sorted.filter(interval);
const traces: object[] = [];
if (bounded.length > 1) {
// a gap in the published intervals stays a gap: nothing is drawn between them
const at = (pick: (p: CurvePrediction) => number | undefined) =>
sorted.map((p) => (interval(p) ? (pick(p) as number) * 100 : null));
traces.push(
{
x,
y: at((p) => p.high),
mode: 'lines',
line: { width: 0 },
connectgaps: false,
showlegend: false,
hoverinfo: 'skip',
legendgroup: name,
},
{
x,
y: at((p) => p.low),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
connectgaps: false,
fillcolor: color + '33',
name: `IC 95 % ${name}`,
legendgroup: name,
hoverinfo: 'skip',
},
);
}
traces.push({
x,
y: sorted.map((p) => p.p * 100),
mode: sorted.length > 1 ? 'lines+markers' : 'markers',
name,
legendgroup: name,
line: { color },
marker: { color, size: 8 },
...(bounded.length === 1
? {
error_y: {
type: 'data',
symmetric: false,
color,
array: sorted.map((p) => (interval(p) ? (p.high! - p.p) * 100 : 0)),
arrayminus: sorted.map((p) => (interval(p) ? (p.p - p.low!) * 100 : 0)),
},
}
: {}),
hovertemplate: `${name}<br>%{x} años: %{y:.2f} %<extra></extra>`,
});
return traces;
}) as Figure['data'],
layout: {
xaxis: {
title: {
text: `Horizonte (años desde la fecha índice${dates.length === 1 ? ` (${dates[0]})` : ''})`,
},
tickmode: 'array',
tickvals: years,
ticktext: years.map(String),
},
// At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: {
title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, top * 110)],
tickformat: '.0f',
},
},
} as Figure;
}
/** The curves in words: each model, its index date and every horizon it publishes, with its
* interval where it has one. */
export function curveText(models: CurveModel[]): string[] {
return models
.filter((m) => m.predictions.length)
.map((m) => {
const sorted = [...m.predictions].sort((a, b) => a.years - b.years);
const said = sorted.map(
(p) =>
`${p.years === 0 ? 'al índice' : `${p.years} ${p.years === 1 ? 'año' : 'años'}`}: ${percent(p.p)} %` +
(interval(p) ? ` (IC 95 %: ${percent(p.low!)}–${percent(p.high!)} %)` : ''),
);
return `${title(m)} (fecha índice ${m.index}): ${said.join('; ')}.`;
});
}
+104
View File
@@ -0,0 +1,104 @@
import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
describe('the risk scales', () => {
it('keeps zero as a value, and a missing horizon as none', () => {
expect(horizon([at(0, 0), at(5, 0.5)], 0)).toMatchObject({ p: 0 });
expect(horizon([at(5, 0.5)], 0)).toBeUndefined(); // never taken from another horizon
expect(horizon([at(0, 0.02)], 5)).toBeUndefined();
expect(horizon([], 5)).toBeUndefined();
});
it('reads 0, 2, 50, 98 and 100 % as they are', () => {
for (const p of [0, 0.02, 0.5, 0.98, 1]) expect(horizon([at(5, p)], 5)?.p).toBe(p);
});
it('a value outside 0 to 1 is not a prediction; an interval needs both ends inside 0 to 1', () => {
expect(horizon([at(5, 1.2)], 5)).toBeUndefined();
expect(horizon([at(5, -0.1)], 5)).toBeUndefined();
expect(horizon([at(5, Number.NaN)], 5)).toBeUndefined();
expect(horizon([at(5, 0.4, 0.3, 0.5)], 5)).toMatchObject({ low: 0.3, high: 0.5 });
expect(horizon([at(5, 0.4, 0.3)], 5)).toMatchObject({
p: 0.4,
low: undefined,
high: undefined,
});
expect(horizon([at(5, 0.4, 0.6, 0.5)], 5)?.low).toBeUndefined();
expect(horizon([at(5, 0.4, -0.1, 0.5)], 5)?.low).toBeUndefined();
});
it('draws both horizons of every model, each model with its own title and index day', () => {
const groups = riskGroups([
{
text: 'Supervivencia v3',
index: '2026-02-01',
predictions: [at(0, 0), at(5, 0.5, 0.4, 0.6)],
},
{ text: 'Recurrencia v2', index: '2026-03-01', predictions: [at(5, 0.98)] },
{ text: 'Otro', index: '2026-03-02', predictions: [at(3, 0.3)] }, // no horizon of its own
]);
expect(groups.map((g) => g.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años'];
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
expect(groups[0].scales.map((s) => s.risk?.p)).toEqual([0, 0.5]);
expect(groups[1].scales.map((s) => s.risk?.p)).toEqual([undefined, 0.98]);
expect(groups[2].scales.map((s) => s.risk)).toEqual([undefined, undefined]);
});
it('with no model, both horizons are drawn unavailable', () => {
const [none, ...rest] = riskGroups([]);
expect(rest).toEqual([]);
expect(none.title).toBeUndefined();
expect(none.scales.map((s) => [s.label, s.risk])).toEqual([
['Riesgo inmediato (al índice)', undefined],
['Riesgo 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',
]);
});
});
describe('which models feed the risk scales', () => {
it('excludes survival and recurrence estimates, which are not risks of the scales outcome', () => {
expect(['cacu.cin2_pim', 'cacu.cancer_pim', 'cacu.cin2_logistic'].every(isRiskModel)).toBe(
true,
);
expect(isRiskModel('cacu.survival')).toBe(false);
expect(isRiskModel('cama.recurrence')).toBe(false);
});
it('with no risk model both horizons are unavailable (nothing is converted from a survival)', () => {
const risk = [
{
text: 'm',
index: '2026-01-01',
predictions: [{ years: 5, p: 0.7 }],
model: 'cacu.survival',
},
].filter((m) => isRiskModel(m.model));
expect(riskGroups(risk).flatMap((g) => g.scales.map((s) => s.risk))).toEqual([
undefined,
undefined,
]);
});
});
describe('survival scales', () => {
it('complements mortality and reverses interval bounds at every published horizon', () => {
const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
expect(g.survival).toBe(true);
expect(g.index).toBe('2026-01-01');
expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
});
it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
.toEqual(inputs);
expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
.toBeUndefined();
});
});
+345
View File
@@ -0,0 +1,345 @@
import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core';
interface Prediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface RiskScale {
label: string;
risk?: Prediction;
}
/** Whether a model's estimate is a risk of the outcome the scales and curves draw. Survival (S(t)) and
* recurrence-free survival are estimates of another outcome, shown in their own analysis: they are
* never drawn on these scales, and no conversion (1 − S) is made. */
export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(model);
/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) =>
[0, 5].map((years) => ({
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`,
risk: m.predictions.find((p) => p.years === years),
})),
);
}
const unit = (n?: number): n is number => typeof n === 'number' && n >= 0 && n <= 1;
/** A model's published prediction at one horizon, when it is a probability: zero is a real value,
* a missing horizon is none (never taken from another horizon), a value outside 0 to 1 is none. */
export function horizon(predictions: Prediction[], years: number): Prediction | undefined {
const found = predictions.find((p) => p.years === years);
if (!found || !unit(found.p)) return undefined;
const interval = unit(found.low) && unit(found.high) && found.low <= found.high;
return {
...found,
low: interval ? found.low : undefined,
high: interval ? found.high : undefined,
};
}
/** One model's two horizons, each with its prediction or none. */
export interface RiskGroup {
/** the model's own title and the day it was scored (none: no model has scored her) */
title?: string;
scenario?: string;
index?: string;
survival?: boolean;
inputs?: Record<string, unknown>;
/** the model and version that scored her, and the day it did */
model?: string;
evaluated?: string;
scales: { label: string; risk?: Prediction }[];
}
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(
models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
text?: string;
evaluated?: string;
}[],
): RiskGroup[] {
return models
.map((m) => ({
title: 'Supervivencia',
index: m.index,
survival: true,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '),
scales: m.predictions.flatMap((p) => {
const v = horizon(m.predictions, p.years);
return v
? [
{
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
}))
.filter((g) => g.scales.length);
}
const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'],
];
/** 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 };
}
/** 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[];
inputs?: Record<string, unknown>;
evaluated?: string;
}[],
): RiskGroup[] {
const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
return models.length
? models.map((m) => ({
...titleParts(m.text),
index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions),
}))
: [{ scales: scales([]) }];
}
/** Segmented scales of 0 to 100 %. The four equal parts are numeric and descriptive: they do not
* stand for clinical thresholds. Without a prediction the bar is neutral grey, says it is not
* available and has no marker. */
@Component({
selector: 'app-risk-scales',
imports: [DecimalPipe],
template: `
@for (g of groups(); track $index) {
@if (g.title) {
<h3>{{ g.title }}</h3>
}
@for (s of g.scales; track s.label) {
<div class="risk-scale" [attr.data-scale]="s.label">
<p>
<strong>{{ s.label }}</strong>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }}
%
}
} @else {
· No disponible
}
</p>
<div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
<span
class="risk-interval"
[style.left.%]="r.low * 100"
[style.width.%]="(r.high - r.low) * 100"
aria-hidden="true"
></span>
}
<span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
<strong
class="risk-value"
[style.left]="'clamp(2.5rem, ' + r.p * 100 + '%, calc(100% - 2.5rem))'"
>{{ r.p * 100 | number: '1.1-2' }} %</strong
>
}
</div>
<div class="risk-labels" aria-hidden="true">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span>
</div>
</div>
}
@if (g.index) {
<p class="muted foot">
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p>
}
@if (g.title && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (item of entries(g.inputs); track item[0]) {
<div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</section>
}
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (item of entries(g.inputs ?? {}); track item[0]) {
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
}
`,
styles: `
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
}
.risk-scale p {
margin: 0;
}
.risk-plot {
padding-top: 30px;
position: relative;
}
.risk-line {
background: linear-gradient(
to right,
#42a77e 0 25%,
#a8c243 25% 50%,
#df8640 50% 75%,
#c24269 75% 100%
);
height: 16px;
}
.unavailable .risk-line {
background: repeating-linear-gradient(
to right,
#d9dfe2 0,
#d9dfe2 calc(25% - 1px),
#fff calc(25% - 1px),
#fff 25%
);
}
.survival .risk-line {
background: linear-gradient(
to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
}
.risk-interval {
border-left: 2px solid #17324d;
border-right: 2px solid #17324d;
height: 8px;
min-width: 2px;
position: absolute;
top: 20px;
}
.risk-interval::before {
background: #17324d;
content: '';
height: 2px;
left: 0;
position: absolute;
right: 0;
top: 3px;
}
.foot {
font-size: 12px;
}
.risk-marker {
background: #17324d;
bottom: -2px;
height: 20px;
position: absolute;
transform: translateX(-50%);
width: 3px;
}
.risk-value {
color: #17324d;
font-size: 13px;
position: absolute;
top: 1px;
transform: translateX(-50%);
white-space: nowrap;
}
.risk-labels {
display: flex;
font-size: 12px;
justify-content: space-between;
margin-top: 3px;
}
`,
})
export class RiskScales {
readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries;
protected readonly inputName = (name: string) =>
(
({
age_group: 'Edad al diagnóstico',
cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
}
+32
View File
@@ -0,0 +1,32 @@
import { parseSeries, seriesName } from './risk-series';
describe('risk series', () => {
it('reads each series and keeps an absent interval absent', () => {
const [series] = parseSeries({
resourceType: 'Parameters',
parameter: [
{
name: 'series',
part: [
{ name: 'id', valueString: 'cacu.cin2_pim' },
{ name: 'source', valueString: 'Institucional' },
{ name: 'outcome', valueString: 'CIN2+' },
{ name: 'status', valueCode: 'resolved' },
{
name: 'point',
part: [
{ name: 'years', valueInteger: 0 },
{ name: 'probability', valueDecimal: 0 },
],
},
],
},
],
});
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
'NCI, ingreso a LIEAG+',
);
});
});

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