Compare commits
27 Commits
d09e8c59ed
...
rebuild
| Author | SHA1 | Date | |
|---|---|---|---|
| 76054eae9a | |||
| ec3eeeef65 | |||
| 83a360aed1 | |||
| cf2dcdfde7 | |||
| ea507c119a | |||
| 620572555d | |||
| 4852d933fa | |||
| 9bc949edd3 | |||
| d3f6f5c214 | |||
| e0084ef9ff | |||
| 682c100b67 | |||
| fe4dd55452 | |||
| 053679c817 | |||
| ffa732df12 | |||
| 786b199203 | |||
| ca887c29ab | |||
| bb506c3926 | |||
| b48c025400 | |||
| a93cd71126 | |||
| 979b7cf34d | |||
| cde9b1cfb1 | |||
| edc32af67e | |||
| 2216186d26 | |||
| 55c4e0b173 | |||
| 52cca0a84c | |||
| 7e50ff9b90 | |||
| ac1d8fc4fa |
@@ -0,0 +1,116 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
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 clínicos'))).toEqual([
|
||||
'Indicadores clínicos',
|
||||
'Resultados de citología, VPH y biopsia',
|
||||
'Distribución de resultados citológicos',
|
||||
'Resultados de VPH por genotipo',
|
||||
'Resultados de biopsia cervical',
|
||||
'Tasa de confirmación histopatológica',
|
||||
'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||
'Indicadores de oportunidad',
|
||||
'Tiempos de tamizaje',
|
||||
]);
|
||||
// one selector reads both the cytology and the HPV card by group
|
||||
await tab.getByRole('radio', { name: 'Por detección inicial y anterior' }).first().click();
|
||||
for (const card of ['Distribución de resultados citológicos', 'Resultados de VPH por genotipo'])
|
||||
await expect(
|
||||
tab
|
||||
.locator('app-readings', { has: page.getByRole('heading', { name: card }) })
|
||||
.locator('section.group')
|
||||
.first(),
|
||||
).toBeVisible();
|
||||
const route = tab.locator('app-readings').last();
|
||||
for (const mode of [
|
||||
'Por ventana de tiempo',
|
||||
'Diagnóstico precolposcópico',
|
||||
'Diagnóstico tras biopsia',
|
||||
'Acumulado desde la toma',
|
||||
]) {
|
||||
await route.getByRole('radio', { name: mode }).click();
|
||||
await expect(
|
||||
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
|
||||
).toBeVisible();
|
||||
}
|
||||
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
|
||||
await expect(
|
||||
tab.getByRole('heading', {
|
||||
name: 'Tasa de confirmación histopatológica de referencia a biopsia',
|
||||
}),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('indicadores cama: its sections in order, the route chained and the types by BI-RADS', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto('/indicadores/cama');
|
||||
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, h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
|
||||
'Indicadores de oportunidad',
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 o 6',
|
||||
'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
'Tiempo de interpretación radiológica a diagnóstico',
|
||||
'Tiempo de interpretación radiológica a resultado de biopsia',
|
||||
'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
'Tiempo de tamizaje a diagnóstico',
|
||||
'Tiempo de tamizaje a diagnóstico y tratamiento',
|
||||
'Indicadores clínicos',
|
||||
expect.stringMatching(/^Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en /),
|
||||
expect.stringMatching(/^Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en /),
|
||||
'Tipo histológico por categoría BI-RADS',
|
||||
'Confirmación histopatológica',
|
||||
]);
|
||||
const types = tab.locator('app-readings', {
|
||||
has: page.getByRole('heading', { name: 'Tipo histológico por categoría BI-RADS' }),
|
||||
});
|
||||
await expect(types.getByRole('columnheader', { name: '% maligno' })).toBeVisible();
|
||||
await tab.getByRole('radio', { name: 'Mastografías con biopsia' }).click();
|
||||
await expect(tab.getByRole('table', { name: 'Con y sin biopsia' })).toBeVisible();
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
+122
@@ -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)];
|
||||
});
|
||||
}
|
||||
+115
-15
@@ -1,5 +1,6 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
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. */
|
||||
function watch(page: Page): string[] {
|
||||
@@ -55,16 +56,17 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
|
||||
`${count.toLocaleString('es-MX')} pacientes`,
|
||||
);
|
||||
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
|
||||
// CaCu's readings are bars and tables, not plots
|
||||
await expect(page.locator('app-tab-indicadores app-readings').first()).toBeVisible();
|
||||
|
||||
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(10);
|
||||
|
||||
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?'));
|
||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
const bundle = await (await list).json();
|
||||
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
|
||||
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
|
||||
@@ -72,7 +74,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.first().locator('a').first()).toHaveText(first);
|
||||
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 rows.first().locator('a').first().click();
|
||||
@@ -84,13 +86,26 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
||||
|
||||
await page.goto('/indicadores/cama');
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
||||
await page.getByRole('tab', { name: 'Análisis de Riesgo' }).click();
|
||||
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
|
||||
await page.getByRole('option', { name: '12 meses' }).click();
|
||||
const camaRows = page.locator('table.worklist tbody tr');
|
||||
await expect(camaRows.first()).toContainText('BI-RADS');
|
||||
// the whole list and a record, each as its file
|
||||
for (const [button, file] of [
|
||||
['Exportar Excel', 'seguimiento-cama.xlsx'],
|
||||
['Exportar PDF', 'seguimiento-cama.pdf'],
|
||||
]) {
|
||||
const saved = page.waitForEvent('download');
|
||||
await page.getByRole('button', { name: button }).click();
|
||||
expect((await saved).suggestedFilename()).toBe(file);
|
||||
}
|
||||
await camaRows.first().locator('a').first().click();
|
||||
const record = page.waitForEvent('download');
|
||||
await page.getByRole('button', { name: 'Exportar PDF' }).click();
|
||||
expect((await record).suggestedFilename()).toBe('expediente-cama.pdf');
|
||||
await page.goto('/indicadores/tea');
|
||||
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
||||
expect(problems).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -101,12 +116,17 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
|
||||
await page.goto('/conectar');
|
||||
await page.getByText('cacu', { exact: true }).click();
|
||||
await expect(page.locator('vflow')).toBeVisible();
|
||||
await page.getByText('Fuente de datos · Patients').click();
|
||||
await expect(page.locator('formly-form')).toBeVisible(); // drawn by hand: its raw form
|
||||
// a node's caption: its kind, then its name
|
||||
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 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.
|
||||
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
|
||||
.poll(() =>
|
||||
@@ -139,13 +159,13 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
|
||||
}) => {
|
||||
const problems = watch(page);
|
||||
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' });
|
||||
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
|
||||
await version.getByRole('button', { name: 'Ver gráficas' }).click();
|
||||
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
|
||||
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([]);
|
||||
});
|
||||
|
||||
@@ -171,7 +191,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 page.getByLabel('Nombre de esta fuente').fill('Resultados');
|
||||
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.
|
||||
await page.getByRole('button', { name: 'Editar conexión' }).click();
|
||||
await page.locator('[data-field="password"]').fill('not-it');
|
||||
@@ -199,7 +219,8 @@ function captured(domain: string) {
|
||||
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
|
||||
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
|
||||
|
||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
// CaCu's (Phase 6) and CaMa's (Phase 7) pages are their own; TEA's follows the old one.
|
||||
for (const domain of ['tea']) {
|
||||
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
|
||||
page,
|
||||
}) => {
|
||||
@@ -228,6 +249,28 @@ for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Phase 7's Trazabilidad panels over the old tab's: an old title stands for these. */
|
||||
const PANELS: Record<string, Record<string, string[]>> = {
|
||||
cacu: {
|
||||
'Tiempo de tamizaje a diagnóstico': [
|
||||
'Tiempo de tamizaje a primer diagnóstico',
|
||||
'Tiempo de tamizaje a diagnóstico tras biopsia',
|
||||
],
|
||||
'Tiempo de diagnóstico a tratamiento': ['Tiempo de diagnóstico tras biopsia a tratamiento'],
|
||||
},
|
||||
cama: {
|
||||
'Días de la toma de la mastografía a su resultado': [
|
||||
'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
'Días de la toma de la mastografía a su resultado',
|
||||
],
|
||||
'Días de tamizaje a diagnóstico': [
|
||||
'Tiempo de tamizaje a diagnóstico',
|
||||
'Tasa de detección histopatológica',
|
||||
],
|
||||
'Tasa de confirmación histopatológica': ['Confirmación histopatológica'],
|
||||
},
|
||||
};
|
||||
|
||||
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
|
||||
page,
|
||||
@@ -246,7 +289,10 @@ for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
const headings = await tab
|
||||
.locator('h2, h3')
|
||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
|
||||
const now = PANELS[domain] ?? {};
|
||||
expect(headings).toEqual(
|
||||
old.filter((i) => i.kind !== 'plot').flatMap((i) => now[i.text] ?? [i.text]),
|
||||
);
|
||||
const drawn = await tab
|
||||
.locator('.js-plotly-plot')
|
||||
.evaluateAll((els) =>
|
||||
@@ -283,3 +329,57 @@ for (const domain of ['cacu', 'cama', 'tea']) {
|
||||
).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([]);
|
||||
});
|
||||
}
|
||||
|
||||
+837
-13
File diff suppressed because it is too large
Load Diff
Generated
+285
-2
@@ -25,9 +25,11 @@
|
||||
"d3-zoom": "3.0.0",
|
||||
"material-symbols": "0.48.3",
|
||||
"ngx-vflow": "2.7.0",
|
||||
"pdfmake": "0.3.14",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"tslib": "^2.3.0",
|
||||
"write-excel-file": "4.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.3.0",
|
||||
@@ -38,6 +40,7 @@
|
||||
"@types/d3-selection": "3.0.13",
|
||||
"@types/d3-zoom": "3.0.9",
|
||||
"@types/fhir": "0.0.44",
|
||||
"@types/pdfmake": "0.3.5",
|
||||
"@types/plotly.js": "3.0.15",
|
||||
"jsdom": "^31.0.0",
|
||||
"ng-openapi-gen": "^1.1.0",
|
||||
@@ -2402,6 +2405,30 @@
|
||||
"@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": {
|
||||
"version": "0.158.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
|
||||
@@ -3465,6 +3492,12 @@
|
||||
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
|
||||
"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": {
|
||||
"version": "0.10.5",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
|
||||
@@ -3570,6 +3603,37 @@
|
||||
"license": "MIT",
|
||||
"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": {
|
||||
"version": "3.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
|
||||
@@ -3816,6 +3880,15 @@
|
||||
"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": {
|
||||
"version": "2.11.39",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz",
|
||||
@@ -3891,6 +3964,35 @@
|
||||
"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": {
|
||||
"version": "4.29.6",
|
||||
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
|
||||
@@ -4119,6 +4221,15 @@
|
||||
"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": {
|
||||
"version": "0.7.1",
|
||||
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz",
|
||||
@@ -4326,6 +4437,12 @@
|
||||
"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": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
|
||||
@@ -4561,7 +4678,6 @@
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-string-truncated-width": {
|
||||
@@ -4626,6 +4742,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": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
|
||||
@@ -4636,6 +4758,23 @@
|
||||
"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": {
|
||||
"version": "11.4.1",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
|
||||
@@ -5366,6 +5505,16 @@
|
||||
"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": {
|
||||
"version": "11.4.1",
|
||||
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz",
|
||||
@@ -5844,6 +5993,12 @@
|
||||
"@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": {
|
||||
"version": "8.1.1",
|
||||
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
|
||||
@@ -5922,6 +6077,34 @@
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -5990,6 +6173,14 @@
|
||||
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
|
||||
"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": {
|
||||
"version": "8.5.33",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
|
||||
@@ -6165,6 +6356,12 @@
|
||||
"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": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz",
|
||||
@@ -6663,6 +6860,15 @@
|
||||
"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": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
@@ -6852,6 +7058,12 @@
|
||||
"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": {
|
||||
"version": "6.2.5",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
|
||||
@@ -6979,6 +7191,53 @@
|
||||
"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": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
@@ -7676,6 +7935,18 @@
|
||||
"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": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
@@ -7693,6 +7964,18 @@
|
||||
"dev": true,
|
||||
"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": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
|
||||
|
||||
+4
-1
@@ -29,9 +29,11 @@
|
||||
"d3-zoom": "3.0.0",
|
||||
"material-symbols": "0.48.3",
|
||||
"ngx-vflow": "2.7.0",
|
||||
"pdfmake": "0.3.14",
|
||||
"plotly.js-cartesian-dist-min": "4.1.2",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
"tslib": "^2.3.0",
|
||||
"write-excel-file": "4.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.3.0",
|
||||
@@ -42,6 +44,7 @@
|
||||
"@types/d3-selection": "3.0.13",
|
||||
"@types/d3-zoom": "3.0.9",
|
||||
"@types/fhir": "0.0.44",
|
||||
"@types/pdfmake": "0.3.5",
|
||||
"@types/plotly.js": "3.0.15",
|
||||
"jsdom": "^31.0.0",
|
||||
"ng-openapi-gen": "^1.1.0",
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/* 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 CacuEligibility$Params {
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* One CaCu scenario (default: every one)
|
||||
*/
|
||||
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('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 = '/cacu/fhir/Patient/{id}/$eligibility';
|
||||
@@ -0,0 +1,45 @@
|
||||
/* 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 CacuReferenceRisk$Params {
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* Only what was reported by this day
|
||||
*/
|
||||
cutoff?: (string | null);
|
||||
|
||||
/**
|
||||
* The cytology's sample day (default: her latest)
|
||||
*/
|
||||
sample?: (string | null);
|
||||
}
|
||||
|
||||
export function cacuReferenceRisk(http: HttpClient, rootUrl: string, params: CacuReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, cacuReferenceRisk.PATH, 'get');
|
||||
if (params) {
|
||||
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<{
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
cacuReferenceRisk.PATH = '/cacu/fhir/Patient/{id}/$reference-risk';
|
||||
@@ -0,0 +1,45 @@
|
||||
/* 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 CacuRiskSeries$Params {
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* Only what was reported by this day
|
||||
*/
|
||||
cutoff?: (string | null);
|
||||
|
||||
/**
|
||||
* The cytology's sample day (default: her latest)
|
||||
*/
|
||||
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('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 = '/cacu/fhir/Patient/{id}/$risk-series';
|
||||
@@ -0,0 +1,41 @@
|
||||
/* 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 EegSummary$Params {
|
||||
|
||||
/**
|
||||
* months
|
||||
*/
|
||||
'follow-up-window'?: (number | null);
|
||||
'follow-up-start'?: (string | null);
|
||||
'follow-up-cutoff'?: (string | null);
|
||||
}
|
||||
|
||||
export function eegSummary(http: HttpClient, rootUrl: string, params?: EegSummary$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, eegSummary.PATH, 'get');
|
||||
if (params) {
|
||||
rb.query('follow-up-window', params['follow-up-window'], {});
|
||||
rb.query('follow-up-start', params['follow-up-start'], {});
|
||||
rb.query('follow-up-cutoff', params['follow-up-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<{
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
eegSummary.PATH = '/tea/fhir/Patient/$eeg-summary';
|
||||
@@ -22,8 +22,28 @@ export interface SearchPatient$Params {
|
||||
* default: the last day with data
|
||||
*/
|
||||
'follow-up-cutoff'?: (string | null);
|
||||
|
||||
/**
|
||||
* the list from this day (in place of a window)
|
||||
*/
|
||||
'follow-up-start'?: (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>
|
||||
*/
|
||||
@@ -55,7 +75,11 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
|
||||
rb.query('_id', params['_id'], {});
|
||||
rb.query('follow-up-window', params['follow-up-window'], {});
|
||||
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
|
||||
rb.query('follow-up-start', params['follow-up-start'], {});
|
||||
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('risk-horizon', params['risk-horizon'], {});
|
||||
rb.query('_revinclude', params['_revinclude'], {});
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/* 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 { LanguageModel } from '../../models/language-model';
|
||||
|
||||
export interface LanguageModel$Params {
|
||||
}
|
||||
|
||||
export function languageModel(http: HttpClient, rootUrl: string, params?: LanguageModel$Params, context?: HttpContext): Observable<StrictHttpResponse<LanguageModel>> {
|
||||
const rb = new RequestBuilder(rootUrl, languageModel.PATH, 'get');
|
||||
if (params) {
|
||||
}
|
||||
|
||||
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<LanguageModel>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
languageModel.PATH = '/ingest/llm';
|
||||
@@ -0,0 +1,37 @@
|
||||
/* 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 StartDraft$Params {
|
||||
pipeline_id: string;
|
||||
run?: boolean;
|
||||
}
|
||||
|
||||
export function startDraft(http: HttpClient, rootUrl: string, params: StartDraft$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, startDraft.PATH, 'post');
|
||||
if (params) {
|
||||
rb.path('pipeline_id', params.pipeline_id, {});
|
||||
rb.query('run', params.run, {});
|
||||
}
|
||||
|
||||
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;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
startDraft.PATH = '/ingest/pipelines/{pipeline_id}/draft';
|
||||
@@ -8,12 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
|
||||
import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
import { Domain } from '../../models/domain';
|
||||
import { Model } from '../../models/model';
|
||||
|
||||
export interface Models$Params {
|
||||
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');
|
||||
if (params) {
|
||||
rb.path('domain', params.domain, {});
|
||||
@@ -24,7 +25,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
|
||||
).pipe(
|
||||
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||
map((r: HttpResponse<any>) => {
|
||||
return r as StrictHttpResponse<Array<string>>;
|
||||
return r as StrictHttpResponse<Array<Model>>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Conflicts$Params {
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
}
|
||||
|
||||
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
|
||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
||||
|
||||
|
||||
export interface Held$Params {
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
}
|
||||
|
||||
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/* 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 RebuildGold$Params {
|
||||
}
|
||||
|
||||
export function rebuildGold(http: HttpClient, rootUrl: string, params?: RebuildGold$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||
[key: string]: string;
|
||||
}>> {
|
||||
const rb = new RequestBuilder(rootUrl, rebuildGold.PATH, 'post');
|
||||
if (params) {
|
||||
}
|
||||
|
||||
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;
|
||||
}>;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
rebuildGold.PATH = '/runs/rebuild';
|
||||
@@ -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';
|
||||
+42
-26
@@ -5,6 +5,40 @@ export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth
|
||||
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
|
||||
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
|
||||
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
|
||||
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
|
||||
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
|
||||
export type { CacuReferenceRisk$Params as CacuReferenceRisk$Params } from './fn/fhir/cacu-reference-risk';
|
||||
export { cacuReferenceRisk as cacuReferenceRisk } from './fn/fhir/cacu-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 { EegSummary$Params as EegSummary$Params } from './fn/fhir/eeg-summary';
|
||||
export { eegSummary as eegSummary } from './fn/fhir/eeg-summary';
|
||||
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
|
||||
export { postBundle as postBundle } from './fn/fhir/post-bundle';
|
||||
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
|
||||
export { searchCondition as searchCondition } from './fn/fhir/search-condition';
|
||||
export type { SearchDiagnosticReport$Params as SearchDiagnosticReport$Params } from './fn/fhir/search-diagnostic-report';
|
||||
export { searchDiagnosticReport as searchDiagnosticReport } from './fn/fhir/search-diagnostic-report';
|
||||
export type { SearchEncounter$Params as SearchEncounter$Params } from './fn/fhir/search-encounter';
|
||||
export { searchEncounter as searchEncounter } from './fn/fhir/search-encounter';
|
||||
export type { SearchMeasure$Params as SearchMeasure$Params } from './fn/fhir/search-measure';
|
||||
export { searchMeasure as searchMeasure } from './fn/fhir/search-measure';
|
||||
export type { ReadMeasure$Params as ReadMeasure$Params } from './fn/fhir/read-measure';
|
||||
export { readMeasure as readMeasure } from './fn/fhir/read-measure';
|
||||
export type { SearchMeasureReport$Params as SearchMeasureReport$Params } from './fn/fhir/search-measure-report';
|
||||
export { searchMeasureReport as searchMeasureReport } from './fn/fhir/search-measure-report';
|
||||
export type { SearchObservation$Params as SearchObservation$Params } from './fn/fhir/search-observation';
|
||||
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
|
||||
export type { SearchPatient$Params as SearchPatient$Params } 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 { readPatient as readPatient } from './fn/fhir/read-patient';
|
||||
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
|
||||
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
|
||||
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
|
||||
export { searchRiskAssessment as searchRiskAssessment } from './fn/fhir/search-risk-assessment';
|
||||
export type { Metadata$Params as Metadata$Params } from './fn/fhir/metadata';
|
||||
export { metadata as metadata } from './fn/fhir/metadata';
|
||||
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
|
||||
export { domains as domains } from './fn/operations/domains';
|
||||
export type { Health$Params as Health$Params } from './fn/operations/health';
|
||||
@@ -15,12 +49,16 @@ export type { GetConceptMap$Params as GetConceptMap$Params } from './fn/ingest/g
|
||||
export { getConceptMap as getConceptMap } from './fn/ingest/get-concept-map';
|
||||
export type { SaveConceptMap$Params as SaveConceptMap$Params } from './fn/ingest/save-concept-map';
|
||||
export { saveConceptMap as saveConceptMap } from './fn/ingest/save-concept-map';
|
||||
export type { LanguageModel$Params as LanguageModel$Params } from './fn/ingest/language-model';
|
||||
export { languageModel as languageModel } from './fn/ingest/language-model';
|
||||
export type { Pipelines$Params as Pipelines$Params } from './fn/ingest/pipelines';
|
||||
export { pipelines as pipelines } from './fn/ingest/pipelines';
|
||||
export type { Pipeline$Params as Pipeline$Params } from './fn/ingest/pipeline';
|
||||
export { pipeline as pipeline } from './fn/ingest/pipeline';
|
||||
export type { SavePipeline$Params as SavePipeline$Params } from './fn/ingest/save-pipeline';
|
||||
export { savePipeline as savePipeline } from './fn/ingest/save-pipeline';
|
||||
export type { StartDraft$Params as StartDraft$Params } from './fn/ingest/start-draft';
|
||||
export { startDraft as startDraft } from './fn/ingest/start-draft';
|
||||
export type { NodeRows$Params as NodeRows$Params } from './fn/ingest/node-rows';
|
||||
export { nodeRows as nodeRows } from './fn/ingest/node-rows';
|
||||
export type { StartRun$Params as StartRun$Params } from './fn/ingest/start-run';
|
||||
@@ -73,8 +111,12 @@ export type { Reject$Params as Reject$Params } from './fn/review/reject';
|
||||
export { reject as reject } from './fn/review/reject';
|
||||
export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unrecognised';
|
||||
export { unrecognised as unrecognised } from './fn/review/unrecognised';
|
||||
export type { RebuildGold$Params as RebuildGold$Params } from './fn/runs/rebuild-gold';
|
||||
export { rebuildGold as rebuildGold } from './fn/runs/rebuild-gold';
|
||||
export type { RunStatus$Params as RunStatus$Params } 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 { studies as studies } from './fn/eeg/studies';
|
||||
export type { Study$Params as Study$Params } from './fn/eeg/study';
|
||||
@@ -91,29 +133,3 @@ export type { UsersDeleteUser$Params as UsersDeleteUser$Params } from './fn/user
|
||||
export { usersDeleteUser as usersDeleteUser } from './fn/users/users-delete-user';
|
||||
export type { UsersPatchUser$Params as UsersPatchUser$Params } from './fn/users/users-patch-user';
|
||||
export { usersPatchUser as usersPatchUser } from './fn/users/users-patch-user';
|
||||
export type { PostBundle$Params as PostBundle$Params } from './fn/fhir/post-bundle';
|
||||
export { postBundle as postBundle } from './fn/fhir/post-bundle';
|
||||
export type { SearchCondition$Params as SearchCondition$Params } from './fn/fhir/search-condition';
|
||||
export { searchCondition as searchCondition } from './fn/fhir/search-condition';
|
||||
export type { SearchDiagnosticReport$Params as SearchDiagnosticReport$Params } from './fn/fhir/search-diagnostic-report';
|
||||
export { searchDiagnosticReport as searchDiagnosticReport } from './fn/fhir/search-diagnostic-report';
|
||||
export type { SearchEncounter$Params as SearchEncounter$Params } from './fn/fhir/search-encounter';
|
||||
export { searchEncounter as searchEncounter } from './fn/fhir/search-encounter';
|
||||
export type { SearchMeasure$Params as SearchMeasure$Params } from './fn/fhir/search-measure';
|
||||
export { searchMeasure as searchMeasure } from './fn/fhir/search-measure';
|
||||
export type { ReadMeasure$Params as ReadMeasure$Params } from './fn/fhir/read-measure';
|
||||
export { readMeasure as readMeasure } from './fn/fhir/read-measure';
|
||||
export type { SearchMeasureReport$Params as SearchMeasureReport$Params } from './fn/fhir/search-measure-report';
|
||||
export { searchMeasureReport as searchMeasureReport } from './fn/fhir/search-measure-report';
|
||||
export type { SearchObservation$Params as SearchObservation$Params } from './fn/fhir/search-observation';
|
||||
export { searchObservation as searchObservation } from './fn/fhir/search-observation';
|
||||
export type { SearchPatient$Params as SearchPatient$Params } 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 { readPatient as readPatient } from './fn/fhir/read-patient';
|
||||
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
|
||||
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
|
||||
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
|
||||
export { searchRiskAssessment as searchRiskAssessment } from './fn/fhir/search-risk-assessment';
|
||||
export type { Metadata$Params as Metadata$Params } from './fn/fhir/metadata';
|
||||
export { metadata as metadata } from './fn/fhir/metadata';
|
||||
|
||||
@@ -19,11 +19,13 @@ export type { Group } from './models/group';
|
||||
export type { Guided } from './models/guided';
|
||||
export type { HttpValidationError } from './models/http-validation-error';
|
||||
export type { Join } from './models/join';
|
||||
export type { LanguageModel } from './models/language-model';
|
||||
export type { Link } from './models/link';
|
||||
export type { Listing } from './models/listing';
|
||||
export type { Login } from './models/login';
|
||||
export type { Map } from './models/map';
|
||||
export type { Metric } from './models/metric';
|
||||
export type { Model } from './models/model';
|
||||
export type { Option } from './models/option';
|
||||
export type { PersonDecision } from './models/person-decision';
|
||||
export type { Pipeline } from './models/pipeline';
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
|
||||
*/
|
||||
export interface Correction {
|
||||
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
field: string;
|
||||
record: string;
|
||||
value: string;
|
||||
|
||||
@@ -25,7 +25,7 @@ export interface Extract {
|
||||
/**
|
||||
* Qué estudio se saca del documento.
|
||||
*/
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
formats?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
|
||||
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
|
||||
export interface Fhir {
|
||||
column?: string;
|
||||
concept_map?: (string | null);
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'fhir';
|
||||
|
||||
@@ -11,5 +11,5 @@ export interface FieldSpec {
|
||||
placeholder?: string;
|
||||
provider?: (string | null);
|
||||
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';
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export interface Join {
|
||||
label?: string;
|
||||
|
||||
/**
|
||||
* Pares [columna izquierda, derecha].
|
||||
* Columna de la primera entrada = columna de la segunda.
|
||||
*/
|
||||
on: Array<[string, string]>;
|
||||
position?: (Position | null);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface LanguageModel {
|
||||
available: boolean;
|
||||
model: (string | null);
|
||||
reason: (string | null);
|
||||
vision: boolean;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/* eslint-disable */
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Model {
|
||||
name: string;
|
||||
title: string;
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||
|
||||
export interface Rejection {
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
reason: string;
|
||||
record: string;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface Relation {
|
||||
outcome_code: string;
|
||||
probability: number;
|
||||
q: (number | null);
|
||||
reason?: (string | null);
|
||||
reference_probability: number;
|
||||
z: number;
|
||||
zone: string;
|
||||
|
||||
@@ -12,7 +12,7 @@ export interface Target {
|
||||
/**
|
||||
* En qué estudio de la plataforma se guarda.
|
||||
*/
|
||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||
id: string;
|
||||
inputs?: Array<string>;
|
||||
kind?: 'target';
|
||||
|
||||
+5
-3
@@ -4,7 +4,9 @@
|
||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||
</a>
|
||||
@if (domain(); as current) {
|
||||
<span class="title">Plataforma de Indicadores</span>
|
||||
<span class="title">{{
|
||||
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
|
||||
}}</span>
|
||||
<button
|
||||
mat-flat-button
|
||||
class="domain"
|
||||
@@ -16,7 +18,7 @@
|
||||
</button>
|
||||
<mat-menu #menu="matMenu">
|
||||
@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>
|
||||
} @else {
|
||||
@@ -31,7 +33,7 @@
|
||||
</nav>
|
||||
@if (auth.user(); as u) {
|
||||
<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>
|
||||
<mat-menu #account="matMenu">
|
||||
<span class="who" mat-menu-item disabled>{{ u.email }}</span>
|
||||
|
||||
+38
-1
@@ -21,10 +21,22 @@
|
||||
|
||||
.title {
|
||||
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-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 {
|
||||
--mat-button-filled-container-color: var(--color-primary);
|
||||
--mat-button-filled-label-text-color: var(--color-text);
|
||||
@@ -67,10 +79,35 @@
|
||||
width: clamp(155px, 15vw, 185px);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
@media (max-width: 1100px) {
|
||||
.title {
|
||||
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 {
|
||||
|
||||
+5
-4
@@ -43,10 +43,11 @@ export class App {
|
||||
),
|
||||
{ initialValue: '' },
|
||||
);
|
||||
/** The domain of an indicator page, if this is one. */
|
||||
protected readonly domain = computed(
|
||||
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined,
|
||||
);
|
||||
/** The section and domain of a page that has one (indicators, governance): the switcher
|
||||
* moves between that section's domains. */
|
||||
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(() =>
|
||||
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
|
||||
);
|
||||
|
||||
@@ -36,6 +36,24 @@
|
||||
<span class="spacer"></span>
|
||||
<button mat-stroked-button (click)="save()">Guardar</button>
|
||||
<button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button>
|
||||
@if (onlySources()) {
|
||||
<span
|
||||
[matTooltip]="
|
||||
llm.value()?.available
|
||||
? 'El modelo de lenguaje del sitio arma toda la canalización a partir de estas fuentes y la ejecuta.'
|
||||
: 'No disponible: ' +
|
||||
(llm.value()?.reason ?? 'no hay modelo de lenguaje configurado')
|
||||
"
|
||||
>
|
||||
<button
|
||||
mat-flat-button
|
||||
(click)="automatic()"
|
||||
[disabled]="running() || !llm.value()?.available"
|
||||
>
|
||||
<mat-icon>auto_awesome</mat-icon>Armar automáticamente
|
||||
</button>
|
||||
</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@if (message()) {
|
||||
@@ -73,10 +91,6 @@
|
||||
</button>
|
||||
</div>
|
||||
<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) {
|
||||
<div class="inputs">
|
||||
Entradas:
|
||||
@@ -87,40 +101,71 @@
|
||||
}
|
||||
</div>
|
||||
} @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) {
|
||||
<div class="source-summary">
|
||||
<p>
|
||||
<mat-icon>check_circle</mat-icon>
|
||||
{{ d.label || d.id }}
|
||||
<mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
|
||||
<mat-tab label="Configuración">
|
||||
@if (d.kind === 'source') {
|
||||
@if (guided(d)) {
|
||||
<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>
|
||||
<button mat-flat-button (click)="connectSource(d.id)">
|
||||
<mat-icon>edit</mat-icon> Editar conexión
|
||||
<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-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>
|
||||
</div>
|
||||
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)">
|
||||
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" />
|
||||
}
|
||||
</mat-tab>
|
||||
</mat-tab-group>
|
||||
<button mat-stroked-button (click)="show()">Vista previa</button>
|
||||
@if (preview(); as rows) {
|
||||
<div class="preview">
|
||||
|
||||
@@ -140,3 +140,55 @@ h2 {
|
||||
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);
|
||||
}
|
||||
|
||||
+126
-23
@@ -1,5 +1,13 @@
|
||||
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 { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
@@ -7,7 +15,7 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatListModule } from '@angular/material/list';
|
||||
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 { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
|
||||
@@ -15,12 +23,14 @@ import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
|
||||
import { withFormlyMaterial } from '@ngx-formly/material';
|
||||
import { Connection, NodeChange, Vflow } from 'ngx-vflow';
|
||||
import { Api } from '../api/api';
|
||||
import { languageModel } from '../api/fn/ingest/language-model';
|
||||
import { nodeRows } from '../api/fn/ingest/node-rows';
|
||||
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
|
||||
import { pipelines } from '../api/fn/ingest/pipelines';
|
||||
import { savePipeline } from '../api/fn/ingest/save-pipeline';
|
||||
import { schema } from '../api/fn/ingest/schema';
|
||||
import { sourcePreview } from '../api/fn/ingest/source-preview';
|
||||
import { startDraft } from '../api/fn/ingest/start-draft';
|
||||
import { startRun } from '../api/fn/ingest/start-run';
|
||||
import { runStatus } from '../api/fn/runs/run-status';
|
||||
import type { Pipeline } from '../api/models/pipeline';
|
||||
@@ -57,21 +67,21 @@ export const KINDS: Record<Kind, string> = {
|
||||
read: 'Leer documentos',
|
||||
route: 'Separar por tipo',
|
||||
map: 'Traducir códigos',
|
||||
extract: 'Sacar datos',
|
||||
extract: 'Extraer datos',
|
||||
fhir: 'Leer FHIR',
|
||||
join: 'Juntar',
|
||||
join: 'Unir',
|
||||
link: 'Identificar a la persona',
|
||||
target: 'Guardar en la plataforma',
|
||||
};
|
||||
export const HELP: Record<Kind, string> = {
|
||||
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:
|
||||
'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.',
|
||||
extract: 'Toma 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.',
|
||||
join: 'Junta dos entradas que hablan de lo mismo; por ejemplo, un resultado con su orden.',
|
||||
extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
|
||||
fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
|
||||
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.',
|
||||
target: 'Guarda los estudios ya revisados en la plataforma.',
|
||||
};
|
||||
@@ -90,7 +100,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatListModule,
|
||||
MatSlideToggleModule,
|
||||
MatTabsModule,
|
||||
MatTableModule,
|
||||
MatTooltipModule,
|
||||
Vflow,
|
||||
@@ -107,10 +117,13 @@ export class Conectar {
|
||||
private readonly dialog = inject(MatDialog);
|
||||
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
|
||||
protected readonly help = HELP;
|
||||
/** The raw form of a source drawn with the dialog ("Avanzado"). */
|
||||
protected readonly advanced = signal(false);
|
||||
/** "Avanzado": the selected node as JSON, as edited and not applied yet. */
|
||||
protected readonly rawDraft = signal<string | undefined>(undefined);
|
||||
protected readonly rawError = signal('');
|
||||
|
||||
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
|
||||
/** The site's language model: Automático needs it. */
|
||||
protected readonly llm = resource({ loader: () => this.api.invoke(languageModel) });
|
||||
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
|
||||
|
||||
protected readonly pipelineId = signal<string | undefined>(undefined);
|
||||
@@ -127,11 +140,29 @@ export class Conectar {
|
||||
protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected()));
|
||||
protected readonly message = signal('');
|
||||
protected readonly run = signal<{ id: string; status: string } | undefined>(undefined);
|
||||
/** Automático drafts a pipeline that holds its sources only. */
|
||||
protected readonly onlySources = computed(
|
||||
() => this.docs().length > 0 && this.docs().every((d) => d.kind === 'source'),
|
||||
);
|
||||
protected readonly running = computed(() => {
|
||||
const run = this.run();
|
||||
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 model: Record<string, unknown> = {};
|
||||
/** The selected node's form, generated from its kind's JSON Schema. */
|
||||
@@ -264,7 +295,8 @@ export class Conectar {
|
||||
);
|
||||
this.form = new UntypedFormGroup({});
|
||||
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). */
|
||||
@@ -279,13 +311,46 @@ export class Conectar {
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
|
||||
);
|
||||
if (this.advanced()) delete values['guided']; // drawn by hand from here on
|
||||
this.update(
|
||||
id,
|
||||
(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 {
|
||||
const from = this.selected();
|
||||
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
|
||||
@@ -338,20 +403,44 @@ export class Conectar {
|
||||
const id = this.pipelineId();
|
||||
if (!id || !(await this.save())) return;
|
||||
try {
|
||||
const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
|
||||
this.run.set({ id: run_id, status: 'STARTING' });
|
||||
while (this.running()) {
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
this.run.set({
|
||||
id: run_id,
|
||||
status: (await this.api.invoke(runStatus, { run_id }))['status'],
|
||||
});
|
||||
await this.follow((await this.api.invoke(startRun, { pipeline_id: id, body: {} }))['run_id']);
|
||||
} catch (e) {
|
||||
this.message.set(problem(e));
|
||||
}
|
||||
}
|
||||
|
||||
/** "Armar automáticamente": saves the sources, starts the `draft` job (the site's model
|
||||
* draws the whole pipeline, saves it as a new version and runs it) and, once it ends,
|
||||
* shows the version drawn. */
|
||||
protected async automatic(): Promise<void> {
|
||||
const id = this.pipelineId();
|
||||
if (!id || !(await this.save())) return;
|
||||
try {
|
||||
this.message.set('Armando la canalización: se leen los documentos y el modelo los revisa.');
|
||||
await this.follow((await this.api.invoke(startDraft, { pipeline_id: id }))['run_id']);
|
||||
if (this.run()?.status === 'SUCCESS') {
|
||||
await this.open(id);
|
||||
this.message.set(
|
||||
`Versión ${this.version()} armada y ejecutada. Revise lo que queda en Revisión.`,
|
||||
);
|
||||
this.list.reload();
|
||||
}
|
||||
} catch (e) {
|
||||
this.message.set(problem(e));
|
||||
}
|
||||
}
|
||||
|
||||
private async follow(run_id: string): Promise<void> {
|
||||
this.run.set({ id: run_id, status: 'STARTING' });
|
||||
while (this.running()) {
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
this.run.set({
|
||||
id: run_id,
|
||||
status: (await this.api.invoke(runStatus, { run_id }))['status'],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** What the node gives: a source's first rows, or what any other node gave in the last run. */
|
||||
protected async show(): Promise<void> {
|
||||
const doc = this.doc();
|
||||
@@ -363,7 +452,7 @@ export class Conectar {
|
||||
? 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 });
|
||||
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) {
|
||||
this.message.set(problem(e));
|
||||
}
|
||||
@@ -389,7 +478,14 @@ export class Conectar {
|
||||
}
|
||||
|
||||
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. */
|
||||
@@ -416,3 +512,10 @@ function problem(e: unknown): string {
|
||||
}
|
||||
return String(e);
|
||||
}
|
||||
|
||||
function escape(text: string): string {
|
||||
return text.replace(
|
||||
/[&<>"']/g,
|
||||
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ const PIPELINE = {
|
||||
when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
|
||||
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
|
||||
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;
|
||||
|
||||
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']);
|
||||
});
|
||||
|
||||
@@ -34,7 +40,13 @@ describe('node forms from the pipeline schema', () => {
|
||||
expect(schema.properties.resource.type).toBe('string');
|
||||
});
|
||||
|
||||
it('edits maps as JSON', () => {
|
||||
expect(schema.properties.values.widget.formlyConfig.type).toBe('json');
|
||||
it('edits maps of texts and pairs as rows', () => {
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ 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';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import {
|
||||
ConfigOption,
|
||||
@@ -27,11 +28,29 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
|
||||
)!;
|
||||
const node = structuredClone(defs[name]);
|
||||
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;
|
||||
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 {
|
||||
if (schema.$ref) {
|
||||
const { $ref, ...rest } = schema;
|
||||
@@ -45,6 +64,34 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
|
||||
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 isTuple =
|
||||
schema.type === 'array' &&
|
||||
@@ -117,7 +164,7 @@ export class ArrayType extends FieldArrayType {}
|
||||
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
|
||||
template: `
|
||||
<mat-form-field appearance="outline" class="json">
|
||||
<mat-label>{{ props.label }} (JSON)</mat-label>
|
||||
<mat-label>{{ props.label }}</mat-label>
|
||||
<textarea
|
||||
matInput
|
||||
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 = {
|
||||
types: [
|
||||
{ name: 'object', component: ObjectType },
|
||||
{ name: 'array', component: ArrayType },
|
||||
{ name: 'json', component: JsonType },
|
||||
{ name: 'map', component: MapType },
|
||||
{ name: 'pairs', component: PairsType },
|
||||
{ name: 'enum', extends: 'select' },
|
||||
{ name: 'string', extends: 'input' },
|
||||
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
|
||||
|
||||
@@ -128,6 +128,25 @@
|
||||
}
|
||||
</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') {
|
||||
<div class="picker">
|
||||
<mat-form-field appearance="outline" class="grow">
|
||||
@@ -319,7 +338,7 @@
|
||||
</p>
|
||||
@if (t.detail) {
|
||||
<details>
|
||||
<summary>Lo que respondió el sistema</summary>
|
||||
<summary>Respuesta de la fuente</summary>
|
||||
<pre>{{ t.detail }}</pre>
|
||||
</details>
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface SourceDialogData {
|
||||
guided?: Guided | null;
|
||||
label?: string;
|
||||
}
|
||||
const NONE: string[] = [];
|
||||
|
||||
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
|
||||
export interface SourceDialogResult {
|
||||
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. */
|
||||
protected tables(): string[] {
|
||||
return this.tableList();
|
||||
|
||||
+10
-3
@@ -3,8 +3,7 @@ import type { Figure } from './plot';
|
||||
/** The EEG metrics (models.tea.eeg.biomarkers.CODES), as the pages name them. */
|
||||
export const METRIC_NAMES: Record<string, string> = {
|
||||
posterior_rhythm: 'Ritmo posterior (Hz)',
|
||||
spindles_n2: 'Husos de sueño N2 (por min)',
|
||||
spindles_n3: 'Husos de sueño N3 (por min)',
|
||||
spindles: 'Husos de sueño NREM (por min)',
|
||||
paroxysmal_spikes: 'Picos paroxísticos (por min)',
|
||||
anteroposterior_gradient: 'Gradiente anteroposterior',
|
||||
};
|
||||
@@ -26,7 +25,7 @@ export const ZONE_NAMES: Record<string, string> = {
|
||||
/** The association's biomarkers (core.tea.association.BIOMARKERS). */
|
||||
export const BIOMARKER_NAMES: Record<string, string> = {
|
||||
spikes: 'Picos paroxísticos',
|
||||
spindles: 'Husos de sueño N2',
|
||||
spindles: 'Husos de sueño NREM',
|
||||
posterior_rhythm: 'Ritmo posterior',
|
||||
gradient: 'Gradiente anteroposterior',
|
||||
};
|
||||
@@ -134,3 +133,11 @@ export function byDeviation(zones: Site[]): Site[] {
|
||||
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',
|
||||
};
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
@@ -2,37 +2,44 @@ import type { Figure } from '../plot';
|
||||
import { PALETTE } from '../plot';
|
||||
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
|
||||
|
||||
/** A curve with its band, as the reports give them. */
|
||||
/** A curve with its band, as the reports give them; a value may be absent (null). */
|
||||
interface Band {
|
||||
x: number[];
|
||||
y: number[];
|
||||
y: (number | null)[];
|
||||
low?: (number | null)[];
|
||||
high?: (number | null)[];
|
||||
}
|
||||
|
||||
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
||||
const lines: Partial<Plotly.Data>[] = [];
|
||||
if (b.low && b.high) {
|
||||
lines.push({
|
||||
x: [...b.x, ...[...b.x].reverse()],
|
||||
y: [...b.high, ...[...b.low].reverse()] as number[],
|
||||
fill: 'toself',
|
||||
fillcolor: `${colour}33`,
|
||||
line: { width: 0 },
|
||||
hoverinfo: 'skip',
|
||||
showlegend: false,
|
||||
type: 'scatter',
|
||||
});
|
||||
}
|
||||
lines.push({
|
||||
x: b.x,
|
||||
y: b.y,
|
||||
name,
|
||||
type: 'scatter',
|
||||
mode: 'lines',
|
||||
line: { color: colour, dash },
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
/** The value or a gap: an absent value is not drawn (zero is a value). */
|
||||
const orGap = (ys: (number | null)[]) => ys.map((v) => (finite(v) ? v : null)) as number[];
|
||||
|
||||
/** The runs of consecutive indices where both limits are known: the band is drawn there only
|
||||
* (an absent limit is no zero). */
|
||||
function runs(b: Band): number[][] {
|
||||
const found: number[][] = [[]];
|
||||
b.x.forEach((x, i) => {
|
||||
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) found.at(-1)!.push(i);
|
||||
else if (found.at(-1)!.length) found.push([]);
|
||||
});
|
||||
return lines;
|
||||
return found.filter((r) => r.length > 1);
|
||||
}
|
||||
|
||||
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
||||
const bands = runs(b).map((run) => ({
|
||||
x: [...run, ...[...run].reverse()].map((i) => b.x[i]),
|
||||
y: [...run.map((i) => b.high![i]), ...[...run].reverse().map((i) => b.low![i])] as number[],
|
||||
fill: 'toself' as const,
|
||||
fillcolor: `${colour}33`,
|
||||
line: { width: 0 },
|
||||
hoverinfo: 'skip' as const,
|
||||
showlegend: false,
|
||||
type: 'scatter' as const,
|
||||
}));
|
||||
return [
|
||||
...bands,
|
||||
{ x: b.x, y: orGap(b.y), name, type: 'scatter', mode: 'lines', line: { color: colour, dash } },
|
||||
];
|
||||
}
|
||||
|
||||
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's
|
||||
@@ -286,27 +293,38 @@ export function scenarioFigure(
|
||||
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
|
||||
],
|
||||
layout: {
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' } },
|
||||
yaxis: { title: { text: yTitle } },
|
||||
// One label per month with every curve's survival there, as percentages.
|
||||
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 point without both limits has no bar, and none has: no bars. */
|
||||
function points(
|
||||
name: string,
|
||||
x: number[],
|
||||
p: { S: number[]; low: number[]; high: number[] },
|
||||
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
|
||||
): Partial<Plotly.Data> {
|
||||
const bars = p.S.map((v, i) => {
|
||||
const [low, high] = [p.low?.[i], p.high?.[i]];
|
||||
return finite(v) && finite(low) && finite(high) ? [high - v, v - low] : null;
|
||||
});
|
||||
return {
|
||||
x,
|
||||
y: p.S,
|
||||
error_y: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
array: p.high.map((h, i) => h - p.S[i]),
|
||||
arrayminus: p.S.map((v, i) => v - p.low[i]),
|
||||
},
|
||||
y: orGap(p.S),
|
||||
...(bars.some((e) => e)
|
||||
? {
|
||||
error_y: {
|
||||
type: 'data' as const,
|
||||
symmetric: false,
|
||||
array: bars.map((e) => e?.[0] ?? null) as number[],
|
||||
arrayminus: bars.map((e) => e?.[1] ?? null) as number[],
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
name,
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
<section class="page">
|
||||
<h1>Gobernanza de modelos</h1>
|
||||
<nav class="domains" aria-label="Dominios">
|
||||
@for (d of domains.value() ?? []; track d) {
|
||||
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
|
||||
}
|
||||
</nav>
|
||||
<h1>{{ labels[domain()] ?? domain() }}</h1>
|
||||
<p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
|
||||
|
||||
<form class="card actions" (submit)="$event.preventDefault()">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
@@ -17,13 +13,44 @@
|
||||
name="asOf"
|
||||
/>
|
||||
</mat-form-field>
|
||||
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button>
|
||||
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button>
|
||||
@if (domain() === 'tea') {
|
||||
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button>
|
||||
@if (confirming(); as c) {
|
||||
<span class="confirm" role="alert">
|
||||
{{
|
||||
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) {
|
||||
<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>
|
||||
@if (message()) {
|
||||
@@ -33,17 +60,19 @@
|
||||
@if (models.isLoading()) {
|
||||
<app-loading what="los modelos" />
|
||||
} @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) {
|
||||
<div class="card model">
|
||||
<h2>{{ m.name }}</h2>
|
||||
<h2>
|
||||
{{ m.title }} <code class="muted code">{{ m.name }}</code>
|
||||
</h2>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Versión</th>
|
||||
<th>Creada</th>
|
||||
<th>Entrenamiento / prueba</th>
|
||||
<th>Datos</th>
|
||||
<th>Informes</th>
|
||||
<th>Validación clínica</th>
|
||||
<th></th>
|
||||
@@ -59,32 +88,37 @@
|
||||
}
|
||||
</td>
|
||||
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
|
||||
<td class="num">
|
||||
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
|
||||
</td>
|
||||
<td class="nowrap">{{ sizes(v) }}</td>
|
||||
<td>
|
||||
@for (r of v.reports; track r) {
|
||||
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
|
||||
reportNames[r] ?? r
|
||||
}}</a>
|
||||
}
|
||||
@if (v.reports.includes('interpretability')) {
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
(click)="chosen.set({ name: m.name, version: v.version })"
|
||||
>
|
||||
Ver gráficas
|
||||
</button>
|
||||
}
|
||||
<div class="reports">
|
||||
@for (r of v.reports; track r) {
|
||||
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
|
||||
reportNames[r] ?? r
|
||||
}}</a>
|
||||
}
|
||||
@if (v.reports.includes('interpretability')) {
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
(click)="chosen.set({ name: m.name, version: v.version })"
|
||||
>
|
||||
Ver gráficas
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
@if (!v.reports.includes('clinical_validation')) {
|
||||
<input
|
||||
#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)"
|
||||
/>
|
||||
<button mat-stroked-button type="button" (click)="file.click()">
|
||||
Subir validación clínica
|
||||
</button>
|
||||
} @else {
|
||||
Agregada
|
||||
}
|
||||
@@ -105,7 +139,7 @@
|
||||
|
||||
@if (chosen(); as c) {
|
||||
<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) {
|
||||
<h3>{{ f.title }}</h3>
|
||||
<app-plot [figure]="f.figure" [height]="360" />
|
||||
|
||||
@@ -1,18 +1,8 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
h1 {
|
||||
text-align: center;
|
||||
}
|
||||
.domains {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: var(--space-4);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
.domains a.active {
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
.subtitle {
|
||||
margin: 4px 0 var(--space-4);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
@@ -30,6 +20,7 @@ h1 {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge {
|
||||
white-space: nowrap;
|
||||
margin-left: var(--space-2);
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
@@ -45,3 +36,32 @@ td a {
|
||||
padding: 48px 0;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { Api } from '../api/api';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
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 { train } from '../api/fn/models/train';
|
||||
import { versions } from '../api/fn/models/versions';
|
||||
import { domains } from '../api/fn/operations/domains';
|
||||
import { studies } from '../api/fn/eeg/studies';
|
||||
import { study } from '../api/fn/eeg/study';
|
||||
import { terminateRun } from '../api/fn/runs/terminate-run';
|
||||
import { runStatus } from '../api/fn/runs/run-status';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import type { Version } from '../api/models/version';
|
||||
@@ -47,7 +46,6 @@ const REPORTS: Record<string, string> = {
|
||||
MatButtonModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
RouterLink,
|
||||
Plot,
|
||||
],
|
||||
templateUrl: './gobernanza.html',
|
||||
@@ -60,15 +58,15 @@ export class Gobernanza {
|
||||
|
||||
protected readonly labels = DOMAINS as Record<string, string>;
|
||||
protected readonly reportNames = REPORTS;
|
||||
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||
private readonly refreshed = signal(0);
|
||||
protected readonly models = resource({
|
||||
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
|
||||
loader: async ({ params: { domain } }) => {
|
||||
const names = await this.api.invoke(models, { domain });
|
||||
const found = await this.api.invoke(models, { domain });
|
||||
return Promise.all(
|
||||
names.map(async (name) => ({
|
||||
found.map(async ({ name, title }) => ({
|
||||
name,
|
||||
title,
|
||||
versions: await this.api.invoke(versions, { domain, name }),
|
||||
})),
|
||||
);
|
||||
@@ -96,7 +94,41 @@ export class Gobernanza {
|
||||
});
|
||||
protected readonly metricNames = METRIC_NAMES;
|
||||
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 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.
|
||||
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);
|
||||
}
|
||||
|
||||
protected async promote(name: string, version: number): Promise<void> {
|
||||
try {
|
||||
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);
|
||||
} catch (e) {
|
||||
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> {
|
||||
for (;;) {
|
||||
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;
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
}
|
||||
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> {
|
||||
this.confirming.set(undefined);
|
||||
const domain = this.domain() as Domain;
|
||||
const { run_id } =
|
||||
kind === 'train'
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { bars, Mode } from './bars';
|
||||
import { Reading } from './measures';
|
||||
|
||||
const read = (r: Reading) => () => r;
|
||||
const cells = (mode: Mode, r: Reading) => bars(mode, read(r))!.rows.map((x) => x.cells);
|
||||
|
||||
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' }];
|
||||
expect(cells({ kind: 'counts', label: 'x', measure: 'M', catalog }, r)).toEqual([
|
||||
['3', '75.0 %'],
|
||||
['1', '25.0 %'],
|
||||
]);
|
||||
});
|
||||
it('add up an aggregate after the first row and indent its parts', () => {
|
||||
const r: Reading = {
|
||||
populations: {},
|
||||
strata: {
|
||||
category: {
|
||||
n: { 'initial-population': 6 },
|
||||
a: { 'initial-population': 3 },
|
||||
b: { 'initial-population': 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
const catalog = ['n', 'a', 'b'].map((code) => ({ code, label: code, color: '#000' }));
|
||||
const aggregate = { label: 'Anormal', color: '#f00', codes: ['a', 'b'] };
|
||||
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, aggregate }, read(r))!;
|
||||
expect(t.rows.map((x) => [x.label, x.cells[0], !!x.sub])).toEqual([
|
||||
['n', '6', false],
|
||||
['Anormal', '4', false],
|
||||
['a', '3', true],
|
||||
['b', '1', true],
|
||||
]);
|
||||
});
|
||||
it('draw a proportion with its interval as marks', () => {
|
||||
const r: Reading = {
|
||||
populations: { numerator: 51, denominator: 70 },
|
||||
strata: {},
|
||||
score: 0.729,
|
||||
low: 0.615,
|
||||
high: 0.819,
|
||||
};
|
||||
const t = bars({ kind: 'ratio', label: 'Total', measure: 'M' }, read(r))!;
|
||||
expect(t.rows[0].cells).toEqual(['51/70', '72.9 %', '61.5 %–81.9 %']);
|
||||
expect(t.rows[0].marks.map(Math.round)).toEqual([62, 82]);
|
||||
});
|
||||
it('stagger steps from where the step they follow ends', () => {
|
||||
const at: Record<string, Reading> = {
|
||||
A: { populations: { 'measure-observation': 3 }, strata: {}, score: 10 },
|
||||
B: { populations: { 'measure-observation': 2 }, strata: {}, score: 30 },
|
||||
C: { populations: { 'measure-observation': 1 }, strata: {}, score: 20 },
|
||||
};
|
||||
const steps = [
|
||||
{ label: 'a', measure: 'A' },
|
||||
{ label: 'b', measure: 'B' },
|
||||
{ label: 'c', measure: 'C', after: 0 },
|
||||
{ label: 'd', measure: 'D' },
|
||||
];
|
||||
const mode: Mode = { kind: 'days', label: 'x', steps, staggered: true, scale: true };
|
||||
const t = bars(mode, (m) => at[m])!;
|
||||
expect(t.rows.map((x) => x.offset)).toEqual([0, 25, 25, undefined]);
|
||||
expect(t.rows[3].none).toBe('Sin mediciones en el periodo');
|
||||
expect(t.note).toBe('Escala: 0 a 40 días.');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { name } from './labels';
|
||||
import { Reading } from './measures';
|
||||
import { NEUTRAL_DARK } from './palette-cacu';
|
||||
|
||||
/** A category as drawn: its code in the report, its name and its colour. */
|
||||
export type Category = { code: string; label: string; color: string };
|
||||
/** A colour by code (the category decides it, never its place in the report). */
|
||||
export type Colors = Record<string, string>;
|
||||
/** Categories a card leaves out of its rows: their records stay in its total and its shares. */
|
||||
export type Hidden = { codes: string[]; unit: string };
|
||||
/** A row adding up some categories, drawn after the first one; those are indented under it. */
|
||||
export type Aggregate = { label: string; color: string; codes: string[] };
|
||||
/** A step of a route; staggered, it starts where step `after` (by default, the previous) ends. */
|
||||
export type Step = { label: string; measure: string; after?: number };
|
||||
export type Read = (measure: string) => Reading | undefined;
|
||||
|
||||
/** One way of reading a card: the bars of a table, or groups of bars (`grouped`). */
|
||||
export type Mode = {
|
||||
label: string;
|
||||
caption?: string;
|
||||
/** said above the table: what its rows count */
|
||||
heading?: string;
|
||||
/** the header of the rows' names */
|
||||
rowsLabel?: string;
|
||||
} & (
|
||||
| {
|
||||
kind: 'counts';
|
||||
measure: string;
|
||||
catalog: Category[];
|
||||
aggregate?: Aggregate;
|
||||
unit?: string;
|
||||
percentLabel?: string;
|
||||
hidden?: Hidden;
|
||||
/** every bar on 0 to 100 % of the total, its length the share shown */
|
||||
percent?: boolean;
|
||||
}
|
||||
| {
|
||||
/** a proportion by group; `complete`: every group of `order`, those left out as zero
|
||||
* when the listed ones add up to every patient (see `reconciles`) */
|
||||
kind: 'shares';
|
||||
measure: string;
|
||||
stratum: string;
|
||||
order: string[];
|
||||
complete?: boolean;
|
||||
colors?: Colors;
|
||||
percentLabel?: string;
|
||||
}
|
||||
| {
|
||||
/** per group (`<stratum>-category` cells), an independent bar per category */
|
||||
kind: 'grouped';
|
||||
measure: string;
|
||||
catalog: Category[];
|
||||
aggregate?: Aggregate;
|
||||
stratum: string;
|
||||
order: string[];
|
||||
unit: string;
|
||||
complete?: boolean;
|
||||
/** a group's denominator is all its records, not only its categories' */
|
||||
ofAll?: boolean;
|
||||
hidden?: Hidden;
|
||||
}
|
||||
| { kind: 'days'; steps: Step[]; tint?: Tint; staggered?: boolean; scale?: boolean }
|
||||
/** a proportion as one bar of 0 to 100 %, its 95 % interval the two marks */
|
||||
| { kind: 'ratio'; measure: string; color?: string; percentLabel?: string }
|
||||
/** a proportion as its two parts, what counted and what did not */
|
||||
| {
|
||||
kind: 'split';
|
||||
measure: string;
|
||||
yes: string;
|
||||
no: string;
|
||||
colors: [string, string];
|
||||
unit: string;
|
||||
percentLabel: string;
|
||||
}
|
||||
/** each row's units by result, in segments, and the malignant share of those with a grade
|
||||
* (read from `malignancy`); the results are the period's, then `results` */
|
||||
| {
|
||||
kind: 'outcomes';
|
||||
measure: string;
|
||||
stratum: string;
|
||||
rows: Category[];
|
||||
results: Category[];
|
||||
malignant: string[];
|
||||
malignancy: string;
|
||||
}
|
||||
);
|
||||
export type Tint = { bar: string; mark: string };
|
||||
|
||||
/** One bar: its start, length and marks in % of the scale, and its cells of text. */
|
||||
export interface Bar {
|
||||
label: string;
|
||||
/** indented under the aggregate above it */
|
||||
sub?: boolean;
|
||||
/** why the row has no figures */
|
||||
hint?: string;
|
||||
color?: string;
|
||||
offset?: number;
|
||||
width: number;
|
||||
marks: number[];
|
||||
cells: string[];
|
||||
/** the bar in parts, each with what it says when hovered */
|
||||
segments?: { width: number; color: string; title: string }[];
|
||||
/** said in place of the bar */
|
||||
none?: string;
|
||||
}
|
||||
export interface Bars {
|
||||
head: string[];
|
||||
rows: Bar[];
|
||||
markColor?: string;
|
||||
/** what the reader must know to take the rows right */
|
||||
note?: string;
|
||||
legend?: { label: string; color: string }[];
|
||||
}
|
||||
|
||||
export const NOT_AVAILABLE = 'No disponible';
|
||||
export const NO_PATIENTS = 'Sin pacientes en el periodo';
|
||||
export const NO_ROUND =
|
||||
'Ninguna paciente del periodo tiene clasificación de detección inicial o anterior: los ' +
|
||||
'grupos en cero reflejan información no registrada, no ausencia de pacientes.';
|
||||
|
||||
export const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
|
||||
export const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
|
||||
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
|
||||
export const whole = (n: unknown): n is number =>
|
||||
typeof n === 'number' && Number.isInteger(n) && n >= 0;
|
||||
|
||||
/** The patients of a reading: its cohort, or a proportion's denominator. */
|
||||
export const patients = (r?: Reading) =>
|
||||
r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
|
||||
|
||||
/** A group the report leaves out is zero only when the listed groups add up to every record
|
||||
* (the report omits empty groups); otherwise it is not available. */
|
||||
export const reconciles = (listed: number[], total: number) =>
|
||||
listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
|
||||
|
||||
/** What a card says of the categories it does not draw, when the period has any. */
|
||||
export function hiddenNote(mode: Mode, read: Read): string | undefined {
|
||||
if (!('hidden' in mode) || !mode.hidden) return undefined;
|
||||
const cells = read(mode.measure)?.strata['category'] ?? {};
|
||||
const found = mode.hidden.codes.filter((c) => size(cells[c]));
|
||||
const n = found.reduce((t, c) => t + size(cells[c]), 0);
|
||||
if (!n) return undefined;
|
||||
const [unit, words] =
|
||||
n === 1
|
||||
? [mode.hidden.unit.replace(/s$/, ''), 'no se muestra desglosado; está incluido']
|
||||
: [mode.hidden.unit, 'no se muestran desglosados; están incluidos'];
|
||||
return `${n} ${unit} (${found.map(name).join(', ')}) ${words} en el total y en los porcentajes.`;
|
||||
}
|
||||
|
||||
/** Rows with an aggregate's row after the first, its parts marked by `sub`. */
|
||||
export function withAggregate<T>(
|
||||
rows: T[],
|
||||
codes: string[],
|
||||
aggregate: Aggregate | undefined,
|
||||
sum: () => T,
|
||||
sub: (row: T) => T,
|
||||
): T[] {
|
||||
if (!aggregate || !rows.length) return rows;
|
||||
const marked = rows.map((row, i) => (aggregate.codes.includes(codes[i]) ? sub(row) : row));
|
||||
return [marked[0], sum(), ...marked.slice(1)];
|
||||
}
|
||||
|
||||
/** The bars of a mode; none when the period has nothing to draw. */
|
||||
export function bars(mode: Mode, read: Read): Bars | undefined {
|
||||
switch (mode.kind) {
|
||||
case 'counts':
|
||||
return counts(mode, read);
|
||||
case 'ratio': {
|
||||
const r = read(mode.measure);
|
||||
const { numerator: n = 0, denominator: total = 0 } = r?.populations ?? {};
|
||||
if (r?.score === undefined || !total) return undefined;
|
||||
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
|
||||
const cells = [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'];
|
||||
return {
|
||||
head: ['n/N', mode.percentLabel ?? 'Porcentaje', 'IC 95 %'],
|
||||
rows: [
|
||||
{
|
||||
label: 'Total',
|
||||
color: mode.color,
|
||||
width: 100 * r.score,
|
||||
cells,
|
||||
marks: ends.map((v) => 100 * v),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
case 'split': {
|
||||
const { numerator: n = 0, denominator: total = 0 } = read(mode.measure)?.populations ?? {};
|
||||
if (!total) return undefined;
|
||||
return {
|
||||
head: [mode.unit, mode.percentLabel],
|
||||
rows: (
|
||||
[
|
||||
[mode.yes, n],
|
||||
[mode.no, total - n],
|
||||
] as const
|
||||
).map(([label, k], i) => ({
|
||||
label,
|
||||
color: mode.colors[i],
|
||||
width: (100 * k) / total,
|
||||
marks: [],
|
||||
cells: [`${k}`, pct(k, total)],
|
||||
})),
|
||||
};
|
||||
}
|
||||
case 'days':
|
||||
return medians(mode, read);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function counts(mode: Extract<Mode, { kind: 'counts' }>, read: Read): Bars | undefined {
|
||||
const cells = read(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 all = [
|
||||
...mode.catalog.filter((c) => !hidden.includes(c.code)),
|
||||
...Object.keys(cells)
|
||||
.filter((c) => !named.includes(c) && !hidden.includes(c))
|
||||
.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
|
||||
];
|
||||
const scale = mode.percent ? total : Math.max(...Object.values(cells).map(size));
|
||||
const row = (label: string, n: number, color?: string): Bar => ({
|
||||
label,
|
||||
color,
|
||||
width: (100 * n) / scale,
|
||||
marks: [],
|
||||
cells: [`${n}`, pct(n, total)],
|
||||
});
|
||||
const a = mode.aggregate;
|
||||
const summed = () =>
|
||||
row(
|
||||
a!.label,
|
||||
a!.codes.reduce((t, c) => t + size(cells[c]), 0),
|
||||
a!.color,
|
||||
);
|
||||
return {
|
||||
head: [mode.unit ?? 'n', mode.percentLabel ?? 'Porcentaje'],
|
||||
rows: withAggregate(
|
||||
all.map((c) => row(c.label, size(cells[c.code]), c.color)),
|
||||
all.map((c) => c.code),
|
||||
a,
|
||||
summed,
|
||||
(r) => ({ ...r, sub: true }),
|
||||
),
|
||||
note: hiddenNote(mode, read),
|
||||
};
|
||||
}
|
||||
|
||||
/** Median days per step, with their quartiles; staggered, each from where its step ends. */
|
||||
function medians(mode: Extract<Mode, { kind: 'days' }>, read: Read): Bars | undefined {
|
||||
const found = mode.steps.map((s) => read(s.measure));
|
||||
if (!found.some((r) => r?.score !== undefined)) return undefined;
|
||||
const starts: number[] = [];
|
||||
mode.steps.forEach(({ after }, i) => {
|
||||
const j = after ?? i - 1;
|
||||
starts.push(mode.staggered && j >= 0 ? starts[j] + (found[j]?.score ?? 0) : 0);
|
||||
});
|
||||
const top =
|
||||
Math.max(...found.map((r, i) => starts[i] + Math.max(r?.score ?? 0, r?.high ?? 0))) || 1;
|
||||
const at = (v: number) => (100 * v) / top;
|
||||
return {
|
||||
head: ['Mediana', 'Observaciones', 'Q1–Q3'],
|
||||
markColor: mode.tint?.mark,
|
||||
note: mode.scale ? `Escala: 0 a ${days(top)} días.` : undefined,
|
||||
rows: mode.steps.map(({ label }, i) => {
|
||||
const r = found[i];
|
||||
const n = `${r?.populations['measure-observation'] ?? 0}`;
|
||||
if (r?.score === undefined)
|
||||
return {
|
||||
label,
|
||||
width: 0,
|
||||
marks: [],
|
||||
none: 'Sin mediciones en el periodo',
|
||||
cells: ['—', n, '—'],
|
||||
};
|
||||
const spread = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
|
||||
return {
|
||||
label,
|
||||
color: mode.tint?.bar,
|
||||
offset: mode.staggered ? at(starts[i]) : undefined,
|
||||
width: at(r.score),
|
||||
marks: spread.map((v) => at(starts[i] + v)),
|
||||
cells: [`${days(r.score)} días`, n, spread.map(days).join('–') || '—'],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { type Figure, PALETTE } from '../plot';
|
||||
import { name, type Reading } from './measures';
|
||||
import type { Catalog, Category, HistoryPanel } from './pages';
|
||||
import { name } from './labels';
|
||||
import { type Reading } from './measures';
|
||||
import type { HistoryPanel } from './history';
|
||||
import type { Catalog, Category } from './pages';
|
||||
|
||||
const OLIVE = '#A8C243';
|
||||
const ROSE = '#C24269';
|
||||
@@ -12,114 +14,11 @@ function rgba(hex: string, alpha: number): string {
|
||||
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). */
|
||||
function counted(r: Reading, code: string): number {
|
||||
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
|
||||
}
|
||||
|
||||
/** Groups inside, their categories outside, the total in the centre. */
|
||||
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
|
||||
const values = catalog.categories.map((c) => counted(r, c.code));
|
||||
const total = values.reduce((a, b) => a + b, 0);
|
||||
const groups = catalog.groups.map((g) =>
|
||||
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
|
||||
);
|
||||
const faded = new Set(catalog.faded ?? []);
|
||||
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
|
||||
const common = {
|
||||
type: 'pie',
|
||||
sort: false,
|
||||
direction: 'clockwise',
|
||||
rotation: 0,
|
||||
showlegend: false,
|
||||
textinfo: 'text',
|
||||
textposition: 'inside',
|
||||
insidetextorientation: 'horizontal',
|
||||
};
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
...common,
|
||||
name: 'centro',
|
||||
values: [1],
|
||||
labels: ['centro'],
|
||||
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
|
||||
text: [`<b>${count(total)}</b><br>${center}`],
|
||||
marker: { colors: ['#FFFFFF'] },
|
||||
hoverinfo: 'skip',
|
||||
},
|
||||
{
|
||||
...common,
|
||||
name: 'grupos',
|
||||
values: groups,
|
||||
labels: catalog.groups.map((g) => g.label),
|
||||
hole: 0.62,
|
||||
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
|
||||
text: groups.map((n, i) =>
|
||||
total && n / total >= 0.05 ? `${catalog.groups[i].label}<br>${share(n)}` : '',
|
||||
),
|
||||
marker: {
|
||||
colors: catalog.groups.map((g) =>
|
||||
rgba(
|
||||
g.color,
|
||||
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
|
||||
),
|
||||
),
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
},
|
||||
{
|
||||
...common,
|
||||
name: 'categorias',
|
||||
values,
|
||||
labels: catalog.categories.map((c) => c.label),
|
||||
hole: 0.74,
|
||||
domain: { x: [0, 1], y: [0, 1] },
|
||||
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
|
||||
marker: {
|
||||
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
},
|
||||
] as Partial<Plotly.Data>[],
|
||||
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
|
||||
};
|
||||
}
|
||||
|
||||
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
|
||||
export function scenarioBars(
|
||||
r: Reading,
|
||||
@@ -150,7 +49,8 @@ export function scenarioBars(
|
||||
xaxis: {
|
||||
title: { text: '% de pacientes del escenario con resultado' },
|
||||
ticksuffix: ' %',
|
||||
range: [0, 100],
|
||||
range: [0, 100.5],
|
||||
dtick: 20,
|
||||
},
|
||||
yaxis: {
|
||||
type: 'category',
|
||||
@@ -159,87 +59,6 @@ export function scenarioBars(
|
||||
categoryarray: y,
|
||||
automargin: true,
|
||||
},
|
||||
legend: { orientation: 'h', y: -0.25 },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Wilson score interval at 95 %, in percent. */
|
||||
export function wilson(k: number, n: number): [number, number] {
|
||||
const z = 1.959963984540054;
|
||||
const p = k / n;
|
||||
const d = 1 + (z * z) / n;
|
||||
const c = (p + (z * z) / (2 * n)) / d;
|
||||
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
|
||||
return [100 * (c - h), 100 * (c + h)];
|
||||
}
|
||||
|
||||
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
|
||||
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
|
||||
export function rateDots(
|
||||
r: Reading,
|
||||
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
|
||||
): Figure {
|
||||
const cells = r.strata[`${spec.stratum}-category`] ?? {};
|
||||
const rows = spec.rows.map((row) => {
|
||||
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
|
||||
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
|
||||
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
|
||||
const k = biopsied
|
||||
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
|
||||
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
|
||||
const rate = den ? (100 * k) / den : null;
|
||||
const [low, high] = den ? wilson(k, den) : [null, null];
|
||||
return { row, k, den, rate, low, high };
|
||||
});
|
||||
const y = rows.map((x) => x.row.label);
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
name: 'tasas',
|
||||
y,
|
||||
x: rows.map((x) => x.rate),
|
||||
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
|
||||
cliponaxis: false,
|
||||
error_x: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
color: ROSE,
|
||||
thickness: 2,
|
||||
width: 6,
|
||||
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
|
||||
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
|
||||
},
|
||||
hovertemplate: '%{y}: %{x:.1f} %<extra></extra>',
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
margin: { t: 24, r: 110, b: 56, l: 56 },
|
||||
yaxis: {
|
||||
type: 'category',
|
||||
categoryorder: 'array',
|
||||
categoryarray: [...y].reverse(),
|
||||
automargin: true,
|
||||
},
|
||||
xaxis: { range: [0, 100], ticksuffix: ' %', zeroline: false, title: { text: spec.axis } },
|
||||
annotations: rows.map((x) => ({
|
||||
x: 1,
|
||||
xref: 'paper',
|
||||
xanchor: 'left',
|
||||
xshift: 8,
|
||||
y: x.row.label,
|
||||
yref: 'y',
|
||||
showarrow: false,
|
||||
align: 'left',
|
||||
text: x.den
|
||||
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
|
||||
: spec.colored
|
||||
? 'Sin pacientes'
|
||||
: 'Sin biopsias',
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -305,9 +124,9 @@ export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure
|
||||
line: { color: '#FFFFFF', width: 2 },
|
||||
},
|
||||
// an empty slice says nothing (its label would sit on its neighbours')
|
||||
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
|
||||
texttemplate: values.map((v) => (v ? `%{label}<br>%{percent} del total de ${center}` : '')),
|
||||
textposition: 'outside',
|
||||
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
||||
hovertemplate: `%{label}<br>%{value} (%{percent} del total de ${center})<extra></extra>`,
|
||||
} as Partial<Plotly.Data>,
|
||||
],
|
||||
layout: {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { Sheet } from '../export';
|
||||
import { STATES } from '../paciente/stages';
|
||||
import type { CamaRow, Row } from './follow-up';
|
||||
import { name } from './labels';
|
||||
|
||||
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';
|
||||
}
|
||||
|
||||
/** CaMa's follow-up list as a table to save: what the page shows, a missing value said so. */
|
||||
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: [
|
||||
'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',
|
||||
],
|
||||
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,
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
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}`,
|
||||
]),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
|
||||
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,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
|
||||
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. */
|
||||
export interface Row {
|
||||
@@ -8,6 +9,8 @@ export interface Row {
|
||||
curp?: string;
|
||||
status: string;
|
||||
ageGroup: string;
|
||||
age?: number;
|
||||
stages: Stage[];
|
||||
cytology?: { date: string; result?: string; adequacy?: string };
|
||||
hpv?: { date: string; positive: boolean; types1618?: boolean };
|
||||
daysToDiagnosis?: number;
|
||||
@@ -24,15 +27,36 @@ const AGE_GROUPS: [number, number][] = [
|
||||
[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(
|
||||
birth: string | undefined,
|
||||
at: string,
|
||||
groups: [number, number][] = AGE_GROUPS,
|
||||
): string {
|
||||
if (!birth) return 'Sin dato';
|
||||
const [by, bm, bd] = birth.split('-').map(Number);
|
||||
const [y, m, d] = at.split('-').map(Number);
|
||||
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
|
||||
const age = ageAt(birth, at);
|
||||
if (age === undefined) return 'Sin dato';
|
||||
const found = groups.find(([lo, hi]) => lo <= age && age <= hi);
|
||||
if (found) return `${found[0]}-${found[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,
|
||||
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
|
||||
ageGroup: ageGroup(patient.birthDate, cutoff),
|
||||
age: ageAt(patient.birthDate, cutoff),
|
||||
stages: route(last, cutoff),
|
||||
cytology: last && {
|
||||
date: last.effectiveDateTime!,
|
||||
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
|
||||
@@ -146,11 +172,12 @@ export interface CamaRow {
|
||||
status: string;
|
||||
priority: 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 };
|
||||
}
|
||||
|
||||
const CAMA_AGE_GROUPS: [number, number][] = [
|
||||
export const CAMA_AGE_GROUPS: [number, number][] = [
|
||||
[40, 49],
|
||||
[50, 59],
|
||||
[60, 69],
|
||||
@@ -196,6 +223,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
|
||||
birads: mammogram
|
||||
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
|
||||
: undefined,
|
||||
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
|
||||
},
|
||||
biopsy: biopsy && {
|
||||
date: reported(biopsy)!,
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { Mode, NO_PATIENTS, NOT_AVAILABLE } from './bars';
|
||||
import { grouped, outcomes, shares, unavailable } from './groups';
|
||||
import { Reading } from './measures';
|
||||
|
||||
const read = (r: Reading) => () => r;
|
||||
const cell = (n: number) => ({ 'initial-population': n });
|
||||
const catalog = [
|
||||
{ code: 'NILM', label: 'Normal', color: '#0f0' },
|
||||
{ code: 'HSIL', label: 'LIEAG', color: '#f00' },
|
||||
];
|
||||
|
||||
describe('shares', () => {
|
||||
const mode: Mode = {
|
||||
kind: 'shares',
|
||||
label: 'Ronda',
|
||||
measure: 'M',
|
||||
stratum: 'round',
|
||||
order: ['initial', 'subsequent', 'no_data'],
|
||||
complete: true,
|
||||
};
|
||||
it('a group with no patients has no rate', () => {
|
||||
const r: Reading = {
|
||||
populations: { denominator: 0 },
|
||||
strata: { round: { initial: { numerator: 0, denominator: 0 } } },
|
||||
};
|
||||
const plain = { ...mode, complete: false } as Mode;
|
||||
expect(shares(plain, read(r))!.rows[0].cells).toEqual(['0/0', '—']);
|
||||
});
|
||||
it('draw a group left out as zero only when the listed ones add up', () => {
|
||||
const listed = { initial: { numerator: 1, denominator: 4 } };
|
||||
const whole = shares(
|
||||
mode,
|
||||
read({ populations: { denominator: 4 }, strata: { round: listed } }),
|
||||
)!;
|
||||
expect(whole.rows[1]).toMatchObject({ hint: NO_PATIENTS, cells: ['0/0', '—'] });
|
||||
const short = shares(
|
||||
mode,
|
||||
read({ populations: { denominator: 5 }, strata: { round: listed } }),
|
||||
)!;
|
||||
expect(short.rows[1]).toMatchObject({ hint: NOT_AVAILABLE, cells: ['—', '—'] });
|
||||
expect(short.note).toContain('no concilian');
|
||||
});
|
||||
it('say when the report does not break the period down', () => {
|
||||
const r: Reading = { populations: { denominator: 4 }, strata: {} };
|
||||
expect(unavailable(mode, read(r))).toContain('no publica el desglose «Ronda»');
|
||||
});
|
||||
});
|
||||
|
||||
describe('grouped', () => {
|
||||
const mode: Mode = {
|
||||
kind: 'grouped',
|
||||
label: 'Por ronda',
|
||||
measure: 'CACU_EU7',
|
||||
catalog,
|
||||
stratum: 'round',
|
||||
order: ['initial', 'subsequent', 'no_data'],
|
||||
unit: 'pacientes',
|
||||
complete: true,
|
||||
ofAll: true,
|
||||
};
|
||||
it('split the subsequent round by the last screening, each group over its own', () => {
|
||||
const r: Reading = {
|
||||
populations: { 'initial-population': 5 },
|
||||
strata: {
|
||||
'round-category': {
|
||||
'initial|NILM': cell(1),
|
||||
'subsequent|NILM': cell(2),
|
||||
'subsequent|HSIL': cell(2),
|
||||
},
|
||||
'subsequent_history-category': {
|
||||
'within_1_year|NILM': cell(2),
|
||||
'2_years|HSIL': cell(1),
|
||||
'3_or_more_years|HSIL': cell(1),
|
||||
},
|
||||
},
|
||||
};
|
||||
const g = grouped(mode, read(r))!;
|
||||
expect(g.groups.map((x) => [x.code, x.total])).toEqual([
|
||||
['initial', 1],
|
||||
['within_1_year', 2],
|
||||
['2_years', 1],
|
||||
['3_or_more_years', 1],
|
||||
['no_data', 0],
|
||||
]);
|
||||
expect(g.groups[1].label).toBe('Detección anterior hace un año o menos');
|
||||
expect(g.groups[2].rows.map((x) => x.text)).toEqual(['0/1 · 0.0 %', '1/1 · 100.0 %']);
|
||||
expect(g.groups[4].hint).toBe('Sin pacientes en el grupo');
|
||||
});
|
||||
it('name the youngest results group from 15', () => {
|
||||
const r: Reading = {
|
||||
populations: { 'initial-population': 1 },
|
||||
strata: { 'age_group-category': { '<25|NILM': cell(1) } },
|
||||
};
|
||||
const byAge = { ...mode, stratum: 'age_group', order: ['<25'] } as Mode;
|
||||
expect(grouped(byAge, read(r))!.groups[0].label).toBe('15-24');
|
||||
});
|
||||
});
|
||||
|
||||
describe('outcomes', () => {
|
||||
it('segment each row by result and give the malignant share of the graded', () => {
|
||||
const types: Reading = {
|
||||
populations: {},
|
||||
strata: {
|
||||
category: { '8500/3': cell(1), no_biopsy: cell(1) },
|
||||
birads: { '5': cell(2), '4A': cell(0) },
|
||||
'birads-category': { '5|8500/3': cell(1), '5|no_biopsy': cell(1) },
|
||||
},
|
||||
};
|
||||
const grades: Reading = {
|
||||
populations: {},
|
||||
strata: { 'birads-category': { '5|invasive': cell(1), '5|no_biopsy': cell(1) } },
|
||||
};
|
||||
const mode: Mode = {
|
||||
kind: 'outcomes',
|
||||
label: 'x',
|
||||
measure: 'T',
|
||||
stratum: 'birads',
|
||||
rows: [
|
||||
{ code: '5', label: 'BI-RADS 5', color: '' },
|
||||
{ code: '4A', label: 'BI-RADS 4A', color: '' },
|
||||
],
|
||||
results: [{ code: 'no_biopsy', label: 'Sin biopsia', color: '#ccc' }],
|
||||
malignant: ['in_situ', 'invasive'],
|
||||
malignancy: 'G',
|
||||
};
|
||||
const t = outcomes(mode, (m) => (m === 'T' ? types : grades))!;
|
||||
expect(t.head).toEqual([
|
||||
'Pacientes',
|
||||
'Carcinoma ductal infiltrante',
|
||||
'Sin biopsia',
|
||||
'% maligno',
|
||||
]);
|
||||
expect(t.rows[0].cells).toEqual(['2', '1', '1', '1/1 (100.0 %)']);
|
||||
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import {
|
||||
Bar,
|
||||
Bars,
|
||||
hiddenNote,
|
||||
Mode,
|
||||
NO_PATIENTS,
|
||||
NO_ROUND,
|
||||
NOT_AVAILABLE,
|
||||
patients,
|
||||
pct,
|
||||
Read,
|
||||
reconciles,
|
||||
size,
|
||||
whole,
|
||||
withAggregate,
|
||||
} from './bars';
|
||||
import { name } from './labels';
|
||||
|
||||
/** One category of a group as a bar of 0 to 100 %: its records over the group's. */
|
||||
export interface GroupRow {
|
||||
label: string;
|
||||
color: string;
|
||||
sub?: boolean;
|
||||
/** none when the group has no records */
|
||||
percent?: number;
|
||||
/** "2/5 · 40.0 %" */
|
||||
text: string;
|
||||
}
|
||||
export interface Group {
|
||||
code: string;
|
||||
label: string;
|
||||
total: number;
|
||||
hint?: string;
|
||||
rows: GroupRow[];
|
||||
}
|
||||
|
||||
/** The subsequent round, split by the form's last screening, drawn in place of that group. */
|
||||
const LAST_SCREENING: Record<string, string> = {
|
||||
within_1_year: 'Detección anterior hace un año o menos',
|
||||
'2_years': 'Detección anterior hace dos años',
|
||||
'3_or_more_years': 'Detección anterior hace tres años o más',
|
||||
};
|
||||
/** Results counted from 15 years old: their youngest group starts there. */
|
||||
const FROM_15 = ['CACU_EU7', 'CACU_VPH_GENOTIPO'];
|
||||
|
||||
const cellsOf = (strata: Record<string, Record<string, number>>, group: string) =>
|
||||
Object.entries(strata)
|
||||
.filter(([k]) => k.split('|')[0] === group)
|
||||
.map(([k, c]) => [k.split('|')[1], size(c)] as const);
|
||||
|
||||
/** The groups of a `grouped` mode, each with a bar per category over its own records. A group
|
||||
* the report leaves out is drawn empty only when the listed ones add up (`complete`). */
|
||||
export function grouped(mode: Mode, read: Read): { groups: Group[]; note?: string } | undefined {
|
||||
if (mode.kind !== 'grouped') return undefined;
|
||||
const r = read(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 history = (mode.stratum === 'round' && r?.strata['subsequent_history-category']) || {};
|
||||
const split = Object.keys(history).length > 0;
|
||||
const reconciled = reconciles(Object.values(cells).map(size), patients(r));
|
||||
const codes = [
|
||||
...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
|
||||
...found.filter((g) => !mode.order.includes(g)),
|
||||
].flatMap((g) => (split && g === 'subsequent' ? Object.keys(LAST_SCREENING) : [g]));
|
||||
const count = (g: string) => cellsOf(g in LAST_SCREENING ? history : cells, g);
|
||||
const n = (g: string, code: string) =>
|
||||
count(g).reduce((t, [c, k]) => (c === code ? t + k : t), 0);
|
||||
const total = (g: string) =>
|
||||
mode.ofAll
|
||||
? count(g).reduce((t, [, k]) => t + k, 0)
|
||||
: mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
|
||||
const row = (label: string, color: string, k: number, of: number): GroupRow => {
|
||||
const percent = of ? (100 * k) / of : undefined;
|
||||
return { label, color, percent, text: `${k}/${of} · ${of ? pct(k, of) : '—'}` };
|
||||
};
|
||||
const groups = codes.map((code): Group => {
|
||||
const of = total(code);
|
||||
const a = mode.aggregate;
|
||||
return {
|
||||
code,
|
||||
label:
|
||||
LAST_SCREENING[code] ??
|
||||
(code === '<25' && mode.stratum === 'age_group' && FROM_15.includes(mode.measure)
|
||||
? '15-24'
|
||||
: name(code)),
|
||||
total: of,
|
||||
hint: of ? undefined : `Sin ${mode.unit} en el grupo`,
|
||||
rows: withAggregate(
|
||||
mode.catalog.map((c) => row(c.label, c.color, n(code, c.code), of)),
|
||||
mode.catalog.map((c) => c.code),
|
||||
a,
|
||||
() =>
|
||||
row(
|
||||
a!.label,
|
||||
a!.color,
|
||||
a!.codes.reduce((t, c) => t + n(code, c), 0),
|
||||
of,
|
||||
),
|
||||
(x) => ({ ...x, sub: true }),
|
||||
),
|
||||
};
|
||||
});
|
||||
const unrounded =
|
||||
mode.complete &&
|
||||
reconciled &&
|
||||
total('no_data') > 0 &&
|
||||
groups.every((g) => g.code === 'no_data' || !g.total);
|
||||
const sentence =
|
||||
mode.complete && !reconciled
|
||||
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se ' +
|
||||
'muestran como cero.'
|
||||
: unrounded
|
||||
? NO_ROUND
|
||||
: undefined;
|
||||
const note = [sentence, hiddenNote(mode, read)].filter(Boolean).join(' ') || undefined;
|
||||
return { groups, note };
|
||||
}
|
||||
|
||||
/** Why a grouped mode has nothing to draw though its period has records. */
|
||||
export function unavailable(mode: Mode, read: Read): string | undefined {
|
||||
if (mode.kind !== 'grouped' && !(mode.kind === 'shares' && mode.complete)) return undefined;
|
||||
const r = read(mode.measure);
|
||||
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
|
||||
if (!patients(r) || Object.keys(r?.strata[key] ?? {}).length) return undefined;
|
||||
return `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
|
||||
}
|
||||
|
||||
const RESULT_COLORS = ['#5C42C2', '#C24269', '#9C42C2', '#A8C243', '#2778B8', '#B19525'];
|
||||
const GRADES = ['benign', 'in_situ', 'invasive'];
|
||||
|
||||
/** Each row's units by result, as one bar in segments, and the malignant share. */
|
||||
export function outcomes(mode: Mode, read: Read): Bars | undefined {
|
||||
if (mode.kind !== 'outcomes') return undefined;
|
||||
const r = read(mode.measure);
|
||||
const units = r?.strata[mode.stratum] ?? {};
|
||||
if (!Object.keys(units).length) return undefined;
|
||||
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
|
||||
const fixed = mode.results.map((x) => x.code);
|
||||
const results = [
|
||||
...Object.keys(r?.strata['category'] ?? {})
|
||||
.filter((code) => !fixed.includes(code))
|
||||
.sort()
|
||||
.map((code, i) => ({ code, label: name(code), color: RESULT_COLORS[i % 6] })),
|
||||
...mode.results,
|
||||
];
|
||||
const graded = read(mode.malignancy)?.strata[`${mode.stratum}-category`];
|
||||
const of = (row: string, codes: string[]) =>
|
||||
codes.reduce((t, c) => t + size(graded?.[`${row}|${c}`]), 0);
|
||||
const malignant = (row: string) => {
|
||||
if (!graded) return NOT_AVAILABLE;
|
||||
const [bad, known] = [of(row, mode.malignant), of(row, GRADES)];
|
||||
if (known) return `${bad}/${known} (${pct(bad, known)})`;
|
||||
return size(graded[`${row}|no_data`]) ? 'Sin biopsias clasificables' : 'Sin biopsias';
|
||||
};
|
||||
return {
|
||||
head: ['Pacientes', ...results.map((x) => x.label), '% maligno'],
|
||||
legend: results.map(({ label, color }) => ({ label, color })),
|
||||
rows: mode.rows.map(({ code, label }) => {
|
||||
const n = size(units[code]);
|
||||
const by = results.map((x) => size(cells[`${code}|${x.code}`]));
|
||||
return {
|
||||
label,
|
||||
width: 100,
|
||||
marks: [],
|
||||
hint: n ? undefined : 'Sin pacientes en el periodo',
|
||||
segments: results.map((x, i) => ({
|
||||
width: n ? (100 * by[i]) / n : 0,
|
||||
color: x.color,
|
||||
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
|
||||
})),
|
||||
cells: n ? [`${n}`, ...by.map(String), malignant(code)] : ['0', ...by.map(() => '—'), '—'],
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** A proportion by group; complete, every group of the order, as the counts allow. */
|
||||
export function shares(mode: Mode, read: Read): Bars | undefined {
|
||||
if (mode.kind !== 'shares') return undefined;
|
||||
const r = read(mode.measure);
|
||||
const cells = r?.strata[mode.stratum] ?? {};
|
||||
const listed = Object.keys(cells);
|
||||
const head = ['n/N', mode.percentLabel ?? 'Porcentaje'];
|
||||
const of = (code: string): Bar => {
|
||||
const [n, total] = [cells[code]?.['numerator'], cells[code]?.['denominator']];
|
||||
const label = name(code);
|
||||
const color = mode.colors?.[code];
|
||||
if (!whole(n) || !whole(total) || n > total)
|
||||
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
|
||||
return {
|
||||
label,
|
||||
color,
|
||||
hint: total ? undefined : NO_PATIENTS,
|
||||
marks: [],
|
||||
width: total ? (100 * n) / total : 0,
|
||||
cells: [`${n}/${total}`, pct(n, total)],
|
||||
};
|
||||
};
|
||||
if (!mode.complete) {
|
||||
const found = mode.order.filter((c) => cells[c]);
|
||||
return found.length ? { head, rows: found.map(of) } : undefined;
|
||||
}
|
||||
if (!patients(r) || !listed.length) return undefined;
|
||||
const reconciled = reconciles(
|
||||
listed.map((c) => cells[c]['denominator']),
|
||||
patients(r),
|
||||
);
|
||||
const rows = [...mode.order, ...listed.filter((c) => !mode.order.includes(c))].map((code) =>
|
||||
listed.includes(code)
|
||||
? of(code)
|
||||
: {
|
||||
label: name(code),
|
||||
color: mode.colors?.[code],
|
||||
width: 0,
|
||||
marks: [],
|
||||
...(reconciled
|
||||
? { hint: NO_PATIENTS, cells: ['0/0', '—'] }
|
||||
: { hint: NOT_AVAILABLE, cells: ['—', '—'] }),
|
||||
},
|
||||
);
|
||||
const classified = mode.order.filter((c) => c !== 'no_data' && listed.includes(c));
|
||||
const none = classified.every((c) => !cells[c]['denominator']) && listed.includes('no_data');
|
||||
const note = !reconciled
|
||||
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no ' +
|
||||
'se muestran como cero.'
|
||||
: none
|
||||
? NO_ROUND
|
||||
: undefined;
|
||||
return { head, rows, note };
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
|
||||
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
|
||||
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
|
||||
export interface HistoryPanel {
|
||||
title: string;
|
||||
measure: string;
|
||||
kind: 'stack' | 'percent' | 'median';
|
||||
/** stack: the categories, in the old order, with their names and colours */
|
||||
series?: { code: string; label: string; color: string }[];
|
||||
/** stack: the y axis */
|
||||
axis?: string;
|
||||
group?: string;
|
||||
}
|
||||
export interface History {
|
||||
panels: HistoryPanel[];
|
||||
/** the line's colour (percent and median) */
|
||||
line: string;
|
||||
/** how many of the latest months the tab opens with (none: from the first with data) */
|
||||
months?: number;
|
||||
}
|
||||
|
||||
const GREY = '#C9CDD2';
|
||||
const stack = (
|
||||
title: string,
|
||||
measure: string,
|
||||
axis: string,
|
||||
series: [string, string, string][],
|
||||
): HistoryPanel => ({
|
||||
title,
|
||||
measure,
|
||||
kind: 'stack',
|
||||
axis,
|
||||
series: series.map(([code, label, color]) => ({ code, label, color })),
|
||||
});
|
||||
const BIRADS_SERIES: [string, string, string][] = [
|
||||
['4A', 'BI-RADS 4A', '#C24269'],
|
||||
['4B', 'BI-RADS 4B', '#9C42C2'],
|
||||
['4C', 'BI-RADS 4C', '#5C42C2'],
|
||||
['5', 'BI-RADS 5', '#C2429C'],
|
||||
['6', 'BI-RADS 6', '#8E2F62'],
|
||||
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
|
||||
];
|
||||
|
||||
export const HISTORY: Record<string, History> = {
|
||||
cacu: {
|
||||
line: '#6A8000',
|
||||
months: 5,
|
||||
panels: [
|
||||
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
|
||||
['NILM', 'Normal', '#9DBFE3'],
|
||||
['ASC-US', 'ASC-US', '#2F6DB3'],
|
||||
['LSIL', 'LIEBG', '#9C42C2'],
|
||||
['ASC-H', 'ASC-H', '#5C42C2'],
|
||||
['HSIL', 'LIEAG', '#C2429C'],
|
||||
['CIS', 'Carcinoma in situ', '#8E2F62'],
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
|
||||
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
|
||||
stack(
|
||||
'Resultado de biopsia tras citología de alto grado',
|
||||
'CACU_CONFIRMACION_CITOLOGIA',
|
||||
'Pacientes',
|
||||
[
|
||||
['normal', 'Normal', '#9DBFE3'],
|
||||
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
|
||||
['CIN2', 'CIN 2', '#E07A9C'],
|
||||
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
|
||||
['CIN3', 'CIN 3', '#A8325A'],
|
||||
['CIS', 'Carcinoma in situ', '#9C42C2'],
|
||||
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
|
||||
['no_biopsy', 'Sin biopsia aún', GREY],
|
||||
['no_data', 'Biopsia sin grado', GREY],
|
||||
],
|
||||
),
|
||||
{
|
||||
title: 'Días de la toma de la citología a su resultado',
|
||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a primer diagnóstico',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a tratamiento',
|
||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Riesgo CIN2+ por banda',
|
||||
measure: 'CACU_RIESGO_BANDA',
|
||||
kind: 'stack',
|
||||
axis: 'Pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
cama: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{
|
||||
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de la toma de la mastografía a su resultado',
|
||||
measure: 'CAMA_EU38A',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días del resultado de la mastografía al diagnóstico',
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tasa de detección histopatológica',
|
||||
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
|
||||
kind: 'percent',
|
||||
},
|
||||
stack(
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_MASTOGRAFIA',
|
||||
'Mastografías',
|
||||
BIRADS_SERIES,
|
||||
),
|
||||
stack(
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_PACIENTE',
|
||||
'Pacientes',
|
||||
BIRADS_SERIES,
|
||||
),
|
||||
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
|
||||
['benign', 'Benigno', '#9DBFE3'],
|
||||
['in_situ', 'Carcinoma in situ', '#C24269'],
|
||||
['invasive', 'Carcinoma invasor', '#9C42C2'],
|
||||
['no_biopsy', 'Sin biopsia reportada', GREY],
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{
|
||||
title: 'Confirmación histopatológica',
|
||||
measure: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
kind: 'percent',
|
||||
},
|
||||
],
|
||||
},
|
||||
tea: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de M-CHAT a ADOS-2',
|
||||
measure: 'M26_DIAS_MCHAT_ADOS2',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de ADOS-2 a diagnóstico',
|
||||
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de M-CHAT a diagnóstico positivo',
|
||||
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
|
||||
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
|
||||
['in_process', 'En proceso', '#B8433A'],
|
||||
]),
|
||||
{
|
||||
title: 'Porcentaje de confirmación diagnóstica',
|
||||
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
|
||||
kind: 'percent',
|
||||
},
|
||||
{
|
||||
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
|
||||
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
|
||||
kind: 'percent',
|
||||
},
|
||||
{
|
||||
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
|
||||
kind: 'percent',
|
||||
},
|
||||
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
|
||||
['mchat_only', 'Solo M-CHAT', '#B8433A'],
|
||||
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
|
||||
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
|
||||
['eeg', 'Con EEG', '#A8C243'],
|
||||
]),
|
||||
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
|
||||
['good', 'Bueno', '#A8C243'],
|
||||
['bad', 'No aceptable', '#B8433A'],
|
||||
['not_analyzed', 'Sin analizar', GREY],
|
||||
]),
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -36,7 +36,7 @@ import { Loading } from '../loading';
|
||||
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
|
||||
} @else {
|
||||
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
|
||||
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
|
||||
<mat-tab label="Indicadores">
|
||||
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
|
||||
</mat-tab>
|
||||
<mat-tab label="Trazabilidad">
|
||||
@@ -45,7 +45,7 @@ import { Loading } from '../loading';
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
@if (domain() === 'cacu') {
|
||||
<mat-tab label="Análisis de riesgos">
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-riesgos [domain]="domain()" />
|
||||
</ng-template>
|
||||
@@ -57,7 +57,7 @@ import { Loading } from '../loading';
|
||||
</ng-template>
|
||||
</mat-tab>
|
||||
} @else if (domain() === 'cama') {
|
||||
<mat-tab label="Análisis de riesgos">
|
||||
<mat-tab label="Análisis de Riesgo">
|
||||
<ng-template matTabContent>
|
||||
<app-tab-seguimiento [domain]="domain()" />
|
||||
</ng-template>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/** Codes as the screens name them. */
|
||||
export const LABELS: Record<string, string> = {
|
||||
NILM: 'Normal (NILM)',
|
||||
LSIL: 'LIEBG',
|
||||
HSIL: 'LIEAG',
|
||||
CIN2: 'CIN 2',
|
||||
CIN3: 'CIN 3',
|
||||
normal: 'Normal',
|
||||
carcinoma: 'Carcinoma',
|
||||
no_data: 'Sin dato',
|
||||
'<25': '<25 años (sin límite inferior)',
|
||||
no_biopsy: 'Sin biopsia',
|
||||
pre_colposcopy: 'Pre colposcopia',
|
||||
post_colposcopy: 'Post colposcopia',
|
||||
post_treatment: 'Post tratamiento',
|
||||
case: 'Caso (cáncer)',
|
||||
low: 'Bajo',
|
||||
intermediate: 'Intermedio',
|
||||
high: 'Alto',
|
||||
satisfactory: 'satisfactoria',
|
||||
unsatisfactory: 'insatisfactoria',
|
||||
benign: 'Benigno',
|
||||
in_situ: 'Carcinoma in situ',
|
||||
invasive: 'Carcinoma invasor',
|
||||
cancer: 'Diagnóstico confirmado',
|
||||
pending_biopsy: 'Pendiente de biopsia',
|
||||
biopsy_no_result: 'Biopsia sin resultado',
|
||||
benign_biopsy: 'Biopsia benigna',
|
||||
confirmed: 'Diagnóstico confirmado',
|
||||
in_process: 'En proceso',
|
||||
not_confirmed: 'Sin TEA',
|
||||
mchat_only: 'Solo M-CHAT',
|
||||
psychology: 'Psicología (ADOS-2)',
|
||||
neuropediatrics: 'Neuropediatría',
|
||||
neurology: 'Neurología',
|
||||
eeg: 'EEG',
|
||||
good: 'Bueno',
|
||||
bad: 'Malo',
|
||||
not_analyzed: 'Sin analizar',
|
||||
initial: 'Detección inicial',
|
||||
subsequent: 'Con detección anterior',
|
||||
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(
|
||||
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
|
||||
),
|
||||
};
|
||||
/** A follow-up priority's label. */
|
||||
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
|
||||
export const STRATA: Record<string, string> = {
|
||||
category: 'Categoría',
|
||||
age_group: 'Grupo de edad',
|
||||
follow_up_status: 'Estatus de seguimiento',
|
||||
result: 'Citología de alto grado',
|
||||
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: 'Detección inicial o anterior',
|
||||
hpv_16: 'VPH 16',
|
||||
hpv_18: 'VPH 18',
|
||||
};
|
||||
/** Breast histologic types (ICD-O-3 morphology) the sites report; any other shows its code. */
|
||||
const HISTOLOGIC_TYPES: Record<string, string> = {
|
||||
'8500/2': 'Carcinoma ductal in situ',
|
||||
'8500/3': 'Carcinoma ductal infiltrante',
|
||||
'8520/2': 'Carcinoma lobulillar in situ',
|
||||
'8520/3': 'Carcinoma lobulillar infiltrante',
|
||||
'8522/3': 'Carcinoma ductal y lobulillar infiltrante',
|
||||
'8480/3': 'Adenocarcinoma mucinoso',
|
||||
'8211/3': 'Carcinoma tubular',
|
||||
'8510/3': 'Carcinoma medular',
|
||||
'8530/3': 'Carcinoma inflamatorio',
|
||||
'8540/3': 'Enfermedad de Paget de la mama',
|
||||
'9010/0': 'Fibroadenoma',
|
||||
'9016/0': 'Fibroadenoma gigante',
|
||||
};
|
||||
export const name = (value: string) => LABELS[value] ?? HISTOLOGIC_TYPES[value] ?? value;
|
||||
@@ -1,3 +1,4 @@
|
||||
import { name } from './labels';
|
||||
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
|
||||
import { code, ext } from '../fhir';
|
||||
import { Figure, PALETTE } from '../plot';
|
||||
@@ -23,6 +24,13 @@ export function periods(type: PeriodType, years = 6, today = new Date()): string
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A period's first day ("2026-S2": July 1st; "2026-03": March 1st). */
|
||||
export function periodStart(period: string): Date {
|
||||
const [year, part] = period.split('-');
|
||||
const month = part.startsWith('S') ? (part === 'S1' ? 0 : 6) : Number(part) - 1;
|
||||
return new Date(Number(year), month, 1);
|
||||
}
|
||||
|
||||
export function periodLabel(period: string): string {
|
||||
const [year, part] = period.split('-');
|
||||
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
|
||||
@@ -50,6 +58,8 @@ export interface Reading {
|
||||
high?: number;
|
||||
unit?: string;
|
||||
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: {
|
||||
@@ -65,6 +75,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
|
||||
if (!group) return undefined;
|
||||
const score = group.measureScore;
|
||||
const strata: Reading['strata'] = {};
|
||||
const scores: NonNullable<Reading['scores']> = {};
|
||||
for (const s of group.stratifier ?? []) {
|
||||
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
|
||||
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
|
||||
@@ -76,6 +87,13 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
|
||||
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 {
|
||||
populations: counts(group),
|
||||
@@ -84,59 +102,10 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
|
||||
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
|
||||
unit: score?.unit,
|
||||
strata,
|
||||
scores,
|
||||
};
|
||||
}
|
||||
|
||||
/** Codes as the screens name them. */
|
||||
const LABELS: Record<string, string> = {
|
||||
NILM: 'Normal (NILM)',
|
||||
LSIL: 'LIEBG',
|
||||
HSIL: 'LIEAG',
|
||||
normal: 'Normal',
|
||||
carcinoma: 'Carcinoma',
|
||||
no_data: 'Sin dato',
|
||||
no_biopsy: 'Sin biopsia',
|
||||
pre_colposcopy: 'Pre colposcopia',
|
||||
post_colposcopy: 'Post colposcopia',
|
||||
post_treatment: 'Post tratamiento',
|
||||
case: 'Caso (cáncer)',
|
||||
low: 'Bajo',
|
||||
intermediate: 'Intermedio',
|
||||
high: 'Alto',
|
||||
satisfactory: 'satisfactoria',
|
||||
unsatisfactory: 'insatisfactoria',
|
||||
benign: 'Benigno',
|
||||
in_situ: 'Carcinoma in situ',
|
||||
invasive: 'Carcinoma invasor',
|
||||
cancer: 'Diagnóstico confirmado',
|
||||
pending_biopsy: 'Pendiente de biopsia',
|
||||
biopsy_no_result: 'Biopsia sin resultado',
|
||||
benign_biopsy: 'Biopsia benigna',
|
||||
confirmed: 'Diagnóstico confirmado',
|
||||
in_process: 'En proceso',
|
||||
not_confirmed: 'Sin TEA',
|
||||
mchat_only: 'Solo M-CHAT',
|
||||
psychology: 'Psicología (ADOS-2)',
|
||||
neuropediatrics: 'Neuropediatría',
|
||||
eeg: 'EEG',
|
||||
good: 'Bueno',
|
||||
bad: 'Malo',
|
||||
not_analyzed: 'Sin analizar',
|
||||
...Object.fromEntries(
|
||||
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
|
||||
),
|
||||
};
|
||||
/** A follow-up priority's label. */
|
||||
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
|
||||
export const STRATA: Record<string, string> = {
|
||||
category: 'Categoría',
|
||||
age_group: 'Grupo de edad',
|
||||
follow_up_status: 'Estatus de seguimiento',
|
||||
result: 'Citología de alto grado',
|
||||
birads: 'BI-RADS de la mastografía',
|
||||
};
|
||||
export const name = (value: string) => LABELS[value] ?? value;
|
||||
|
||||
export function formatScore(measure: Measure, r: Reading | undefined): string {
|
||||
if (!r || r.score === undefined) return 'Sin dato';
|
||||
switch (scoring(measure)) {
|
||||
@@ -149,14 +118,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 '';
|
||||
const p = r.populations;
|
||||
switch (scoring(measure)) {
|
||||
case 'proportion':
|
||||
return r.score === undefined
|
||||
? 'Sin pacientes en el periodo.'
|
||||
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
|
||||
? `Sin ${unit} en el periodo.`
|
||||
: `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
|
||||
case 'continuous-variable':
|
||||
return r.score === undefined
|
||||
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
import type { Category, Mode } from './bars';
|
||||
import {
|
||||
BIOPSY,
|
||||
CONFIRMED,
|
||||
CYTOLOGY,
|
||||
HPV,
|
||||
LEVEL,
|
||||
PRIOR_CYTOLOGY,
|
||||
ROUND,
|
||||
TINT,
|
||||
} from './palette-cacu';
|
||||
import type { Page, ReadingsCard } from './pages';
|
||||
|
||||
const ROSE = '#C24269';
|
||||
const of = (colors: Record<string, string>, rows: [string, string][]): Category[] =>
|
||||
rows.map(([code, label]) => ({ code, label, color: colors[code] }));
|
||||
|
||||
/** Bethesda results; the abnormal ones also added up under "Anormal". */
|
||||
const RESULTS = of(CYTOLOGY, [
|
||||
['NILM', 'Normal'],
|
||||
['ASC-US', 'ASC-US'],
|
||||
['LSIL', 'LIEBG'],
|
||||
['ASC-H', 'ASC-H'],
|
||||
['HSIL', 'LIEAG'],
|
||||
['CIS', 'Carcinoma in situ'],
|
||||
['carcinoma', 'Carcinoma epidermoide invasor'],
|
||||
]);
|
||||
const ABNORMAL = { label: 'Anormal', color: ROSE, codes: RESULTS.slice(1).map((c) => c.code) };
|
||||
const GRADES = of(BIOPSY, [
|
||||
['normal', 'Normal'],
|
||||
['LSIL', 'LIEBG (CIN 1)'],
|
||||
['CIN2', 'CIN 2'],
|
||||
['HSIL', 'LIEAG (CIN 2 y 3)'],
|
||||
['CIN3', 'CIN 3'],
|
||||
['CIS', 'Carcinoma in situ'],
|
||||
['carcinoma', 'Carcinoma invasor'],
|
||||
]);
|
||||
const GENOTYPES = of(HPV, [
|
||||
['negative', 'Negativo'],
|
||||
['positive_16', 'VPH 16'],
|
||||
['positive_18', 'VPH 18'],
|
||||
['positive_16_18', 'VPH 16 y 18'],
|
||||
['positive_other', 'Positivo sin genotipo'],
|
||||
]);
|
||||
/** HPV categories not drawn: their reports stay in the total and the percentages. */
|
||||
const UNDRAWN = { codes: ['positive_incomplete', 'inconsistent', 'no_result'], unit: 'reportes' };
|
||||
|
||||
const ROUNDS = ['initial', 'subsequent', 'no_data'];
|
||||
const BY_ROUND = 'Por detección inicial y anterior';
|
||||
const BY_AGE = 'Por grupo de edad';
|
||||
const GENERAL = 'General';
|
||||
|
||||
/** A results card's general reading and its readings by age group and by round (one
|
||||
* selector for both cards). */
|
||||
function results(measure: string, catalog: Category[], unit: string, more: object): Mode[] {
|
||||
const caption =
|
||||
measure === 'CACU_VPH_GENOTIPO'
|
||||
? 'Porcentaje de reportes de VPH del grupo por genotipo.'
|
||||
: 'Porcentaje de pacientes del grupo por resultado citológico.';
|
||||
const groups = [
|
||||
{
|
||||
label: BY_AGE,
|
||||
stratum: 'age_group',
|
||||
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
|
||||
},
|
||||
{ label: BY_ROUND, stratum: 'round', order: ROUNDS, complete: true },
|
||||
];
|
||||
return [
|
||||
{
|
||||
kind: 'counts',
|
||||
label: GENERAL,
|
||||
measure,
|
||||
catalog,
|
||||
unit: unit === 'pacientes' ? 'Pacientes' : 'Reportes',
|
||||
percentLabel:
|
||||
unit === 'pacientes' ? 'Porcentaje de pacientes' : 'Porcentaje de reportes de VPH',
|
||||
...more,
|
||||
},
|
||||
...groups.map((g) => ({
|
||||
kind: 'grouped' as const,
|
||||
measure,
|
||||
catalog,
|
||||
unit,
|
||||
caption,
|
||||
ofAll: true,
|
||||
...g,
|
||||
...more,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
/** A confirmation rate's card: the whole, and by each of its stratifiers. */
|
||||
const ppv = (measure: string, title: string, note: string, percentLabel: string): ReadingsCard => ({
|
||||
kind: 'readings',
|
||||
title,
|
||||
headline: measure,
|
||||
footnote: true,
|
||||
note: `${note} Confirma la histología LIEBG o mayor.`,
|
||||
modes: [
|
||||
{ kind: 'ratio', label: 'Total', measure, color: CONFIRMED, 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: PRIOR_CYTOLOGY,
|
||||
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,
|
||||
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: LEVEL,
|
||||
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
|
||||
percentLabel: 'Porcentaje de pacientes de cada nivel de histología',
|
||||
},
|
||||
{
|
||||
kind: 'shares',
|
||||
label: BY_ROUND,
|
||||
caption:
|
||||
'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección ' +
|
||||
'inicial (primera vez en la vida), con detección anterior (registrada, o ya con ' +
|
||||
'colposcopía o tratamiento) o «Sin dato». Un grupo sin pacientes se muestra en cero; ' +
|
||||
'sin porcentaje.',
|
||||
measure,
|
||||
stratum: 'round',
|
||||
colors: ROUND,
|
||||
order: ROUNDS,
|
||||
complete: true,
|
||||
percentLabel: 'Porcentaje de pacientes de cada ronda',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const CACU_DAYS = {
|
||||
value: '{median} días (mediana)',
|
||||
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
|
||||
};
|
||||
const days = (label: string, ...steps: [string, string][]): Mode => ({
|
||||
kind: 'days',
|
||||
label,
|
||||
tint: TINT,
|
||||
steps: steps.map(([label, measure]) => ({ label, measure })),
|
||||
});
|
||||
|
||||
export const CACU: Page = {
|
||||
anchor: 'CACU_EU7',
|
||||
clinicalFirst: true,
|
||||
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_POST_BIOPSIA',
|
||||
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
|
||||
...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 tras biopsia 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: [
|
||||
days(
|
||||
'Acumulado desde la toma',
|
||||
['Resultado de citología', 'CACU_EU_TIEMPO_REPORTE'],
|
||||
['Resultado de colposcopía', 'CACU_DIAS_TOMA_COLPOSCOPIA'],
|
||||
['Resultado de biopsia', 'CACU_DIAS_TOMA_BIOPSIA'],
|
||||
['Diagnóstico tras biopsia', 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA'],
|
||||
),
|
||||
{
|
||||
...days(
|
||||
'Por ventana de tiempo',
|
||||
['Toma a resultado de citología', 'CACU_EU_TIEMPO_REPORTE'],
|
||||
['Resultado a colposcopía', 'CACU_DIAS_RESULTADO_COLPOSCOPIA'],
|
||||
['Colposcopía a biopsia', 'CACU_DIAS_COLPOSCOPIA_BIOPSIA'],
|
||||
['Biopsia a diagnóstico', 'CACU_DIAS_BIOPSIA_DIAGNOSTICO'],
|
||||
),
|
||||
staggered: true,
|
||||
caption:
|
||||
'Esquema: cada barra empieza donde termina la anterior. Cada paso mide a sus ' +
|
||||
'propias pacientes: las medianas no se suman.',
|
||||
} as Mode,
|
||||
days('Diagnóstico precolposcópico', [
|
||||
'Toma a primer diagnóstico',
|
||||
'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
]),
|
||||
days('Diagnóstico tras biopsia', [
|
||||
'Toma a diagnóstico tras biopsia',
|
||||
'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_ROUND],
|
||||
sections: [
|
||||
{
|
||||
kind: 'readings',
|
||||
follows: true,
|
||||
title: 'Distribución de resultados citológicos',
|
||||
note: 'Pacientes, por su última muestra válida del periodo.',
|
||||
modes: results('CACU_EU7', RESULTS, 'pacientes', { aggregate: ABNORMAL }),
|
||||
},
|
||||
{
|
||||
kind: 'readings',
|
||||
follows: true,
|
||||
title: 'Resultados de VPH por genotipo',
|
||||
note: 'Reportes, por fecha de toma.',
|
||||
modes: results('CACU_VPH_GENOTIPO', GENOTYPES, 'reportes', { hidden: UNDRAWN }),
|
||||
},
|
||||
{
|
||||
kind: 'readings',
|
||||
title: 'Resultados de biopsia cervical',
|
||||
note: 'Reportes, por fecha de reporte.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'counts',
|
||||
label: GENERAL,
|
||||
measure: 'CACU_BIOPSIA_RESULTADOS',
|
||||
catalog: GRADES,
|
||||
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',
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,228 @@
|
||||
import type { Catalog, Page } from './pages';
|
||||
|
||||
const CAMA_DAYS = {
|
||||
value: '{median} días (mediana)',
|
||||
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
|
||||
};
|
||||
|
||||
/** BI-RADS 4 to 6 as the old app named and coloured them. */
|
||||
const BIRADS: Catalog = {
|
||||
groups: [],
|
||||
categories: [
|
||||
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
|
||||
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
|
||||
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
|
||||
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
|
||||
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
|
||||
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
|
||||
],
|
||||
};
|
||||
/** What a patient without a typed biopsy shows. */
|
||||
const NO_TYPE = [
|
||||
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
|
||||
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
|
||||
];
|
||||
|
||||
/** CaMa's page: the timeliness cards and their route, then the clinical indicators. */
|
||||
export const CAMA: Page = {
|
||||
anchor: 'CAMA_BIRADS456_PACIENTE',
|
||||
kpis: [
|
||||
{
|
||||
measure: 'CAMA_BIRADS456_PACIENTE',
|
||||
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
|
||||
value: '{n} pacientes',
|
||||
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_EU38A',
|
||||
title: 'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
title: 'Tiempo de interpretación radiológica a diagnóstico',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
|
||||
title: 'Tiempo de interpretación radiológica a resultado de biopsia',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
title: 'Tiempo de diagnóstico tras biopsia a tratamiento',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
],
|
||||
opportunity: [
|
||||
{
|
||||
kind: 'readings',
|
||||
title: 'Tiempo de tamizaje a diagnóstico y tratamiento',
|
||||
modes: [
|
||||
{
|
||||
kind: 'days',
|
||||
label: 'Por pasos',
|
||||
rowsLabel: 'Paso',
|
||||
staggered: true,
|
||||
scale: true,
|
||||
tint: { bar: '#42A77E', mark: '#17324D' },
|
||||
caption:
|
||||
'Esquema: cada barra es la mediana de su paso y empieza donde termina el paso del ' +
|
||||
'que parte. Los pasos pueden corresponder a poblaciones diferentes, por lo que las ' +
|
||||
'medianas no se suman. Las marcas indican el primer y tercer cuartil.',
|
||||
steps: [
|
||||
{ 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',
|
||||
},
|
||||
{
|
||||
label: 'Diagnóstico tras biopsia a tratamiento',
|
||||
measure: 'CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
},
|
||||
// from the interpretation, as the diagnosis
|
||||
{
|
||||
label: 'Interpretación radiológica a resultado de biopsia',
|
||||
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
|
||||
after: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'days',
|
||||
label: 'Acumulado desde la toma',
|
||||
rowsLabel: 'Etapa',
|
||||
scale: true,
|
||||
tint: { bar: '#42A77E', mark: '#17324D' },
|
||||
caption:
|
||||
'Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se ' +
|
||||
'calcula por separado. Las marcas indican el primer y tercer cuartil.',
|
||||
steps: [
|
||||
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
|
||||
{
|
||||
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
clinical: [
|
||||
{
|
||||
kind: 'figures',
|
||||
figures: [
|
||||
{
|
||||
kind: 'share-donut',
|
||||
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
|
||||
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
|
||||
catalog: BIRADS,
|
||||
center: 'mastografías',
|
||||
},
|
||||
{
|
||||
kind: 'share-donut',
|
||||
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
|
||||
measure: 'CAMA_BIRADS456_PACIENTE',
|
||||
catalog: BIRADS,
|
||||
center: 'pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'readings',
|
||||
title: 'Tipo histológico por categoría BI-RADS',
|
||||
note:
|
||||
'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave ' +
|
||||
'reportada, por fecha del examen. Los tipos siguen la clasificación CIE-O-3; «Sin dato» ' +
|
||||
'incluye tipos ausentes o ' +
|
||||
'con vínculo ambiguo. El porcentaje maligno conserva la clasificación de la biopsia y ' +
|
||||
'su denominador de pacientes con clasificación conocida.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'outcomes',
|
||||
label: 'Por categoría BI-RADS',
|
||||
heading: 'Resultados por paciente',
|
||||
caption: '«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.',
|
||||
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
|
||||
stratum: 'birads',
|
||||
rows: BIRADS.categories,
|
||||
results: NO_TYPE,
|
||||
malignant: ['in_situ', 'invasive'],
|
||||
malignancy: 'CAMA_HISTOPATOLOGIA_BIRADS',
|
||||
},
|
||||
{
|
||||
kind: 'counts',
|
||||
label: 'Todas las categorías',
|
||||
heading: 'Resultados por paciente',
|
||||
measure: 'CAMA_TIPO_HISTOLOGICO_BIRADS',
|
||||
catalog: [],
|
||||
unit: 'Pacientes',
|
||||
percent: true,
|
||||
percentLabel: 'Porcentaje de pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'choice',
|
||||
title: 'Confirmación histopatológica',
|
||||
card: true,
|
||||
choices: [
|
||||
{
|
||||
label: 'Tipos histológicos',
|
||||
section: {
|
||||
kind: 'readings',
|
||||
title: 'Tipos histológicos',
|
||||
note:
|
||||
'Biopsias por fecha de reporte, agrupadas por tipo histológico (CIE-O-3). «Sin dato» ' +
|
||||
'incluye los ' +
|
||||
'tipos ausentes y los que no pueden vincularse de forma inequívoca. La tasa de ' +
|
||||
'detección conserva su cálculo de carcinomas entre biopsias con clasificación ' +
|
||||
'conocida; su denominador puede ser distinto.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'counts',
|
||||
label: 'Tipos histológicos',
|
||||
heading: 'Tipo histológico',
|
||||
measure: 'CAMA_TIPO_HISTOLOGICO',
|
||||
catalog: [],
|
||||
unit: 'Biopsias',
|
||||
percent: true,
|
||||
percentLabel: 'Porcentaje de reportes de biopsia',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Mastografías con biopsia',
|
||||
section: {
|
||||
kind: 'readings',
|
||||
title: 'Mastografías con biopsia',
|
||||
headline: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
unit: 'mastografías',
|
||||
note:
|
||||
'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: ' +
|
||||
'cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de ' +
|
||||
'la biopsia.',
|
||||
modes: [
|
||||
{
|
||||
kind: 'split',
|
||||
label: 'Con y sin biopsia',
|
||||
measure: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
yes: 'Con reporte de biopsia',
|
||||
no: 'Sin reporte de biopsia',
|
||||
colors: ['#A8C243', '#C9CDD2'],
|
||||
unit: 'Mastografías',
|
||||
percentLabel: 'Porcentaje de mastografías',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
+41
-473
@@ -1,8 +1,14 @@
|
||||
import type { Mode } from './bars';
|
||||
import { CACU } from './pages-cacu';
|
||||
import { CAMA } from './pages-cama';
|
||||
|
||||
/** 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.
|
||||
* Measures are named by their code (`Measure.name`). */
|
||||
export interface Page {
|
||||
kpis: Kpi[];
|
||||
/** the clinical indicators before the timeliness ones (CaCu) */
|
||||
clinicalFirst?: boolean;
|
||||
/** Under the cards, before the clinical indicators (CaMa's timeliness boxes). */
|
||||
opportunity?: Section[];
|
||||
clinical: Section[];
|
||||
@@ -17,26 +23,53 @@ export interface Kpi {
|
||||
value?: 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;
|
||||
/** the headline said under the figure, not above it */
|
||||
footnote?: boolean;
|
||||
/** what the headline proportion counts, in the plural (default: pacientes) */
|
||||
unit?: string;
|
||||
note?: string;
|
||||
modes: Mode[];
|
||||
/** in `columns` with `views`, the mode its section's selector picks */
|
||||
follows?: boolean;
|
||||
}
|
||||
export type Section =
|
||||
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] }
|
||||
| ReadingsCard
|
||||
/** Cards side by side, the last one alone when odd; `views`: one selector (its first view
|
||||
* by default) for the cards that follow it */
|
||||
| {
|
||||
kind: 'columns';
|
||||
title: string;
|
||||
sections: ReadingsCard[];
|
||||
views?: string[];
|
||||
viewsLabel?: string;
|
||||
}
|
||||
/** One section at a time; `card`: the title, the toggle and the chosen card in one card */
|
||||
| {
|
||||
kind: 'choice';
|
||||
title: string;
|
||||
choices: { label: string; section: ReadingsCard }[];
|
||||
card?: boolean;
|
||||
}
|
||||
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
|
||||
| {
|
||||
kind: 'boxes';
|
||||
/** none: the boxes stand alone (TEA) */
|
||||
title?: string;
|
||||
cards: { measure?: string; title: string }[];
|
||||
/** the measure's own title under each card's (CaMa) */
|
||||
subtitles?: boolean;
|
||||
}
|
||||
/** Each figure in its own card, titled, two to a row (TEA). */
|
||||
| { kind: 'grid'; figures: FigureSpec[] }
|
||||
/** TEA's period summary in words, its numbers from the measures. */
|
||||
| { kind: 'tea-summary' }
|
||||
| ({ kind: 'card' } & Kpi);
|
||||
| { kind: 'tea-summary' };
|
||||
/** Figure titles may carry `{p}`, the applied period. */
|
||||
export type FigureSpec =
|
||||
| {
|
||||
kind: 'donut' | 'share-donut';
|
||||
kind: 'share-donut';
|
||||
title: string;
|
||||
measure: string;
|
||||
catalog: Catalog;
|
||||
@@ -50,18 +83,6 @@ export type FigureSpec =
|
||||
measure: string;
|
||||
/** the numerator's and the rest's names (stack), or the axis (share) */
|
||||
names: [string, string];
|
||||
}
|
||||
| {
|
||||
kind: 'rates';
|
||||
title: string;
|
||||
measure: string;
|
||||
stratum: string;
|
||||
rows: Category[];
|
||||
/** each row in its category's colour (else all rose) */
|
||||
colored?: boolean;
|
||||
/** the categories (of the measure) that count as a positive */
|
||||
positive: string[];
|
||||
axis: string;
|
||||
};
|
||||
|
||||
export interface Category {
|
||||
@@ -78,73 +99,6 @@ export interface Catalog {
|
||||
}
|
||||
|
||||
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: '#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 = {
|
||||
value: '{median} días (mediana)',
|
||||
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. */
|
||||
const BIRADS: Catalog = {
|
||||
groups: [],
|
||||
categories: [
|
||||
{ code: '4', label: 'BI-RADS 4 (sin subcategoría)', color: '#C24269', group: '' },
|
||||
{ code: '4A', label: 'BI-RADS 4A', color: '#9C42C2', group: '' },
|
||||
{ code: '4B', label: 'BI-RADS 4B', color: '#5C42C2', group: '' },
|
||||
{ code: '4C', label: 'BI-RADS 4C', color: '#C2429C', group: '' },
|
||||
{ code: '5', label: 'BI-RADS 5', color: '#8E2F62', group: '' },
|
||||
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
|
||||
],
|
||||
};
|
||||
const BREAST_BIOPSY: Catalog = {
|
||||
groups: [
|
||||
{ id: 'benign', label: 'No maligno', color: '#42C29C' },
|
||||
{ id: 'malignant', label: 'Maligno', color: ROSE },
|
||||
],
|
||||
categories: [
|
||||
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
|
||||
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
|
||||
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
|
||||
],
|
||||
};
|
||||
|
||||
export const PAGES: Record<string, Page> = {
|
||||
tea: {
|
||||
@@ -239,392 +193,6 @@ export const PAGES: Record<string, Page> = {
|
||||
},
|
||||
],
|
||||
},
|
||||
cama: {
|
||||
anchor: 'CAMA_BIRADS456_PACIENTE',
|
||||
kpis: [
|
||||
{
|
||||
measure: 'CAMA_BIRADS456_PACIENTE',
|
||||
title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6',
|
||||
value: '{n} pacientes',
|
||||
note: 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.',
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
value: '{pct} %',
|
||||
note: '{num} de {den} biopsias con riesgo a carcinoma.',
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_EU38A',
|
||||
title: 'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
title: 'Tiempo de interpretación radiológica a diagnóstico',
|
||||
...CAMA_DAYS,
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de diagnóstico a tratamiento',
|
||||
value: 'Indicador no disponible',
|
||||
note: PENDING,
|
||||
},
|
||||
],
|
||||
opportunity: [
|
||||
{
|
||||
kind: 'boxes',
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
subtitles: true,
|
||||
cards: [
|
||||
{
|
||||
measure: 'CAMA_EU38A',
|
||||
title: 'Tiempo de toma de mastografía a interpretación radiológica',
|
||||
},
|
||||
{
|
||||
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' },
|
||||
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
|
||||
],
|
||||
},
|
||||
],
|
||||
clinical: [
|
||||
{
|
||||
kind: 'figures',
|
||||
figures: [
|
||||
{
|
||||
kind: 'share-donut',
|
||||
title: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en {p}',
|
||||
measure: 'CAMA_BIRADS456_MASTOGRAFIA',
|
||||
catalog: BIRADS,
|
||||
center: 'mastografías',
|
||||
},
|
||||
{
|
||||
kind: 'share-donut',
|
||||
title: 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en {p}',
|
||||
measure: 'CAMA_BIRADS456_PACIENTE',
|
||||
catalog: BIRADS,
|
||||
center: 'pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'figures',
|
||||
title: 'Resultado histopatológico por categoría BI-RADS',
|
||||
figures: [
|
||||
{
|
||||
kind: 'rates',
|
||||
title: 'Por categoría BI-RADS, {p}',
|
||||
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
|
||||
stratum: 'birads',
|
||||
rows: BIRADS.categories,
|
||||
colored: true,
|
||||
positive: ['in_situ', 'invasive'],
|
||||
axis: 'Porcentaje con resultado maligno',
|
||||
},
|
||||
{
|
||||
kind: 'donut',
|
||||
title: 'Resultado de la biopsia, {p}',
|
||||
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
|
||||
catalog: BREAST_BIOPSY,
|
||||
center: 'con resultado',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'card',
|
||||
measure: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
value: '{pct} %',
|
||||
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',
|
||||
title: 'Distribución de resultados, {p}',
|
||||
measure: 'CACU_EU7',
|
||||
catalog: CYTOLOGY,
|
||||
center: 'pacientes',
|
||||
},
|
||||
{
|
||||
kind: 'scenario-bars',
|
||||
title: 'TOTAL por escenario clínico, {p}',
|
||||
measure: 'CACU_EU7',
|
||||
catalog: CYTOLOGY,
|
||||
stratum: 'follow_up_status',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'figures',
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
figures: [
|
||||
{
|
||||
kind: 'rates',
|
||||
title: 'Por resultado de la citología, {p}',
|
||||
measure: 'CACU_CONFIRMACION_CITOLOGIA',
|
||||
stratum: 'result',
|
||||
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',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
|
||||
* measure month by month, as stacked counts by category, a percentage with its 95 % interval,
|
||||
* or a median with its quartiles. `group` heads a run of panels (TEA's "Tiempos del tamizaje"). */
|
||||
export interface HistoryPanel {
|
||||
title: string;
|
||||
measure: string;
|
||||
kind: 'stack' | 'percent' | 'median';
|
||||
/** stack: the categories, in the old order, with their names and colours */
|
||||
series?: { code: string; label: string; color: string }[];
|
||||
/** stack: the y axis */
|
||||
axis?: string;
|
||||
group?: string;
|
||||
}
|
||||
export interface History {
|
||||
panels: HistoryPanel[];
|
||||
/** the line's colour (percent and median) */
|
||||
line: string;
|
||||
/** how many of the latest months the tab opens with (none: from the first with data) */
|
||||
months?: number;
|
||||
}
|
||||
|
||||
const GREY = '#C9CDD2';
|
||||
const stack = (
|
||||
title: string,
|
||||
measure: string,
|
||||
axis: string,
|
||||
series: [string, string, string][],
|
||||
): HistoryPanel => ({
|
||||
title,
|
||||
measure,
|
||||
kind: 'stack',
|
||||
axis,
|
||||
series: series.map(([code, label, color]) => ({ code, label, color })),
|
||||
});
|
||||
const BIRADS_SERIES: [string, string, string][] = [
|
||||
['4A', 'BI-RADS 4A', '#C24269'],
|
||||
['4B', 'BI-RADS 4B', '#9C42C2'],
|
||||
['4C', 'BI-RADS 4C', '#5C42C2'],
|
||||
['5', 'BI-RADS 5', '#C2429C'],
|
||||
['6', 'BI-RADS 6', '#8E2F62'],
|
||||
['4', 'BI-RADS 4 (sin subcategoría)', '#7A3496'],
|
||||
];
|
||||
|
||||
export const HISTORY: Record<string, History> = {
|
||||
cacu: {
|
||||
line: '#6A8000',
|
||||
months: 5,
|
||||
panels: [
|
||||
stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
|
||||
['NILM', 'Normal', '#9DBFE3'],
|
||||
['ASC-US', 'ASC-US', '#2F6DB3'],
|
||||
['LSIL', 'LIEBG', '#9C42C2'],
|
||||
['ASC-H', 'ASC-H', '#5C42C2'],
|
||||
['HSIL', 'LIEAG', '#C2429C'],
|
||||
['CIS', 'Carcinoma in situ', '#8E2F62'],
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{ title: 'Pacientes con citología anómala', measure: 'IND1', kind: 'percent' },
|
||||
{ title: 'Tasa de detección histopatológica', measure: 'CACU_EU13', kind: 'percent' },
|
||||
stack(
|
||||
'Resultado de biopsia tras citología de alto grado',
|
||||
'CACU_CONFIRMACION_CITOLOGIA',
|
||||
'Pacientes',
|
||||
[
|
||||
['normal', 'Normal', '#9DBFE3'],
|
||||
['LSIL', 'LIEBG (CIN 1)', '#69C242'],
|
||||
['HSIL', 'LIEAG (CIN 2 y 3)', '#C24269'],
|
||||
['CIS', 'Carcinoma in situ', '#9C42C2'],
|
||||
['carcinoma', 'Carcinoma invasor', '#5C42C2'],
|
||||
['no_biopsy', 'Sin biopsia aún', GREY],
|
||||
['no_data', 'Biopsia sin grado', GREY],
|
||||
],
|
||||
),
|
||||
{
|
||||
title: 'Días de la toma de la citología a su resultado',
|
||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a diagnóstico',
|
||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de tamizaje a tratamiento',
|
||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Tiempo de diagnóstico a tratamiento',
|
||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Riesgo CIN2+ por banda',
|
||||
measure: 'CACU_RIESGO_BANDA',
|
||||
kind: 'stack',
|
||||
axis: 'Pacientes',
|
||||
},
|
||||
],
|
||||
},
|
||||
cama: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{
|
||||
title: 'Días de la toma de la mastografía a su resultado',
|
||||
measure: 'CAMA_EU38A',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días del resultado de la mastografía al diagnóstico',
|
||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
title: 'Días de tamizaje a diagnóstico',
|
||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
stack(
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_MASTOGRAFIA',
|
||||
'Mastografías',
|
||||
BIRADS_SERIES,
|
||||
),
|
||||
stack(
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'CAMA_BIRADS456_PACIENTE',
|
||||
'Pacientes',
|
||||
BIRADS_SERIES,
|
||||
),
|
||||
stack('Resultado histopatológico', 'CAMA_HISTOPATOLOGIA_BIRADS', 'Pacientes', [
|
||||
['benign', 'Benigno', '#9DBFE3'],
|
||||
['in_situ', 'Carcinoma in situ', '#C24269'],
|
||||
['invasive', 'Carcinoma invasor', '#9C42C2'],
|
||||
['no_biopsy', 'Sin biopsia reportada', GREY],
|
||||
['no_data', 'Sin dato', GREY],
|
||||
]),
|
||||
{
|
||||
title: 'Tasa de confirmación histopatológica',
|
||||
measure: 'CAMA_CONFIRMACION_BIRADS45',
|
||||
kind: 'percent',
|
||||
},
|
||||
],
|
||||
},
|
||||
tea: {
|
||||
line: '#9C42C2',
|
||||
panels: [
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de M-CHAT a ADOS-2',
|
||||
measure: 'M26_DIAS_MCHAT_ADOS2',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de ADOS-2 a diagnóstico',
|
||||
measure: 'M27_DIAS_ADOS2_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
{
|
||||
group: 'Tiempos del tamizaje',
|
||||
title: 'Días de M-CHAT a diagnóstico positivo',
|
||||
measure: 'M25_DIAS_MCHAT_DIAGNOSTICO',
|
||||
kind: 'median',
|
||||
},
|
||||
stack('Progresión del proceso diagnóstico', 'M23_PACIENTES_EVALUADOS', 'Pacientes', [
|
||||
['confirmed', 'Diagnóstico confirmado', '#A8C243'],
|
||||
['in_process', 'En proceso', '#B8433A'],
|
||||
]),
|
||||
{
|
||||
title: 'Porcentaje de confirmación diagnóstica',
|
||||
measure: 'M24_CONFIRMACION_DIAGNOSTICO',
|
||||
kind: 'percent',
|
||||
},
|
||||
{
|
||||
title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG',
|
||||
measure: 'M21_DIAGNOSTICADOS_CON_EEG',
|
||||
kind: 'percent',
|
||||
},
|
||||
{
|
||||
title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
measure: 'M22_DIAGNOSTICADOS_SIN_EEG',
|
||||
kind: 'percent',
|
||||
},
|
||||
stack('Flujo del proceso diagnóstico y estudios de EEG', 'M28_CASOS_POR_ESTADO', 'Casos', [
|
||||
['mchat_only', 'Solo M-CHAT', '#B8433A'],
|
||||
['psychology', 'Hasta evaluación psicológica', '#42C29C'],
|
||||
['neuropediatrics', 'Hasta evaluación neuropediátrica', '#7184A2'],
|
||||
['eeg', 'Con EEG', '#A8C243'],
|
||||
]),
|
||||
stack('Calidad del EEG', 'M29_CALIDAD_EEG', 'Estudios de EEG', [
|
||||
['good', 'Bueno', '#A8C243'],
|
||||
['bad', 'No aceptable', '#B8433A'],
|
||||
['not_analyzed', 'Sin analizar', GREY],
|
||||
]),
|
||||
],
|
||||
},
|
||||
cama: CAMA,
|
||||
cacu: CACU,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/** CaCu's colours, by category: a colour names a category (never a position in a report), so
|
||||
* one category looks the same on every card; greys are what is absent or not classified. */
|
||||
export const NEUTRAL = '#C9CDD2';
|
||||
export const NEUTRAL_DARK = '#9AA3AB';
|
||||
const STEEL = '#5F7F9A';
|
||||
const STEEL_MID = '#8FA7BB';
|
||||
|
||||
const GREEN = '#408651';
|
||||
const BLUE = '#2778B8';
|
||||
const OCHRE = '#B19525';
|
||||
const VIOLET = '#7955B1';
|
||||
const PINK = '#E07A9C';
|
||||
const RASPBERRY = '#CE4778';
|
||||
const RUBY = '#BC4163';
|
||||
const WINE = '#AA394D';
|
||||
const PLUM = '#8D4C79';
|
||||
|
||||
export const CYTOLOGY: Record<string, string> = {
|
||||
NILM: GREEN,
|
||||
'ASC-US': BLUE,
|
||||
LSIL: OCHRE,
|
||||
'ASC-H': VIOLET,
|
||||
HSIL: RASPBERRY,
|
||||
CIS: WINE,
|
||||
carcinoma: PLUM,
|
||||
no_data: NEUTRAL,
|
||||
};
|
||||
export const BIOPSY: Record<string, string> = {
|
||||
normal: GREEN,
|
||||
LSIL: OCHRE,
|
||||
CIN2: PINK,
|
||||
HSIL: RASPBERRY,
|
||||
CIN3: RUBY,
|
||||
CIS: WINE,
|
||||
carcinoma: PLUM,
|
||||
no_data: NEUTRAL,
|
||||
};
|
||||
/** HPV by genotype; a prior HPV group takes its genotype's colour. */
|
||||
export const HPV: Record<string, string> = {
|
||||
negative: '#42A77E',
|
||||
positive_16: '#DF8640',
|
||||
positive_18: '#C29C42',
|
||||
positive_16_18: '#C24269',
|
||||
positive_other: '#A8C243',
|
||||
positive: '#A8C243',
|
||||
hpv_16: '#DF8640',
|
||||
hpv_18: '#C29C42',
|
||||
no_data: NEUTRAL,
|
||||
};
|
||||
export const ROUND: Record<string, string> = {
|
||||
initial: STEEL,
|
||||
subsequent: STEEL_MID,
|
||||
no_data: NEUTRAL,
|
||||
};
|
||||
/** A PPV's groups: a cytology or histology level takes its category's colour. */
|
||||
export const PRIOR_CYTOLOGY: Record<string, string> = {
|
||||
ascus_plus: BLUE,
|
||||
lsil_plus: OCHRE,
|
||||
hsil_plus: RASPBERRY,
|
||||
no_data: NEUTRAL,
|
||||
};
|
||||
export const LEVEL: Record<string, string> = {
|
||||
cin1_plus: OCHRE,
|
||||
cin2_plus: RASPBERRY,
|
||||
carcinoma: PLUM,
|
||||
};
|
||||
export const CONFIRMED = '#6A8000';
|
||||
/** A median's bar and its quartile marks. */
|
||||
export const TINT = { bar: '#42A77E', mark: '#17324D' };
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
@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().caption) {
|
||||
<p class="state">{{ mode().caption }}</p>
|
||||
}
|
||||
@if (mode().heading) {
|
||||
<h4 class="heading">{{ mode().heading }}</h4>
|
||||
}
|
||||
@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">
|
||||
@for (t of [0, 25, 50, 75, 100]; track t) {
|
||||
<span [style.left.%]="t">{{ t }} %</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">{{ unit() }}: {{ group.total }}</span>
|
||||
@if (group.hint) {
|
||||
<span class="n">{{ group.hint }}</span>
|
||||
}
|
||||
</h4>
|
||||
@for (row of group.rows; track row.label) {
|
||||
<div class="row" [class.sub]="row.sub" [attr.data-category]="row.label">
|
||||
<span class="name">{{ row.label }}</span>
|
||||
<span class="track" aria-hidden="true">
|
||||
<span
|
||||
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 (table(); as t) {
|
||||
<table [attr.aria-label]="mode().label">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ mode().rowsLabel ?? '' }}</th>
|
||||
@for (h of t.head; track h) {
|
||||
<th>{{ h }}</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (row of t.rows; track row.label) {
|
||||
<tr [class.sub]="row.sub">
|
||||
<th scope="row">
|
||||
{{ row.label }}
|
||||
@if (row.hint) {
|
||||
<span class="hint">{{ row.hint }}</span>
|
||||
}
|
||||
@if (row.none) {
|
||||
<span class="hint">{{ row.none }}</span>
|
||||
} @else {
|
||||
<span class="track" aria-hidden="true">
|
||||
@for (p of row.segments ?? []; track $index) {
|
||||
<span
|
||||
class="bar"
|
||||
[style.width.%]="p.width"
|
||||
[style.background]="p.color"
|
||||
[attr.title]="p.title"
|
||||
></span>
|
||||
} @empty {
|
||||
<span
|
||||
class="bar"
|
||||
[style.margin-left.%]="row.offset"
|
||||
[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>
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
:host {
|
||||
--name-width: minmax(9rem, 16rem);
|
||||
--value-width: 8.5rem;
|
||||
display: block;
|
||||
min-width: 0;
|
||||
}
|
||||
:host(.compact) {
|
||||
overflow-x: auto;
|
||||
.title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.state {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 13px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
table {
|
||||
font-size: 13px;
|
||||
}
|
||||
thead th {
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
.title {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.headline {
|
||||
font-weight: 500;
|
||||
}
|
||||
.heading {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
mat-button-toggle-group {
|
||||
flex-wrap: wrap;
|
||||
margin: 4px 0;
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
font-weight: 400;
|
||||
padding: 4px 6px;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
thead th:first-child,
|
||||
th[scope='row'] {
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
width: 60%;
|
||||
}
|
||||
tr.sub th[scope='row'],
|
||||
.row.sub .name {
|
||||
padding-left: 1.25rem;
|
||||
}
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
}
|
||||
.track {
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
display: flex;
|
||||
height: 8px;
|
||||
position: relative;
|
||||
}
|
||||
.bar {
|
||||
background: #a8c243;
|
||||
display: block;
|
||||
flex: none;
|
||||
height: 100%;
|
||||
}
|
||||
.mark {
|
||||
background: #333;
|
||||
height: 12px;
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 2px;
|
||||
}
|
||||
.legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
font-size: 12px;
|
||||
gap: 4px 16px;
|
||||
i {
|
||||
display: inline-block;
|
||||
height: 10px;
|
||||
margin-right: 6px;
|
||||
width: 10px;
|
||||
}
|
||||
}
|
||||
.axis,
|
||||
.row {
|
||||
column-gap: 8px;
|
||||
display: grid;
|
||||
grid-template-columns: var(--name-width) 1fr var(--value-width);
|
||||
}
|
||||
.axis {
|
||||
font-size: 12px;
|
||||
margin: 12px 0 2px;
|
||||
}
|
||||
.ticks {
|
||||
height: 1.2em;
|
||||
position: relative;
|
||||
span {
|
||||
position: absolute;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
span:first-child {
|
||||
transform: none;
|
||||
}
|
||||
span:last-child {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
}
|
||||
.group {
|
||||
margin: 6px 0 14px;
|
||||
h4 {
|
||||
font-size: 0.95rem;
|
||||
margin: 0 0 4px;
|
||||
}
|
||||
.n {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.8em;
|
||||
font-weight: 400;
|
||||
margin-left: 8px;
|
||||
}
|
||||
}
|
||||
.row {
|
||||
align-items: center;
|
||||
font-size: 0.9rem;
|
||||
min-height: 22px;
|
||||
.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);
|
||||
height: 10px;
|
||||
}
|
||||
.fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
}
|
||||
.value {
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Component, computed, input, signal } from '@angular/core';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { Loading } from '../loading';
|
||||
import { bars, Mode, Read } from './bars';
|
||||
import { grouped, outcomes, shares, unavailable } from './groups';
|
||||
|
||||
/** A card read one mode at a time: its title, its headline, the toggle and the bars (or the
|
||||
* groups of bars). In a section with one selector for several cards, `view` picks the mode. */
|
||||
@Component({
|
||||
selector: 'app-readings',
|
||||
imports: [Loading, MatButtonToggleModule],
|
||||
host: { '[class.compact]': 'compact()' },
|
||||
templateUrl: './readings.html',
|
||||
styleUrl: './readings.scss',
|
||||
})
|
||||
export class Readings {
|
||||
readonly title = input.required<string>();
|
||||
readonly hideTitle = input(false);
|
||||
/** smaller type, for cards of tables with many columns */
|
||||
readonly compact = input(false);
|
||||
readonly headline = input('');
|
||||
/** the headline said under the figure instead */
|
||||
readonly foot = input('');
|
||||
readonly note = input('');
|
||||
readonly modes = input.required<Mode[]>();
|
||||
readonly view = input<string>();
|
||||
readonly loading = input(false);
|
||||
readonly read = input.required<Read>();
|
||||
|
||||
protected readonly chosen = signal('');
|
||||
protected readonly mode = computed(() => {
|
||||
const label = this.view() ?? this.chosen();
|
||||
return this.modes().find((m) => m.label === label) ?? this.modes()[0];
|
||||
});
|
||||
protected readonly missing = computed(() => unavailable(this.mode(), this.read()));
|
||||
protected readonly groups = computed(() => grouped(this.mode(), this.read()));
|
||||
protected readonly table = computed(
|
||||
() =>
|
||||
outcomes(this.mode(), this.read()) ??
|
||||
shares(this.mode(), this.read()) ??
|
||||
bars(this.mode(), this.read()),
|
||||
);
|
||||
/** "Pacientes", "Reportes": what a group's records are called, capitalised. */
|
||||
protected readonly unit = computed(() => {
|
||||
const m = this.mode();
|
||||
const unit = m.kind === 'grouped' ? m.unit : '';
|
||||
return unit.charAt(0).toUpperCase() + unit.slice(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, 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 { detail, formatScore, 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 (optionally read through one selector), or one of
|
||||
* several at a time (as sections, or as one card). */
|
||||
@Component({
|
||||
selector: 'app-section',
|
||||
imports: [MatButtonToggleModule, MatCardModule, NgTemplateOutlet, Readings],
|
||||
template: `
|
||||
@let s = section();
|
||||
@if (s.kind === 'readings') {
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
<ng-container *ngTemplateOutlet="card; context: { $implicit: s }" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
} @else if (s.kind === 'choice' && s.card) {
|
||||
@let open = chosen() || s.choices[0].label;
|
||||
<mat-card appearance="outlined">
|
||||
<mat-card-content>
|
||||
<h3 class="title">{{ s.title }}</h3>
|
||||
<ng-container *ngTemplateOutlet="toggle; context: { $implicit: s, open }" />
|
||||
@for (c of s.choices; track c.label) {
|
||||
@if (c.label === open) {
|
||||
<ng-container
|
||||
*ngTemplateOutlet="card; context: { $implicit: c.section, bare: true }"
|
||||
/>
|
||||
}
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
} @else {
|
||||
<h2>{{ s.title }}</h2>
|
||||
@if (s.kind === 'columns') {
|
||||
@let view = picked() || s.views?.[0];
|
||||
@if (s.views) {
|
||||
<mat-button-toggle-group
|
||||
[attr.aria-label]="s.viewsLabel ?? s.title"
|
||||
[value]="view"
|
||||
(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 ? view : undefined" />
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
@let open = chosen() || s.choices[0].label;
|
||||
<ng-container *ngTemplateOutlet="toggle; context: { $implicit: s, open }" />
|
||||
@for (c of s.choices; track c.label) {
|
||||
@if (c.label === open) {
|
||||
<app-section [section]="c.section" [of]="of()" />
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
<ng-template #toggle let-s let-open="open">
|
||||
<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>
|
||||
</ng-template>
|
||||
<ng-template #card let-c let-bare="bare">
|
||||
<app-readings
|
||||
[title]="c.title"
|
||||
[hideTitle]="!!bare"
|
||||
[compact]="!!bare || compact(c)"
|
||||
[headline]="c.footnote ? '' : headline(c)"
|
||||
[foot]="c.footnote ? headline(c).replace(' · ', ', ').replace('. IC', ', IC') : ''"
|
||||
[note]="c.note ?? ''"
|
||||
[modes]="c.modes"
|
||||
[view]="view()"
|
||||
[loading]="of().loading"
|
||||
[read]="of().reading"
|
||||
/>
|
||||
</ng-template>
|
||||
`,
|
||||
styles: `
|
||||
:host {
|
||||
display: block;
|
||||
margin-top: 24px;
|
||||
min-width: 0;
|
||||
}
|
||||
.title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
mat-button-toggle-group {
|
||||
flex-wrap: wrap;
|
||||
margin: 4px 0 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 following its section's selector takes (its label). */
|
||||
readonly view = input<string>();
|
||||
protected readonly picked = signal('');
|
||||
protected readonly chosen = signal('');
|
||||
|
||||
/** A card whose modes say what their rows count reads in smaller type. */
|
||||
protected compact(c: ReadingsCard): boolean {
|
||||
return c.modes.some((m) => !!m.heading);
|
||||
}
|
||||
|
||||
/** A card's headline: its measure's score and its counts, in its own unit. */
|
||||
protected headline(c: ReadingsCard): string {
|
||||
const measure = c.headline && this.of().measure(c.headline);
|
||||
const r = c.headline && this.of().reading(c.headline);
|
||||
if (!measure || !r) return '';
|
||||
const words = detail(measure, r, c.unit);
|
||||
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@ import type { Measure } from 'fhir/r4';
|
||||
import { DOMAINS } from '../app';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import { code, label } from '../fhir';
|
||||
import { periodTypes, STRATA } from './measures';
|
||||
import { STRATA } from './labels';
|
||||
import { periodTypes } from './measures';
|
||||
|
||||
const SCORING: Record<string, string> = {
|
||||
proportion: 'Proporción',
|
||||
@@ -15,6 +16,29 @@ const IMPROVEMENT: Record<string, string> = {
|
||||
decrease: 'Mejor si baja',
|
||||
};
|
||||
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
|
||||
/** Where the NCI reference risks come from. */
|
||||
const NCI = [
|
||||
[
|
||||
'https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/',
|
||||
'Egemen y colaboradores: estimaciones que sustentan las guías (2020).',
|
||||
],
|
||||
[
|
||||
'https://doi.org/10.1097/LGT.0000000000000528',
|
||||
'Cheung y colaboradores: métodos de estimación (2020).',
|
||||
],
|
||||
[
|
||||
'https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/',
|
||||
'Perkins y colaboradores: guías de manejo ASCCP 2019.',
|
||||
],
|
||||
[
|
||||
'https://data.lhncbc.nlm.nih.gov/public/cervixca/AdditionalTables.zip',
|
||||
'LHNCBC: libros de tablas adicionales.',
|
||||
],
|
||||
[
|
||||
'https://web.archive.org/web/20240710095705/https://lhncbc.nlm.nih.gov/LHC-research/LHC-projects/image-processing/cervixca.html',
|
||||
'LHNCBC: página archivada de las tablas, 10 de julio de 2024.',
|
||||
],
|
||||
].map(([url, citation]) => ({ url, citation }));
|
||||
|
||||
/** "Datos y definiciones" as the old tab: the domain's information, then its catalog, each
|
||||
* indicator opening to what it is (how it scores, which way is better, its periods and
|
||||
@@ -31,6 +55,23 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
|
||||
Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
|
||||
espécimen fue insatisfactorio.
|
||||
</p>
|
||||
<h4>Riesgos de referencia NCI</h4>
|
||||
<p>
|
||||
Los riesgos de referencia corresponden a la cohorte Kaiser Permanente Northern
|
||||
California (2003–2017, pacientes de 25 a 65 años). Las guías ASCCP deciden la conducta
|
||||
con el riesgo de CIN3+. Los riesgos publicados de CIN2+ y cáncer son resultados
|
||||
complementarios; no son directamente comparables con las estimaciones institucionales
|
||||
porque no están validados para la población de esta plataforma.
|
||||
</p>
|
||||
<ul>
|
||||
@for (source of nci; track source.url) {
|
||||
<li>
|
||||
<a [href]="source.url" target="_blank" rel="noopener noreferrer">{{
|
||||
source.citation
|
||||
}}</a>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
@if (available().length) {
|
||||
<p>Periodicidad disponible: {{ available().join(', ') }}.</p>
|
||||
@@ -48,6 +89,22 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
|
||||
@if (m.description) {
|
||||
<p>{{ m.description }}</p>
|
||||
}
|
||||
@if (m.relatedArtifact?.length) {
|
||||
<h4>Referencias</h4>
|
||||
<ul>
|
||||
@for (source of m.relatedArtifact; track $index) {
|
||||
<li>
|
||||
@if (source.url) {
|
||||
<a [href]="source.url" target="_blank" rel="noopener noreferrer">{{
|
||||
source.citation || source.display || source.url
|
||||
}}</a>
|
||||
} @else {
|
||||
{{ source.citation || source.display }}
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
<h4>Cálculo</h4>
|
||||
<p>
|
||||
{{ scoring[code(m.scoring) ?? ''] }}
|
||||
@@ -116,6 +173,7 @@ const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual
|
||||
`,
|
||||
})
|
||||
export class TabDefiniciones {
|
||||
protected readonly nci = NCI;
|
||||
readonly domain = input.required<string>();
|
||||
readonly measures = input.required<Measure[]>();
|
||||
protected readonly scoring = SCORING;
|
||||
|
||||
@@ -34,18 +34,25 @@
|
||||
|
||||
@if (reports.error()) {
|
||||
<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>
|
||||
</div>
|
||||
}
|
||||
@if (page(); as pg) {
|
||||
@if (applied(); as period) {
|
||||
@if (pg.clinicalFirst) {
|
||||
<ng-container *ngTemplateOutlet="clinicalView; context: { $implicit: pg, period: period }" />
|
||||
}
|
||||
<section class="card opportunity" aria-labelledby="opportunity-title">
|
||||
<div class="section-head">
|
||||
<h2 id="opportunity-title">Indicadores de oportunidad</h2>
|
||||
<span class="period">Periodo {{ period }}</span>
|
||||
</div>
|
||||
<div class="kpis">
|
||||
<div
|
||||
class="kpis"
|
||||
[style.--kpi-cols-md]="kpiColumns(pg.kpis.length)[0]"
|
||||
[style.--kpi-cols-lg]="kpiColumns(pg.kpis.length)[1]"
|
||||
>
|
||||
@for (k of pg.kpis; track k.title) {
|
||||
<mat-card appearance="outlined" class="kpi" [attr.data-measure]="k.measure ?? null">
|
||||
<mat-card-content>
|
||||
@@ -53,7 +60,13 @@
|
||||
@if (reports.isLoading() && k.measure) {
|
||||
<app-loading [what]="k.title.toLowerCase()" />
|
||||
} @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>
|
||||
}
|
||||
</mat-card-content>
|
||||
@@ -67,6 +80,12 @@
|
||||
}
|
||||
</section>
|
||||
|
||||
@if (!pg.clinicalFirst) {
|
||||
<ng-container *ngTemplateOutlet="clinicalView; context: { $implicit: pg, period: period }" />
|
||||
}
|
||||
}
|
||||
|
||||
<ng-template #clinicalView let-pg let-period="period">
|
||||
<section class="card clinical-page" aria-labelledby="clinical-title">
|
||||
<h2 id="clinical-title">Indicadores clínicos</h2>
|
||||
@for (section of pg.clinical; track $index) {
|
||||
@@ -75,19 +94,14 @@
|
||||
/>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</ng-template>
|
||||
|
||||
<ng-template #sectionView let-section let-period="period">
|
||||
@switch (section.kind) {
|
||||
@case ('route') {
|
||||
<h3 class="route-title">{{ section.title }}</h3>
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="los tiempos de la ruta" [figure]="true" />
|
||||
} @else if (routeOf(section); as fig) {
|
||||
<app-plot [figure]="fig" [height]="300" />
|
||||
} @else {
|
||||
<p class="state">Sin tiempos publicados en el periodo.</p>
|
||||
}
|
||||
@case ('readings')
|
||||
@case ('columns')
|
||||
@case ('choice') {
|
||||
<app-section [section]="section" [of]="of()" />
|
||||
}
|
||||
@case ('tea-summary') {
|
||||
@if (teaSummary(); as t) {
|
||||
@@ -152,14 +166,10 @@
|
||||
<mat-card-content>
|
||||
<h2 class="box-title">{{ b.title }}</h2>
|
||||
@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>
|
||||
} @else {
|
||||
<p class="state">Filtro general aplicado: {{ period }}</p>
|
||||
@if (section.subtitles) {
|
||||
<h2 class="box-subtitle">{{ measureTitle(b.measure) }}</h2>
|
||||
<p class="state">Figura: Caja de cuartiles</p>
|
||||
}
|
||||
@if (reports.isLoading()) {
|
||||
<app-loading what="la figura" [figure]="true" />
|
||||
} @else if (boxOf(b.measure); as fig) {
|
||||
@@ -173,15 +183,6 @@
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@case ('card') {
|
||||
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
|
||||
<mat-card-content>
|
||||
<h3 class="kpi-title">{{ section.title }}</h3>
|
||||
<div class="kpi-value">{{ kpiValue(section) }}</div>
|
||||
<div class="kpi-detail">{{ kpiNote(section) }}</div>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
@default {
|
||||
<mat-card appearance="outlined" class="figure-card">
|
||||
<mat-card-content>
|
||||
|
||||
@@ -42,13 +42,13 @@ h2 {
|
||||
|
||||
@media (min-width: 1000px) {
|
||||
.kpis {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-columns: repeat(var(--kpi-cols-md, 3), 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1350px) {
|
||||
.kpis {
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
grid-template-columns: repeat(var(--kpi-cols-lg, 5), 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,14 @@ h2 {
|
||||
font-size: 2rem;
|
||||
font-weight: 500;
|
||||
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 {
|
||||
@@ -213,12 +221,6 @@ h2.box-title {
|
||||
margin: 0 0 4px;
|
||||
}
|
||||
|
||||
h2.box-subtitle {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.empty-figure {
|
||||
align-items: center;
|
||||
border: 1px solid var(--color-border);
|
||||
@@ -238,10 +240,6 @@ h2.box-subtitle {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.kpi.closing {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.summary {
|
||||
margin-bottom: 24px;
|
||||
|
||||
|
||||
@@ -15,9 +15,6 @@ import {
|
||||
boxFigure,
|
||||
countBars,
|
||||
fill,
|
||||
nestedDonut,
|
||||
rateDots,
|
||||
routeFigure,
|
||||
scenarioBars,
|
||||
shareDonut,
|
||||
} from './figures';
|
||||
@@ -27,17 +24,17 @@ import {
|
||||
donut,
|
||||
formatScore,
|
||||
medians,
|
||||
name,
|
||||
periodLabel,
|
||||
periods,
|
||||
PeriodType,
|
||||
reading,
|
||||
Reading,
|
||||
scoring,
|
||||
STRATA,
|
||||
strataBars,
|
||||
} from './measures';
|
||||
import { name, STRATA } from './labels';
|
||||
import { Loading } from '../loading';
|
||||
import { ReadingsSection, Source } from './section';
|
||||
|
||||
/** The period's indicators: the timeliness KPIs, the screening route, and a card per
|
||||
* clinical measure with its figures. */
|
||||
@@ -52,6 +49,7 @@ import { Loading } from '../loading';
|
||||
MatCardModule,
|
||||
MatSelectModule,
|
||||
Plot,
|
||||
ReadingsSection,
|
||||
],
|
||||
templateUrl: './tab-indicadores.html',
|
||||
styleUrl: './tab-indicadores.scss',
|
||||
@@ -71,8 +69,7 @@ export class TabIndicadores {
|
||||
protected readonly layout = computed(
|
||||
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
|
||||
);
|
||||
protected readonly pending =
|
||||
'Este indicador aún no está publicado por el catálogo institucional.';
|
||||
protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
|
||||
/** 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()]);
|
||||
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
|
||||
@@ -202,6 +199,12 @@ export class TabIndicadores {
|
||||
return this.byName().get(code);
|
||||
}
|
||||
/** 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 {
|
||||
if (!k.measure) return k.value ?? '';
|
||||
const r = this.rd(k.measure);
|
||||
@@ -256,21 +259,23 @@ export class TabIndicadores {
|
||||
unusable: cat(rd('M29_CALIDAD_EEG'), 'bad'),
|
||||
};
|
||||
});
|
||||
protected measureTitle(code: string | undefined): string {
|
||||
return (code && this.byName().get(code)?.title) || '';
|
||||
}
|
||||
/** A clinical section's route or figures, drawn from the applied period's reports. */
|
||||
protected routeOf(section: Section): Figure | undefined {
|
||||
if (section.kind !== 'route') return undefined;
|
||||
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) }));
|
||||
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined;
|
||||
/** The cards' columns at medium and large widths: all in one row up to five, else in two. */
|
||||
protected kpiColumns(n: number): [number, number] {
|
||||
return [Math.min(n, 3), n <= 5 ? n : Math.ceil(n / 2)];
|
||||
}
|
||||
/** What a section of readings is drawn from. */
|
||||
protected readonly of = computed<Source>(() => {
|
||||
const found = this.loaded();
|
||||
return {
|
||||
loading: this.reports.isLoading(),
|
||||
reading: (code) => found?.get(code),
|
||||
measure: (code) => this.byName().get(code),
|
||||
};
|
||||
});
|
||||
protected figureOf(spec: FigureSpec): Figure | undefined {
|
||||
const r = this.rd(spec.measure);
|
||||
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
|
||||
switch (spec.kind) {
|
||||
case 'donut':
|
||||
return nestedDonut(r, spec.catalog, spec.center);
|
||||
case 'share-donut':
|
||||
return shareDonut(r, spec.catalog, spec.center);
|
||||
case 'counts':
|
||||
@@ -281,8 +286,6 @@ export class TabIndicadores {
|
||||
return ageShare(r, spec.names[0]);
|
||||
case 'scenario-bars':
|
||||
return scenarioBars(r, spec.catalog, spec.stratum, name);
|
||||
case 'rates':
|
||||
return rateDots(r, spec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<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>
|
||||
<div class="filters">
|
||||
<app-patient-search [(value)]="search" (searched)="pageIndex.set(0)" />
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Fecha de corte</mat-label>
|
||||
<input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" />
|
||||
@@ -124,7 +125,7 @@
|
||||
<th>Paciente</th>
|
||||
<th>Grupo de edad</th>
|
||||
<th>Estado del caso</th>
|
||||
<th>Último EEG</th>
|
||||
<th>Paso</th>
|
||||
<th class="num">Puntaje M-CHAT</th>
|
||||
<th class="num">CSS ADOS-2</th>
|
||||
<th>Estatus de EEG</th>
|
||||
@@ -140,14 +141,14 @@
|
||||
</td>
|
||||
<td>{{ r.ageGroup ? ageLabel(r.ageGroup) : 'Sin dato' }}</td>
|
||||
<td>{{ cases[r.case] ?? r.case }}</td>
|
||||
<td>{{ r.lastEeg ?? '—' }}</td>
|
||||
<td>{{ label(r.step) }}</td>
|
||||
<td class="num">{{ r.mchat ?? '—' }}</td>
|
||||
<td class="num">{{ r.css ?? '—' }}</td>
|
||||
<td>{{ eegStatuses[r.eegStatus] ?? r.eegStatus }}</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<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>
|
||||
}
|
||||
</tbody>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { METRIC_NAMES } from '../eeg-labels';
|
||||
import { KeyValuePipe } from '@angular/common';
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
@@ -10,7 +11,8 @@ import type { Patient } from 'fhir/r4';
|
||||
import { EXT, Fhir, resources } from '../fhir';
|
||||
import { Loading } from '../loading';
|
||||
import { ageLabel } from './figures';
|
||||
import { name } from './measures';
|
||||
import { name } from './labels';
|
||||
import { matchesSearch, PatientSearch } from './patient-search';
|
||||
|
||||
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */
|
||||
export interface TeaRow {
|
||||
@@ -19,9 +21,10 @@ export interface TeaRow {
|
||||
ageGroup: string;
|
||||
case: string;
|
||||
status: string;
|
||||
/** the last step she reached by the cut-off (tea-step) */
|
||||
step: string;
|
||||
eegStatus: string;
|
||||
alterations: string[];
|
||||
lastEeg?: string;
|
||||
mchat?: number;
|
||||
css?: number;
|
||||
}
|
||||
@@ -36,10 +39,10 @@ export function teaRow(p: Patient): TeaRow {
|
||||
ageGroup: has(p, 'tea-age-group')[0]?.valueString ?? '',
|
||||
case: coded('tea-case'),
|
||||
status: coded('follow-up-status'),
|
||||
eegStatus: coded('tea-eeg-status'),
|
||||
step: coded('tea-step'),
|
||||
eegStatus: coded('tea-eeg-result'),
|
||||
alterations: has(p, 'tea-eeg-alteration').map((e) => e.valueCoding?.code ?? ''),
|
||||
lastEeg: has(p, 'tea-last-eeg')[0]?.valueDate,
|
||||
mchat: has(p, 'mchat-score')[0]?.valueInteger,
|
||||
mchat: has(p, 'mchat-score')[0]?.valueDecimal,
|
||||
css: has(p, 'ados2-css')[0]?.valueInteger,
|
||||
};
|
||||
}
|
||||
@@ -60,21 +63,26 @@ const EEG_STATUS: Record<string, string> = {
|
||||
normal: 'Normal',
|
||||
abnormal: 'Anormal',
|
||||
no_valid_eeg: 'Sin EEG válido',
|
||||
not_scored: 'Sin analizar',
|
||||
};
|
||||
const CASE: Record<string, string> = {
|
||||
confirmed: 'Diagnóstico confirmado',
|
||||
in_process: 'En proceso',
|
||||
not_confirmed: 'Sin TEA',
|
||||
};
|
||||
/** `theta_power:above` → "theta_power (aumentado)". */
|
||||
export const alteration = (a: string) =>
|
||||
a.replace(/:(above|below)$/, (_, s) => (s === 'above' ? ' (aumentado)' : ' (disminuido)'));
|
||||
/** An EEG metric outside its age curve (`spindles`), or with its side (`spindles:above`). */
|
||||
export const alteration = (a: string) => {
|
||||
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,
|
||||
* filtered as the old page filtered them. */
|
||||
@Component({
|
||||
selector: 'app-tab-riesgos-tea',
|
||||
imports: [
|
||||
PatientSearch,
|
||||
FormsModule,
|
||||
KeyValuePipe,
|
||||
Loading,
|
||||
@@ -100,6 +108,8 @@ export class TabRiesgosTea {
|
||||
protected readonly caseState = signal('');
|
||||
protected readonly altered = signal('');
|
||||
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);
|
||||
/** The query as last asked for ("Consultar"). */
|
||||
private readonly asked = signal({ cutoff: '', window: 3 });
|
||||
@@ -141,7 +151,13 @@ export class TabRiesgosTea {
|
||||
(!band || (r.mchat !== undefined && band.test(r.mchat))) &&
|
||||
(!level || (r.css !== undefined && level.test(r.css))) &&
|
||||
(!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(() =>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<form class="filters card" (submit)="$event.preventDefault()">
|
||||
<app-patient-search [(value)]="search" />
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Fecha de corte</mat-label>
|
||||
<input
|
||||
@@ -9,6 +10,30 @@
|
||||
name="cutoff"
|
||||
/>
|
||||
</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-label>Ventana de meses</mat-label>
|
||||
<mat-select [value]="window()" (selectionChange)="window.set($event.value)">
|
||||
@@ -50,7 +75,26 @@
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button
|
||||
mat-stroked-button
|
||||
type="button"
|
||||
[disabled]="saving() || !applied()"
|
||||
(click)="save('xlsx')"
|
||||
>
|
||||
Exportar Excel
|
||||
</button>
|
||||
<button
|
||||
mat-stroked-button
|
||||
type="button"
|
||||
[disabled]="saving() || !applied()"
|
||||
(click)="save('pdf')"
|
||||
>
|
||||
Exportar PDF
|
||||
</button>
|
||||
</form>
|
||||
@if (saveError()) {
|
||||
<p class="muted" role="alert">{{ saveError() }}</p>
|
||||
}
|
||||
|
||||
@if (error()) {
|
||||
<p class="muted" role="alert">
|
||||
@@ -71,8 +115,9 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Paciente</th>
|
||||
<th>Grupo de edad</th>
|
||||
<th>Edad</th>
|
||||
<th>Estatus de seguimiento</th>
|
||||
<th>Etapas</th>
|
||||
<th>Última citología</th>
|
||||
<th>Último resultado de VPH</th>
|
||||
<th>Última biopsia</th>
|
||||
@@ -86,24 +131,34 @@
|
||||
@for (row of rows(); track row.patient.id) {
|
||||
<tr>
|
||||
<td>
|
||||
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
|
||||
row.name ?? row.patient.id!.slice(0, 10)
|
||||
}}</a>
|
||||
<a
|
||||
[routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
|
||||
[queryParams]="{ corte: applied(), citologia: row.cytology?.date }"
|
||||
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
|
||||
>
|
||||
@if (row.curp) {
|
||||
<div class="muted curp">{{ row.curp }}</div>
|
||||
}
|
||||
</td>
|
||||
<td>{{ row.ageGroup }}</td>
|
||||
<td>
|
||||
{{ row.age ?? 'No disponible' }}
|
||||
<small>Grupo: {{ row.ageGroup }}</small>
|
||||
</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>
|
||||
@if (row.cytology; as c) {
|
||||
{{
|
||||
c.result
|
||||
? name(c.result)
|
||||
: c.adequacy === 'unsatisfactory'
|
||||
? 'Insatisfactoria'
|
||||
: 'Pendiente'
|
||||
}}
|
||||
{{ result(c) }}
|
||||
<small>Fecha: {{ c.date }}</small>
|
||||
<small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
|
||||
} @else {
|
||||
@@ -153,10 +208,17 @@
|
||||
<td>{{ latest(row) ?? 'No disponible' }}</td>
|
||||
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
@if (opened() === row.patient.id) {
|
||||
<tr class="stage-detail">
|
||||
<td colspan="11"><app-stages [stages]="row.stages" [detail]="true" /></td>
|
||||
</tr>
|
||||
}
|
||||
} @empty {
|
||||
<tr>
|
||||
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
|
||||
</tr>
|
||||
@if (page() && !loading()) {
|
||||
<tr>
|
||||
<td colspan="11" class="muted">No hay registros para los filtros aplicados.</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
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 {
|
||||
overflow-x: auto;
|
||||
padding: 0;
|
||||
@@ -43,6 +48,7 @@ a {
|
||||
|
||||
.worklist td small {
|
||||
display: block;
|
||||
white-space: nowrap;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font-size: 0.8em;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
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 { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
@@ -8,9 +16,13 @@ import { MatSelectModule } from '@angular/material/select';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import type { Bundle } from 'fhir/r4';
|
||||
import { Fhir } from '../fhir';
|
||||
import { Row, rows, windowStart } from './follow-up';
|
||||
import { saveExcel, savePdf } from '../export';
|
||||
import { Stages } from '../paciente/stages';
|
||||
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 { name } from './measures';
|
||||
import { name } from './labels';
|
||||
|
||||
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
|
||||
|
||||
@@ -19,6 +31,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
|
||||
@Component({
|
||||
selector: 'app-tab-riesgos',
|
||||
imports: [
|
||||
PatientSearch,
|
||||
DecimalPipe,
|
||||
FormsModule,
|
||||
Loading,
|
||||
@@ -27,6 +40,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
|
||||
MatInputModule,
|
||||
MatSelectModule,
|
||||
RouterLink,
|
||||
Stages,
|
||||
],
|
||||
templateUrl: './tab-riesgos.html',
|
||||
styleUrl: './tab-riesgos.scss',
|
||||
@@ -41,29 +55,39 @@ export class TabRiesgos {
|
||||
protected readonly horizon = signal(5);
|
||||
protected readonly sort = signal('-recent');
|
||||
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. */
|
||||
private readonly moved = signal<Bundle | undefined>(undefined);
|
||||
|
||||
protected readonly statuses = STATUSES;
|
||||
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({
|
||||
params: () => ({
|
||||
domain: this.domain(),
|
||||
'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 } }) => {
|
||||
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
|
||||
loader: ({ params: { domain, query, size } }) => {
|
||||
this.moved.set(undefined);
|
||||
return this.fhir.search(domain, 'Patient', {
|
||||
...params,
|
||||
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
|
||||
'_include:iterate': 'DiagnosticReport:result',
|
||||
});
|
||||
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
|
||||
},
|
||||
});
|
||||
protected readonly loading = signal(false);
|
||||
@@ -108,6 +132,42 @@ export class TabRiesgos {
|
||||
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> {
|
||||
this.saving.set(true);
|
||||
this.saveError.set('');
|
||||
try {
|
||||
const cutoff = this.applied();
|
||||
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
|
||||
const pages = await this.fhir.all(this.domain(), 'Patient', asked);
|
||||
const start = windowStart(cutoff, this.window());
|
||||
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon()));
|
||||
const sheet = followUpSheet(all, [
|
||||
['Ventana consultada', `${start} al ${cutoff}`],
|
||||
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
|
||||
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`],
|
||||
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`],
|
||||
['Búsqueda', this.search() || 'Ninguna'],
|
||||
['Horizonte de la probabilidad (años)', `${this.horizon()}`],
|
||||
]);
|
||||
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu');
|
||||
else await savePdf([sheet], 'seguimiento-cacu', true);
|
||||
} 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 {
|
||||
return !!this.page()?.link?.some((l) => l.relation === relation);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<form class="filters card" (submit)="$event.preventDefault()">
|
||||
<app-patient-search [(value)]="search" />
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Fecha de corte</mat-label>
|
||||
<input
|
||||
@@ -66,9 +67,11 @@
|
||||
@for (row of rows(); track row.patient.id) {
|
||||
<tr>
|
||||
<td>
|
||||
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
|
||||
row.name ?? row.patient.id!.slice(0, 10)
|
||||
}}</a>
|
||||
<a
|
||||
[routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
|
||||
[queryParams]="{ ventana: window(), corte: applied() }"
|
||||
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
|
||||
>
|
||||
@if (row.curp) {
|
||||
<div class="muted curp">{{ row.curp }}</div>
|
||||
}
|
||||
@@ -90,9 +93,11 @@
|
||||
<td>{{ priority(row.priority) }}</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr>
|
||||
<td colspan="6" class="muted">No hay registros para los filtros aplicados.</td>
|
||||
</tr>
|
||||
@if (page() && !loading()) {
|
||||
<tr>
|
||||
<td colspan="6" class="muted">No hay registros para los filtros aplicados.</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -110,4 +115,23 @@
|
||||
<button mat-stroked-button (click)="go('next')" [disabled]="!has('next') || loading()">
|
||||
Siguiente
|
||||
</button>
|
||||
<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>
|
||||
</div>
|
||||
@if (saveError()) {
|
||||
<p class="muted" role="alert">{{ saveError() }}</p>
|
||||
}
|
||||
|
||||
@@ -7,9 +7,12 @@ import { MatSelectModule } from '@angular/material/select';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import type { Bundle } from 'fhir/r4';
|
||||
import { Fhir } from '../fhir';
|
||||
import { saveExcel, savePdf } from '../export';
|
||||
import { camaRows, windowStart } from './follow-up';
|
||||
import { camaFollowUpSheet } from './follow-up-sheet';
|
||||
import { PatientSearch, patientSearch } from './patient-search';
|
||||
import { Loading } from '../loading';
|
||||
import { name, PRIORITY } from './measures';
|
||||
import { name, PRIORITY } from './labels';
|
||||
|
||||
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
|
||||
|
||||
@@ -18,6 +21,7 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy
|
||||
@Component({
|
||||
selector: 'app-tab-seguimiento',
|
||||
imports: [
|
||||
PatientSearch,
|
||||
FormsModule,
|
||||
Loading,
|
||||
MatButtonModule,
|
||||
@@ -37,27 +41,31 @@ export class TabSeguimiento {
|
||||
protected readonly window = signal(3);
|
||||
protected readonly status = signal<string>('');
|
||||
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);
|
||||
|
||||
protected readonly statuses = STATUSES;
|
||||
protected readonly name = name;
|
||||
protected readonly priority = (code: string) => PRIORITY[code] ?? code;
|
||||
|
||||
protected readonly saving = signal(false);
|
||||
protected readonly saveError = signal('');
|
||||
/** The list as it is asked for, whatever the page. */
|
||||
private readonly query = computed(() => ({
|
||||
'follow-up-window': this.window(),
|
||||
...patientSearch(this.search()),
|
||||
'follow-up-cutoff': this.cutoff() || undefined,
|
||||
'follow-up-status': this.status() || undefined,
|
||||
_revinclude: ['DiagnosticReport:subject'],
|
||||
'_include:iterate': 'DiagnosticReport:result',
|
||||
}));
|
||||
|
||||
private readonly first = resource({
|
||||
params: () => ({
|
||||
domain: this.domain(),
|
||||
'follow-up-window': this.window(),
|
||||
'follow-up-cutoff': this.cutoff() || undefined,
|
||||
'follow-up-status': this.status() || undefined,
|
||||
_count: this.size(),
|
||||
}),
|
||||
loader: ({ params: { domain, ...params } }) => {
|
||||
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
|
||||
loader: ({ params: { domain, query, size } }) => {
|
||||
this.moved.set(undefined);
|
||||
return this.fhir.search(domain, 'Patient', {
|
||||
...params,
|
||||
_revinclude: ['DiagnosticReport:subject'],
|
||||
'_include:iterate': 'DiagnosticReport:result',
|
||||
});
|
||||
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
|
||||
},
|
||||
});
|
||||
protected readonly loading = signal(false);
|
||||
@@ -86,6 +94,32 @@ export class TabSeguimiento {
|
||||
protected readonly pageCount = computed(() =>
|
||||
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
|
||||
);
|
||||
/** The whole list, not the page shown, as a file. */
|
||||
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
|
||||
this.saving.set(true);
|
||||
this.saveError.set('');
|
||||
try {
|
||||
const cutoff = this.applied();
|
||||
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
|
||||
const pages = await this.fhir.all(this.domain(), 'Patient', asked);
|
||||
const sheet = camaFollowUpSheet(
|
||||
pages.flatMap((p) => camaRows(p, cutoff)),
|
||||
[
|
||||
['Ventana consultada', `${windowStart(cutoff, this.window())} al ${cutoff}`],
|
||||
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
|
||||
['Búsqueda', this.search() || 'Ninguna'],
|
||||
],
|
||||
this.priority,
|
||||
);
|
||||
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cama');
|
||||
else await savePdf([sheet], 'seguimiento-cama', true);
|
||||
} catch {
|
||||
this.saveError.set('No se generó el archivo.');
|
||||
} finally {
|
||||
this.saving.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected retry(): void {
|
||||
this.first.reload();
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import type { Measure, MeasureReport } from 'fhir/r4';
|
||||
import { Fhir, resources } from '../fhir';
|
||||
import { Loading } from '../loading';
|
||||
import { Figure, Plot } from '../plot';
|
||||
import { historyFigure } from './figures';
|
||||
import { periodLabel, periods, PeriodType, reading } from './measures';
|
||||
import { HISTORY, HistoryPanel } from './pages';
|
||||
import { periodLabel, periods, periodStart, PeriodType, reading } from './measures';
|
||||
import { HISTORY, HistoryPanel } from './history';
|
||||
|
||||
interface Drawn {
|
||||
panel: HistoryPanel;
|
||||
@@ -19,24 +21,37 @@ interface Drawn {
|
||||
* each measure period by period. */
|
||||
@Component({
|
||||
selector: 'app-tab-trazabilidad',
|
||||
imports: [Loading, MatButtonToggleModule, Plot],
|
||||
imports: [Loading, MatButtonModule, MatButtonToggleModule, MatSelectModule, Plot],
|
||||
template: `
|
||||
<section class="card filters" aria-labelledby="history-filters">
|
||||
<h2 id="history-filters" class="filters-title">Filtros</h2>
|
||||
<mat-button-toggle-group
|
||||
[value]="type()"
|
||||
(change)="type.set($event.value)"
|
||||
(change)="setType($event.value)"
|
||||
aria-label="Intervalo de análisis"
|
||||
>
|
||||
<mat-button-toggle value="month">Mensual</mat-button-toggle>
|
||||
<mat-button-toggle value="semester">Semestral</mat-button-toggle>
|
||||
</mat-button-toggle-group>
|
||||
@if (domain() !== 'tea') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [value]="chosen()" (selectionChange)="chosen.set($event.value)">
|
||||
@for (p of options(); track p) {
|
||||
<mat-option [value]="p">{{ p }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button mat-flat-button (click)="upTo.set(chosen())" [disabled]="chosen() === upTo()">
|
||||
Aplicar
|
||||
</button>
|
||||
}
|
||||
</section>
|
||||
@if (series.isLoading()) {
|
||||
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" />
|
||||
<app-loading what="el histórico" text="Cargando histórico…" />
|
||||
} @else if (series.error()) {
|
||||
<p class="muted" role="alert">
|
||||
No se pudo cargar la trazabilidad.
|
||||
No se pudo cargar el histórico.
|
||||
<button type="button" class="retry" (click)="series.reload()">Reintentar</button>
|
||||
</p>
|
||||
} @else {
|
||||
@@ -71,6 +86,12 @@ interface Drawn {
|
||||
padding: 16px 20px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.filters {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
}
|
||||
.filters-title {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
@@ -95,13 +116,28 @@ export class TabTrazabilidad {
|
||||
readonly domain = input.required<string>();
|
||||
readonly measures = input.required<Measure[]>();
|
||||
protected readonly type = signal<PeriodType>('month');
|
||||
protected readonly options = computed(() => periods(this.type()));
|
||||
/** The period the history ends in (CaCu, CaMa): the chosen one, once applied. */
|
||||
protected readonly chosen = signal(periods('month')[0]);
|
||||
protected readonly upTo = signal(periods('month')[0]);
|
||||
|
||||
protected setType(type: PeriodType): void {
|
||||
this.type.set(type);
|
||||
this.chosen.set(this.options()[0]);
|
||||
this.upTo.set(this.options()[0]);
|
||||
}
|
||||
|
||||
protected readonly series = resource({
|
||||
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
|
||||
params: () => ({
|
||||
domain: this.domain(),
|
||||
type: this.type(),
|
||||
measures: this.measures(),
|
||||
upTo: this.upTo(),
|
||||
}),
|
||||
loader: async ({ params }) => {
|
||||
const history = HISTORY[params.domain];
|
||||
if (!history) return [];
|
||||
const asked = periods(params.type).reverse();
|
||||
const asked = periods(params.type, 6, periodStart(params.upTo)).reverse();
|
||||
return Promise.all(
|
||||
history.panels.map(async (panel) => {
|
||||
const measure = params.measures.find((m) => m.name === panel.measure);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Api } from '../api/api';
|
||||
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import { scenarioFigure } from '../gobernanza/figures';
|
||||
import type { ScenarioFactors } from './factores';
|
||||
import type { Model } from './record';
|
||||
import { combinationOf, noCurveText, sortUndrawn, survivalFigure } from './survival';
|
||||
import { figureChoices } from './curve-chooser';
|
||||
|
||||
type Report = Record<string, any> | null | undefined;
|
||||
const count = (n: number) => n.toLocaleString('es-MX');
|
||||
|
||||
/** A model version's report, by name. */
|
||||
function report(api: Api, domain: string, model: Model, which: string): Promise<Report> {
|
||||
return api.invoke(readReport$Json, {
|
||||
domain: domain as Domain,
|
||||
name: model.model.split('.')[1],
|
||||
version: model.version,
|
||||
report: which,
|
||||
}) as Promise<Report>;
|
||||
}
|
||||
|
||||
/** The names of the methods the figures draw, each once. */
|
||||
const methods = (figures: { figure: { data: { name?: string }[] } }[]) =>
|
||||
[
|
||||
...new Set(figures.flatMap((f) => f.figure.data.map((t) => t.name)).filter((n) => !!n)),
|
||||
] as string[];
|
||||
|
||||
/** "Análisis de supervivencia" or "de recurrencia": the curves of her clinical scenarios from the
|
||||
* report of the model version that scored her, and the risk factors of those scenarios. CaCu says
|
||||
* apart a scenario the report lists as short of deaths from one it does not mention. */
|
||||
export async function analysis(api: Api, domain: string, m: Model) {
|
||||
const mine = (all: any[] = []) => all.filter((e) => m.scenarios.includes(e.escenario));
|
||||
if (m.model.endsWith('.recurrence')) {
|
||||
const r = (await report(api, domain, m, 'interpretability'))?.['recurrencia'] ?? {};
|
||||
const technical = await report(api, domain, m, 'technical_validation');
|
||||
const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen'];
|
||||
const figures = mine(r['escenarios']).map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${count(e.n)}, recaídas = ${count(e.recaidas)})`,
|
||||
e,
|
||||
r['horizons_months'],
|
||||
'Supervivencia libre de recaída',
|
||||
),
|
||||
);
|
||||
const none = { unavailable: [], insufficient: [], missing: [], methods: [] };
|
||||
return {
|
||||
...none,
|
||||
factors: mine(summary?.['filas']) as ScenarioFactors[],
|
||||
scenarios: m.scenarios,
|
||||
figures,
|
||||
};
|
||||
}
|
||||
const found = await report(api, domain, m, 'interpretability');
|
||||
const drawn = mine(found?.['escenarios']);
|
||||
const figures = drawn.map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${count(e.n)}, fallecidos = ${count(e.fallecidos)})`,
|
||||
e,
|
||||
e.horizons_months,
|
||||
'Supervivencia S(t)',
|
||||
),
|
||||
);
|
||||
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
|
||||
const cacu = domain === 'cacu';
|
||||
return {
|
||||
factors: mine(found?.['factores_escenarios']) as ScenarioFactors[],
|
||||
scenarios: m.scenarios,
|
||||
figures,
|
||||
unavailable: cacu ? [] : undrawn,
|
||||
...(cacu ? sortUndrawn(found, undrawn) : { insufficient: [], missing: [] }),
|
||||
methods: methods(figures),
|
||||
};
|
||||
}
|
||||
export type Analysis = Awaited<ReturnType<typeof analysis>>;
|
||||
|
||||
/** CaCu: the Kaplan-Meier of the patients who share all her values, from the survival report of
|
||||
* the version that scored her; or why there is none. */
|
||||
export async function combination(api: Api, m: Model & { inputs: Record<string, unknown> }) {
|
||||
const found = await report(api, 'cacu', m, 'interpretability');
|
||||
const mine = combinationOf(found, m.inputs);
|
||||
return mine?.km
|
||||
? { n: mine.n, deaths: mine.fallecidos, curves: figureChoices(survivalFigure(mine)) }
|
||||
: { missing: noCurveText(found, mine) };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { ANTECEDENTS } from './record-groups';
|
||||
|
||||
/** CaCu: what each cytology's form declares of her (the one she was opened at first), by day.
|
||||
* Statements of the form, not confirmed diagnoses. */
|
||||
@Component({
|
||||
selector: 'app-antecedents',
|
||||
imports: [MatCardModule],
|
||||
template: `
|
||||
<mat-card appearance="outlined" data-section="antecedentes">
|
||||
<mat-card-header>
|
||||
<mat-card-title>Antecedentes y evaluación ginecológica</mat-card-title>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<p class="muted note">
|
||||
Datos declarados en el formulario de la citología: no son diagnósticos confirmados. Cada
|
||||
dato pertenece al formulario de la toma que se indica.
|
||||
</p>
|
||||
<h3>Citología cervical · toma {{ forms()[0].date }}</h3>
|
||||
<dl class="facts">
|
||||
@for (a of antecedents; track a.field) {
|
||||
<div>
|
||||
<dt>{{ a.title }}</dt>
|
||||
<dd>{{ forms()[0].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>
|
||||
<th>Toma</th>
|
||||
@for (a of antecedents; track a.field) {
|
||||
<th>{{ a.title }}</th>
|
||||
}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (o of forms().slice(1); track o.date) {
|
||||
<tr>
|
||||
<td class="nowrap">{{ o.date }}</td>
|
||||
@for (a of antecedents; track a.field) {
|
||||
<td>{{ o.values[a.field] ?? 'No documentado' }}</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
`,
|
||||
styleUrl: './paciente.scss',
|
||||
})
|
||||
export class Antecedents {
|
||||
readonly forms = input.required<{ date: string; values: Record<string, string> }[]>();
|
||||
protected readonly antecedents = ANTECEDENTS;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { DiagnosticReport, Patient } from 'fhir/r4';
|
||||
import { code, ext, Fhir } from '../fhir';
|
||||
import { ageGroup, CAMA_AGE_GROUPS, CamaRow, camaRows } from '../indicadores/follow-up';
|
||||
import { name, PRIORITY } from '../indicadores/labels';
|
||||
import { PatientRecord, results, shown } from './record';
|
||||
|
||||
interface Listed {
|
||||
window: number;
|
||||
/** the cut-off the list applied */
|
||||
cutoff: string;
|
||||
row?: CamaRow;
|
||||
}
|
||||
|
||||
/** Her row on CaMa's follow-up list, at the window and cut-off she was opened from. */
|
||||
export async function listedRow(
|
||||
fhir: Fhir,
|
||||
{ id, window, cutoff }: { id: string; window: number; cutoff?: string },
|
||||
): Promise<Listed> {
|
||||
const page = await fhir.search('cama', '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] };
|
||||
}
|
||||
|
||||
/** What the old record's card said of her: her row on the list (on it or not), her own latest
|
||||
* mammogram and biopsy. */
|
||||
export function camaSummary(d: PatientRecord, found: Listed) {
|
||||
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 && results(d, r).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,
|
||||
};
|
||||
}
|
||||
type Summary = ReturnType<typeof camaSummary> | undefined;
|
||||
type Facts = [string, string | undefined][];
|
||||
|
||||
const sex = (p?: Patient) =>
|
||||
p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined;
|
||||
|
||||
/** Her data as the PDF lists them. */
|
||||
export function camaFacts(
|
||||
who: { name?: string; curp?: string; numbers: string[] },
|
||||
p: Patient | undefined,
|
||||
c: Summary,
|
||||
): Facts {
|
||||
return [
|
||||
['Nombre', who.name],
|
||||
['CURP', who.curp],
|
||||
['Expedientes', who.numbers.join(', ')],
|
||||
['Fecha de nacimiento', p?.birthDate],
|
||||
['Sexo', sex(p)],
|
||||
['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})`),
|
||||
],
|
||||
['Prioridad', c?.priority],
|
||||
['Días de mastografía a diagnóstico', c?.days?.toString()],
|
||||
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as Facts) : []),
|
||||
];
|
||||
}
|
||||
|
||||
/** Her latest mammogram and biopsy as the PDF lists them. */
|
||||
export const camaStudies = (c: Summary): Facts => [
|
||||
['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],
|
||||
];
|
||||
@@ -0,0 +1,84 @@
|
||||
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 until the user says otherwise */
|
||||
on: boolean;
|
||||
}
|
||||
export type Draw = (ids: Set<string>) => Figure;
|
||||
|
||||
/** A figure's named curves as choices, all on; a trace with no legend of its own (a band) goes
|
||||
* with the named one 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) ?? []) }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Curves to compare on one plot, each chosen or not, with what the chosen ones assume. */
|
||||
@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 said(); 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>();
|
||||
readonly notes = input<(ids: Set<string>) => string[]>(() => []);
|
||||
/** the choices the user turned from their default */
|
||||
private readonly flipped = signal(new Set<string>());
|
||||
protected readonly chosen = computed(
|
||||
() =>
|
||||
new Set(
|
||||
this.choices()
|
||||
.filter((c) => c.on !== this.flipped().has(c.id))
|
||||
.map((c) => c.id),
|
||||
),
|
||||
);
|
||||
protected readonly figure = computed(() => this.draw()(this.chosen()));
|
||||
protected readonly said = computed(() => this.notes()(this.chosen()));
|
||||
protected toggle(id: string) {
|
||||
const next = new Set(this.flipped());
|
||||
if (!next.delete(id)) next.add(id);
|
||||
this.flipped.set(next);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import type { Parameters, ParametersParameter } from 'fhir/r4';
|
||||
import { currency, eligibilityFailure, eligibilityView, ineligibility } from './eligibility';
|
||||
|
||||
const visit = (scenario: string, day: string, eligible: boolean, ...criteria: string[]) => ({
|
||||
name: 'candidate',
|
||||
part: [
|
||||
{ name: 'scenario', valueCoding: { code: scenario } },
|
||||
{ name: 'index-date', valueDate: day },
|
||||
{ name: 'eligible', valueBoolean: eligible },
|
||||
...criteria.map((code) => ({ name: 'criterion', valueCoding: { code } })),
|
||||
],
|
||||
});
|
||||
const answer = (...candidates: ParametersParameter[]): Parameters => ({
|
||||
resourceType: 'Parameters',
|
||||
parameter: [{ name: 'status', valueCode: 'evaluated' }, ...candidates],
|
||||
});
|
||||
|
||||
describe('eligibility', () => {
|
||||
it('keeps each visit with its own decision, latest first, its reasons as the screens say them', () => {
|
||||
const state = eligibilityView(
|
||||
answer(
|
||||
visit('pre_colposcopy', '2025-01-10', true),
|
||||
visit('pre_colposcopy', '2026-02-01', false, 'hysterectomy', 'brand_new'),
|
||||
),
|
||||
);
|
||||
expect(state).toEqual({
|
||||
kind: 'evaluated',
|
||||
visits: [
|
||||
{
|
||||
scenario: 'pre_colposcopy',
|
||||
indexDate: '2026-02-01',
|
||||
eligible: false,
|
||||
reasons: ['Histerectomía previa al índice', 'brand_new'],
|
||||
},
|
||||
{ scenario: 'pre_colposcopy', indexDate: '2025-01-10', eligible: true, reasons: [] },
|
||||
],
|
||||
});
|
||||
});
|
||||
it('never reads a malformed answer, or a failure, as a decision', () => {
|
||||
expect(eligibilityView(answer({ name: 'candidate', part: [] })).kind).toBe('unavailable');
|
||||
expect(
|
||||
eligibilityView({
|
||||
resourceType: 'Parameters',
|
||||
parameter: [{ name: 'status', valueCode: 'no_candidate' }],
|
||||
}).kind,
|
||||
).toBe('none');
|
||||
const failed = (status: number) => eligibilityFailure(new HttpErrorResponse({ status }));
|
||||
expect([409, 404, 500].map((s) => failed(s).kind)).toEqual(['gold', 'unavailable', 'error']);
|
||||
});
|
||||
it('says why she has no estimate from the latest visit of her scenario by the day', () => {
|
||||
const state = eligibilityView(
|
||||
answer(
|
||||
visit('surveillance', '2025-03-01', false, 'under_18'),
|
||||
visit('pre_colposcopy', '2026-05-01', true),
|
||||
),
|
||||
);
|
||||
expect(ineligibility(state, 'pre_colposcopy', '2026-06-01')).toBeUndefined();
|
||||
expect(ineligibility(state, 'pre_colposcopy', '2026-01-01')).toBe(
|
||||
'No disponible por: Edad menor de 18 años al índice.',
|
||||
);
|
||||
expect(ineligibility(state, 'post_treatment', '2026-06-01')).toBe(
|
||||
'No disponible por: paciente ya tratada.',
|
||||
);
|
||||
});
|
||||
it('says the cytology the estimate speaks of, and a later one it does not', () => {
|
||||
const risk = [{ model: 'cacu.cin2_pre_colposcopy', index: '2026-01-10T00:00:00' }];
|
||||
expect(currency(risk, ['2026-01-10']).note).toBe('Estimación de la citología del 2026-01-10.');
|
||||
expect(currency(risk, ['2026-03-01']).note).toContain('posterior, del 2026-03-01');
|
||||
const post = [{ model: 'cacu.cin2_post_colposcopy', index: '2026-01-10' }];
|
||||
expect(currency(post, ['2026-03-01']).excluded).toContain('primera visita poscolposcopía');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import type { Parameters, ParametersParameter } from 'fhir/r4';
|
||||
|
||||
/** The exclusion criteria `$eligibility` names, as the screens say them. */
|
||||
const CRITERIA: Record<string, string> = {
|
||||
hysterectomy: 'Histerectomía previa al índice',
|
||||
under_18: 'Edad menor de 18 años al índice',
|
||||
prior_outcome: 'Resultado CIN2+ previo al índice',
|
||||
no_index_result: 'Sin resultado de citología o VPH en la visita índice',
|
||||
unreported_biopsy: 'Biopsia solicitada sin resultado',
|
||||
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
|
||||
cancer_history: 'Antecedente de cáncer cervicouterino',
|
||||
prior_treatment: 'Tratamiento previo a la visita índice',
|
||||
no_referral: 'Sin citología de referencia previa a la colposcopia',
|
||||
referral_not_graded: 'Citología de referencia de bajo grado sin VPH positivo',
|
||||
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
|
||||
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
|
||||
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
|
||||
no_birth_date: 'Fecha de nacimiento desconocida',
|
||||
died_by_index: 'Defunción en o antes de la visita índice',
|
||||
not_evaluated: 'Escenario que la plataforma no evalúa por ahora',
|
||||
};
|
||||
|
||||
/** One indexed visit of a scenario: the backend's decision and its reasons, as they are. */
|
||||
export interface Visit {
|
||||
scenario: string;
|
||||
indexDate: string;
|
||||
eligible: boolean;
|
||||
reasons: string[];
|
||||
}
|
||||
/** What `$eligibility` answered; "eligible" is never inferred, only read. */
|
||||
export type EligibilityState =
|
||||
| { kind: 'loading' | 'error' | 'unavailable' | 'none' }
|
||||
| { kind: 'gold'; text?: string }
|
||||
| { kind: 'evaluated'; visits: Visit[] };
|
||||
|
||||
type Part = ParametersParameter;
|
||||
const parts = (of: Part[] | undefined, name: string) => (of ?? []).filter((p) => p.name === name);
|
||||
const first = (of: Part[] | undefined, name: string) => parts(of, name)[0];
|
||||
|
||||
/** The answer's visits, latest first. An answer outside the contract is "unavailable". */
|
||||
export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
|
||||
const top = answer?.resourceType === 'Parameters' ? answer.parameter : undefined;
|
||||
if (!Array.isArray(top)) return { kind: 'unavailable' };
|
||||
const status = first(top, 'status')?.valueCode;
|
||||
const candidates = parts(top, 'candidate');
|
||||
if (status === 'no_candidate' && !candidates.length) return { kind: 'none' };
|
||||
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
|
||||
const visits: Visit[] = [];
|
||||
for (const { part } of candidates) {
|
||||
const scenario = first(part, 'scenario')?.valueCoding?.code;
|
||||
const indexDate = first(part, 'index-date')?.valueDate;
|
||||
const eligible = first(part, 'eligible')?.valueBoolean;
|
||||
if (!scenario || !indexDate || eligible === undefined) return { kind: 'unavailable' };
|
||||
const reasons = parts(part, 'criterion')
|
||||
.map((r) => r.valueCoding)
|
||||
.filter((k) => !!k?.code)
|
||||
.map((k) => CRITERIA[k!.code!] ?? k!.display ?? k!.code!);
|
||||
visits.push({ scenario, indexDate, eligible, reasons });
|
||||
}
|
||||
return {
|
||||
kind: 'evaluated',
|
||||
visits: visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate)),
|
||||
};
|
||||
}
|
||||
|
||||
/** A failed answer: the gold to rebuild (409), no such operation for her (404, 422), or the call
|
||||
* itself (anything else). */
|
||||
export function eligibilityFailure(error: unknown): EligibilityState {
|
||||
if (!(error instanceof HttpErrorResponse)) return { kind: 'error' };
|
||||
if (error.status === 409) return { kind: 'gold', text: error.error?.issue?.[0]?.diagnostics };
|
||||
return error.status === 404 || error.status === 422 ? { kind: 'unavailable' } : { kind: 'error' };
|
||||
}
|
||||
|
||||
/** The scenarios that speak for a follow-up status, the first with a visit by the day wins. */
|
||||
const SPEAKS_FOR: Record<string, string[]> = {
|
||||
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
|
||||
post_colposcopy: ['post_colposcopy'],
|
||||
};
|
||||
|
||||
/** Why she has no risk estimate in her scenario by `day`; nothing when she is eligible or no visit
|
||||
* of it is known. A treated patient has none, whatever was indexed. */
|
||||
export function ineligibility(state: EligibilityState, status: string, day: string) {
|
||||
if (status === 'post_treatment') return 'No disponible por: paciente ya tratada.';
|
||||
if (state.kind !== 'evaluated') return undefined;
|
||||
for (const scenario of SPEAKS_FOR[status] ?? []) {
|
||||
const latest = state.visits.find((v) => v.scenario === scenario && v.indexDate <= day);
|
||||
if (latest)
|
||||
return latest.eligible ? undefined : `No disponible por: ${latest.reasons.join('; ')}.`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Which cytology her estimates speak of, against her latest by the cut-off: after the first
|
||||
* post-colposcopy visit nothing is evaluated; otherwise a later cytology is only said. */
|
||||
export function currency(estimates: { model: string; index: string }[], cytologies: string[]) {
|
||||
const sample = estimates
|
||||
.map((e) => e.index.slice(0, 10))
|
||||
.sort()
|
||||
.at(-1);
|
||||
if (!sample) return {};
|
||||
const latest = cytologies
|
||||
.map((d) => d.slice(0, 10))
|
||||
.sort()
|
||||
.at(-1);
|
||||
const said = `Estimación de la citología del ${sample}.`;
|
||||
if (!latest || latest <= sample) return { sample, note: said };
|
||||
if (estimates.some((e) => e.model.includes('post_colposcopy')))
|
||||
return {
|
||||
sample,
|
||||
excluded: `No disponible por: hay una citología posterior a la primera visita poscolposcopía (${latest}) y solo se evalúa esa primera visita.`,
|
||||
};
|
||||
return { sample, note: `${said} Hay una citología posterior, del ${latest}, que no se evalúa.` };
|
||||
}
|
||||
@@ -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),
|
||||
})),
|
||||
);
|
||||
}
|
||||
+143
-285
@@ -5,9 +5,14 @@
|
||||
@if (error()) {
|
||||
<p class="muted" role="alert">No se encontró la paciente.</p>
|
||||
} @else if (patient(); as p) {
|
||||
<h1>
|
||||
{{ identity().name ?? 'Paciente' }} <code class="muted">{{ p.id!.slice(0, 10) }}</code>
|
||||
</h1>
|
||||
<div class="head">
|
||||
<h1>
|
||||
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
|
||||
</h1>
|
||||
@if (cama()) {
|
||||
<ng-container *ngTemplateOutlet="export" />
|
||||
}
|
||||
</div>
|
||||
<dl class="summary">
|
||||
<div>
|
||||
<dt>CURP</dt>
|
||||
@@ -21,16 +26,49 @@
|
||||
<dt>Fecha de nacimiento</dt>
|
||||
<dd>{{ p.birthDate ?? 'Sin dato' }}</dd>
|
||||
</div>
|
||||
@if (stages()) {
|
||||
<div>
|
||||
<dt>Edad</dt>
|
||||
<dd>{{ age() ?? 'Sin dato' }}</dd>
|
||||
</div>
|
||||
}
|
||||
<div>
|
||||
<dt>Sexo</dt>
|
||||
<dd>
|
||||
{{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Estatus de seguimiento</dt>
|
||||
<dd>{{ status() }}</dd>
|
||||
</div>
|
||||
@if (cama(); as c) {
|
||||
<div>
|
||||
<dt>Grupo de edad</dt>
|
||||
<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) {
|
||||
<div>
|
||||
<dt>Defunción</dt>
|
||||
@@ -40,9 +78,52 @@
|
||||
</dl>
|
||||
|
||||
<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-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (stages(); as s) {
|
||||
<ng-container *ngTemplateOutlet="export" />
|
||||
<p class="muted note">
|
||||
Los pasos muestran el tamizaje actual, en curso: el de la citología que se consulta.
|
||||
</p>
|
||||
<div data-section="etapas">
|
||||
<app-stages [stages]="s" [detail]="true" />
|
||||
</div>
|
||||
}
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -59,7 +140,7 @@
|
||||
<td>
|
||||
{{ h.text }}
|
||||
@if (h.code && h.code !== h.text) {
|
||||
<span class="muted">({{ h.code }})</span>
|
||||
<span class="muted">(CIE-10: {{ h.code }})</span>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -91,7 +172,19 @@
|
||||
<td class="nowrap">{{ t.date }}</td>
|
||||
<td>{{ t.kind }}</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>
|
||||
} @empty {
|
||||
<tr>
|
||||
@@ -103,290 +196,34 @@
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card appearance="outlined" class="wide">
|
||||
<mat-card-header
|
||||
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
|
||||
>
|
||||
<mat-card-content>
|
||||
@if (models().length) {
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Modelo</th>
|
||||
<th>Fecha índice</th>
|
||||
<th>Horizonte</th>
|
||||
<th>Probabilidad</th>
|
||||
<th>IC 95 %</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (m of models(); track m.model) {
|
||||
@for (p of m.predictions; track p.years) {
|
||||
<tr>
|
||||
<td>{{ $first ? m.text : '' }}</td>
|
||||
<td>{{ $first ? m.index : '' }}</td>
|
||||
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
|
||||
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
|
||||
<td>
|
||||
@if (p.low !== undefined) {
|
||||
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }}
|
||||
%
|
||||
} @else {
|
||||
—
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<app-plot [figure]="curve()" [height]="300" />
|
||||
} @else {
|
||||
<p class="muted">Ningún modelo vigente la ha evaluado.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
@if (forms().length) {
|
||||
<app-antecedents class="wide" [forms]="forms()" />
|
||||
}
|
||||
@if (excluded() || groups().length || domain() !== 'cacu' || riskModels().length) {
|
||||
<app-risk-card
|
||||
class="wide"
|
||||
[domain]="domain()"
|
||||
[id]="id()"
|
||||
[cutoff]="corte()"
|
||||
[sample]="currency().sample ?? citologia()"
|
||||
[models]="riskModels()"
|
||||
[groups]="groups()"
|
||||
[excluded]="excluded()"
|
||||
[note]="currency().note"
|
||||
/>
|
||||
}
|
||||
|
||||
@if (domain() === 'tea') {
|
||||
<mat-card appearance="outlined" class="wide" data-section="tea">
|
||||
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (ados2(); as a) {
|
||||
<h3>Puntajes por reactivo · {{ a.date }}</h3>
|
||||
<app-plot [figure]="a.figure" [height]="a.height" />
|
||||
<p class="totals">
|
||||
@for (t of a.totals; track t.label) {
|
||||
<span
|
||||
>{{ t.label }}: <strong>{{ t.value }}</strong></span
|
||||
>
|
||||
}
|
||||
</p>
|
||||
} @else {
|
||||
<p class="muted">Sin evaluación ADOS-2.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
|
||||
<mat-card appearance="outlined" class="wide" data-section="eeg">
|
||||
<mat-card-header><mat-card-title>EEG</mat-card-title></mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (eeg.isLoading()) {
|
||||
<app-loading what="el EEG" />
|
||||
} @else if (eeg.value()?.study; as st) {
|
||||
<h3>Calidad del EEG</h3>
|
||||
<p>
|
||||
Estudio del {{ st.study_date }}:
|
||||
<strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong>
|
||||
@if (st.level) {
|
||||
({{ st.level }})
|
||||
}
|
||||
</p>
|
||||
<h3>Alteraciones del EEG</h3>
|
||||
@if (!st.valid) {
|
||||
<p class="muted">Un EEG no aceptable no se compara con la norma por edad.</p>
|
||||
} @else if (!scored()) {
|
||||
<p class="muted">
|
||||
Ninguna curva por edad vigente ha evaluado este EEG (se promueven en Gobernanza).
|
||||
</p>
|
||||
} @else if (alterations().length) {
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Métrica</th>
|
||||
<th>Valor</th>
|
||||
<th>Norma por edad (P5–P95)</th>
|
||||
<th>Mediana</th>
|
||||
<th>Desviación (z)</th>
|
||||
<th>Detalle</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (m of alterations(); track m.code) {
|
||||
<tr [class.chosen]="zoned()?.code === m.code">
|
||||
<td>
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
class="metric"
|
||||
[attr.aria-expanded]="zoned()?.code === m.code"
|
||||
(click)="zone.set(zoned()?.code === m.code ? undefined : m.code)"
|
||||
>
|
||||
{{ metricNames[m.code] ?? m.code }}
|
||||
</button>
|
||||
</td>
|
||||
<td>{{ m.value | number: '1.0-3' }}</td>
|
||||
<td>{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | number: '1.0-3' }}</td>
|
||||
<td>{{ m.median | number: '1.0-3' }}</td>
|
||||
<td>{{ m.z | number: '1.1-2' }}</td>
|
||||
<td>{{ m.outside! > 0 ? 'Aumentado' : 'Disminuido' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted">Elija una alteración para ver sus zonas más afectadas.</p>
|
||||
@if (zoned(); as z) {
|
||||
<section class="zones" aria-label="Zonas más afectadas">
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="muted">
|
||||
{{ metricNames[z.code] ?? z.code }} ·
|
||||
{{
|
||||
zonesScored()
|
||||
? 'desviación de cada zona frente a su norma por edad'
|
||||
: 'valor de cada zona (sin norma por edad por zona)'
|
||||
}}
|
||||
</p>
|
||||
@if (z.electrodes.length) {
|
||||
<app-plot [figure]="head()" [height]="280" />
|
||||
}
|
||||
@if (z.zones.length) {
|
||||
<ol class="regions" aria-label="Zonas ordenadas por desviación">
|
||||
@for (r of zoneOrder(); track r.site) {
|
||||
<li [class.marked]="(r.z ?? 0) >= 2 || (r.z ?? 0) <= -2">
|
||||
<span>{{ zoneNames[r.site] ?? r.site }}</span>
|
||||
<span>{{
|
||||
r.z !== null && r.z !== undefined
|
||||
? 'z = ' + (r.z | number: '1.1-2')
|
||||
: (r.value | number: '1.0-3')
|
||||
}}</span>
|
||||
</li>
|
||||
}
|
||||
</ol>
|
||||
} @else if (!z.electrodes.length) {
|
||||
<p class="muted">Esta métrica no se mide por zona.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
} @else {
|
||||
<p>Sin alteraciones: todas sus métricas están dentro de la norma por edad.</p>
|
||||
}
|
||||
@if (st.valid && scored()) {
|
||||
<section
|
||||
class="relation"
|
||||
aria-label="Relación de las alteraciones del EEG con el ADOS-2"
|
||||
>
|
||||
<h3>Relación con el ADOS-2</h3>
|
||||
@if (!eeg.value()?.analysis?.relation?.length) {
|
||||
<p class="muted">
|
||||
Ningún modelo de asociación vigente ha evaluado este EEG (se promueven en
|
||||
Gobernanza).
|
||||
</p>
|
||||
} @else if (!related().length) {
|
||||
<p>
|
||||
Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara
|
||||
con el ADOS-2 en la cohorte.
|
||||
</p>
|
||||
} @else {
|
||||
<p class="muted">
|
||||
Modelo de asociación ajustado en la cohorte ({{ related()[0].n }} niños, por
|
||||
edad y módulo del ADOS-2): qué tanto se asocia cada alteración del EEG por
|
||||
zona con un aspecto del ADOS-2. No es un diagnóstico ni indica qué causa qué.
|
||||
</p>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Zona del EEG</th>
|
||||
<th>Aspecto del ADOS-2</th>
|
||||
<th>Asociación en la cohorte</th>
|
||||
<th>Probabilidad para este paciente</th>
|
||||
<th>Lo que muestra su ADOS-2</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (f of related(); track f.biomarker + f.zone + f.outcome_code) {
|
||||
<tr>
|
||||
<td>
|
||||
<strong>{{ biomarkerNames[f.biomarker] ?? f.biomarker }}</strong>
|
||||
<small
|
||||
>{{ zoneNames[f.zone] ?? f.zone }} · z =
|
||||
{{ f.z | number: '1.1-2' }}</small
|
||||
>
|
||||
</td>
|
||||
<td>
|
||||
{{ outcomeNames[f.outcome_code] ?? f.outcome_code }}
|
||||
<small>{{ f.kind === 'item' ? 'Reactivo' : 'Dominio' }}</small>
|
||||
</td>
|
||||
<td>
|
||||
OR {{ f.odds_ratio | number: '1.2-2' }}
|
||||
<small
|
||||
>IC 95 % {{ f.ci_low | number: '1.2-2' }}–{{
|
||||
f.ci_high | number: '1.2-2'
|
||||
}}
|
||||
· q {{ qText(f.q) }}</small
|
||||
>
|
||||
<small>{{
|
||||
f.odds_ratio >= 1
|
||||
? 'A mayor z, mayor probabilidad'
|
||||
: 'A menor z, mayor probabilidad'
|
||||
}}</small>
|
||||
</td>
|
||||
<td>
|
||||
<strong>{{ f.probability * 100 | number: '1.0-0' }} %</strong>
|
||||
<small
|
||||
>{{ f.event }} · con z = 0:
|
||||
{{ f.reference_probability * 100 | number: '1.0-0' }} %</small
|
||||
>
|
||||
</td>
|
||||
<td>
|
||||
{{ observed(f) }}
|
||||
@if (matches(f); as m) {
|
||||
<small>{{ m }}</small>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted">
|
||||
OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga
|
||||
alterado; menor que 1, al revés. Solo se muestran las zonas alteradas del
|
||||
paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05).
|
||||
Versión del modelo: {{ related()[0].model }}.
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
} @else {
|
||||
<p class="muted">Sin EEG analizado.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<app-tea-record class="wide" [id]="id()" [observations]="observations()" />
|
||||
}
|
||||
|
||||
@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) {
|
||||
<mat-card appearance="outlined" class="wide" data-section="recurrencia">
|
||||
<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>
|
||||
<h3>Análisis de recurrencia</h3>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -417,17 +254,38 @@
|
||||
<app-plot [figure]="f.figure" [height]="340" />
|
||||
} @empty {
|
||||
<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>
|
||||
}
|
||||
<app-factores [rows]="s.factors" />
|
||||
} @else if (recurrence.error()) {
|
||||
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
@if (survivalModels().length) {
|
||||
<app-survival-card
|
||||
class="wide"
|
||||
[domain]="domain()"
|
||||
[models]="survivalModels()"
|
||||
[analysis]="survival.value()"
|
||||
[loading]="survival.isLoading()"
|
||||
[failed]="!!survival.error()"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
} @else if (loading()) {
|
||||
<app-loading what="el expediente" />
|
||||
}
|
||||
<ng-template #export>
|
||||
<div class="actions">
|
||||
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
|
||||
Exportar PDF
|
||||
</button>
|
||||
</div>
|
||||
@if (saveError()) {
|
||||
<p class="muted" role="alert">{{ saveError() }}</p>
|
||||
}
|
||||
</ng-template>
|
||||
</section>
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
.summary {
|
||||
.summary,
|
||||
.facts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-6);
|
||||
margin: var(--space-3) 0 var(--space-4);
|
||||
}
|
||||
|
||||
.summary dt {
|
||||
.summary dt,
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.summary dd {
|
||||
.summary dd,
|
||||
.facts dd {
|
||||
font-weight: 500;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -51,40 +54,46 @@ mat-card-content {
|
||||
}
|
||||
}
|
||||
|
||||
.totals {
|
||||
h1 .id {
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
margin-left: var(--space-2);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* The name and, in CaMa, the record's export on one line; narrow screens put it under the name. */
|
||||
.head {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.zones {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.regions {
|
||||
list-style: none;
|
||||
margin: 8px 0 0;
|
||||
padding: 0;
|
||||
max-width: 420px;
|
||||
li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--mat-sys-outline-variant);
|
||||
gap: 8px 16px;
|
||||
justify-content: space-between;
|
||||
h1 {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
li.marked {
|
||||
font-weight: 600;
|
||||
color: var(--mat-sys-error);
|
||||
.actions {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
tr.chosen td {
|
||||
background: var(--mat-sys-surface-container);
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
.relation {
|
||||
margin-top: 16px;
|
||||
td small {
|
||||
display: block;
|
||||
color: var(--mat-sys-on-surface-variant);
|
||||
font-size: 0.8em;
|
||||
.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;
|
||||
}
|
||||
}
|
||||
|
||||
+226
-301
@@ -1,4 +1,4 @@
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { DecimalPipe, NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
@@ -8,45 +8,52 @@ import type {
|
||||
Condition,
|
||||
DiagnosticReport,
|
||||
Observation,
|
||||
Parameters,
|
||||
Patient,
|
||||
Procedure,
|
||||
RiskAssessment,
|
||||
} from 'fhir/r4';
|
||||
import { Api } from '../api/api';
|
||||
import { studies as eegStudies } from '../api/fn/eeg/studies';
|
||||
import { study as eegStudy } from '../api/fn/eeg/study';
|
||||
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
|
||||
import { scenarioFigure } from '../gobernanza/figures';
|
||||
import { CURP } from '../indicadores/follow-up';
|
||||
import { name } from '../indicadores/measures';
|
||||
import {
|
||||
BIOMARKER_NAMES,
|
||||
byDeviation,
|
||||
headMap,
|
||||
METRIC_NAMES,
|
||||
OUTCOME_NAMES,
|
||||
ZONE_NAMES,
|
||||
} from '../eeg-labels';
|
||||
import type { Relation } from '../api/models/relation';
|
||||
import { Figure, PALETTE, Plot } from '../plot';
|
||||
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
|
||||
import { code, ext, Fhir, resources } from '../fhir';
|
||||
import { savePdf } from '../export';
|
||||
import { ageAt, CURP } from '../indicadores/follow-up';
|
||||
import { name } from '../indicadores/labels';
|
||||
import { Loading } from '../loading';
|
||||
import { Plot } from '../plot';
|
||||
import { analysis } from './analysis';
|
||||
import { Antecedents } from './antecedents';
|
||||
import { camaSummary, camaFacts, camaStudies, listedRow } from './cama-record';
|
||||
import { currency, eligibilityFailure, eligibilityView, ineligibility } from './eligibility';
|
||||
import { Factores } from './factores';
|
||||
import { forms, history, models, PatientRecord, tests } from './record';
|
||||
import { camaRecordSheets, recordSheets } from './record-sheets';
|
||||
import { RiskCard } from './risk-card';
|
||||
import { riskGroups, riskScales, survivalGroups } from './risk-scales';
|
||||
import { route, Stages } from './stages';
|
||||
import { SurvivalCard } from './survival-card';
|
||||
import { TeaRecord } from './tea-record';
|
||||
|
||||
/** An Observation's value as the screens say it, whatever its type. */
|
||||
function shown(o: Observation): string {
|
||||
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
|
||||
if (o.valueCodeableConcept)
|
||||
return name(code(o.valueCodeableConcept) ?? '') || label(o.valueCodeableConcept);
|
||||
if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim();
|
||||
return o.valueString ?? o.valueDateTime ?? '';
|
||||
}
|
||||
|
||||
/** One patient: her history (conditions, procedures), her tests and results, and the
|
||||
* champion models' risks with their curves. Everything read from the FHIR API. */
|
||||
/** One patient: her history, her tests and results, the form's antecedents, her risk with its
|
||||
* curves and her survival, as the FHIR API publishes them. */
|
||||
@Component({
|
||||
selector: 'app-paciente',
|
||||
imports: [Loading, DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
|
||||
imports: [
|
||||
Antecedents,
|
||||
DecimalPipe,
|
||||
Factores,
|
||||
Loading,
|
||||
MatButtonModule,
|
||||
MatCardModule,
|
||||
MatIconModule,
|
||||
NgTemplateOutlet,
|
||||
Plot,
|
||||
RiskCard,
|
||||
RouterLink,
|
||||
Stages,
|
||||
SurvivalCard,
|
||||
TeaRecord,
|
||||
],
|
||||
templateUrl: './paciente.html',
|
||||
styleUrl: './paciente.scss',
|
||||
})
|
||||
@@ -55,315 +62,233 @@ export class Paciente {
|
||||
private readonly api = inject(Api);
|
||||
readonly domain = 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({
|
||||
params: () => ({ domain: this.domain(), id: this.id() }),
|
||||
loader: async ({ params: { domain, id } }) => {
|
||||
loader: async ({ params: { domain, id } }): Promise<PatientRecord> => {
|
||||
const subject = { subject: `Patient/${id}`, _count: 200 };
|
||||
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
|
||||
this.fhir.read<Patient>(domain, 'Patient', id),
|
||||
this.fhir.all(domain, 'Condition', subject),
|
||||
this.fhir.all(domain, 'Procedure', subject),
|
||||
this.fhir.all(domain, 'DiagnosticReport', subject),
|
||||
this.fhir.all(domain, 'Observation', subject),
|
||||
this.fhir.all(domain, 'RiskAssessment', subject),
|
||||
...['Condition', 'Procedure', 'DiagnosticReport', 'Observation', 'RiskAssessment'].map(
|
||||
(type) => this.fhir.all(domain, type, subject),
|
||||
),
|
||||
]);
|
||||
return {
|
||||
patient,
|
||||
conditions: resources<Condition>(conditions, 'Condition'),
|
||||
procedures: resources<Procedure>(procedures, 'Procedure'),
|
||||
reports: resources<DiagnosticReport>(reports, 'DiagnosticReport').reverse(),
|
||||
patient: patient as Patient,
|
||||
conditions: resources<Condition>(conditions as never, 'Condition'),
|
||||
procedures: resources<Procedure>(procedures as never, 'Procedure'),
|
||||
reports: resources<DiagnosticReport>(reports as never, 'DiagnosticReport').reverse(),
|
||||
observations: new Map(
|
||||
resources<Observation>(observations, 'Observation').map((o) => [o.id, o]),
|
||||
resources<Observation>(observations as never, 'Observation').map((o) => [o.id, o]),
|
||||
),
|
||||
risks: resources<RiskAssessment>(risks, 'RiskAssessment'),
|
||||
risks: resources<RiskAssessment>(risks as never, 'RiskAssessment'),
|
||||
};
|
||||
},
|
||||
});
|
||||
protected readonly patient = computed(() => this.data.value()?.patient);
|
||||
protected readonly error = computed(() => this.data.error());
|
||||
protected readonly loading = computed(() => this.data.isLoading());
|
||||
protected readonly history = computed(() => {
|
||||
const d = this.data.value();
|
||||
if (!d) return [];
|
||||
return [
|
||||
...d.conditions.map((c) => ({
|
||||
date: c.recordedDate ?? '',
|
||||
kind: 'Diagnóstico',
|
||||
text: label(c.code),
|
||||
code: code(c.code),
|
||||
})),
|
||||
...d.procedures.map((p) => ({
|
||||
date: p.performedDateTime ?? '',
|
||||
kind: 'Procedimiento',
|
||||
text: label(p.code),
|
||||
code: undefined,
|
||||
})),
|
||||
].sort((a, b) => b.date.localeCompare(a.date));
|
||||
protected readonly observations = computed(() => [
|
||||
...(this.data.value()?.observations.values() ?? []),
|
||||
]);
|
||||
protected readonly history = computed(() =>
|
||||
this.data.hasValue() ? history(this.data.value()) : [],
|
||||
);
|
||||
protected readonly tests = computed(() => (this.data.hasValue() ? tests(this.data.value()) : []));
|
||||
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
|
||||
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
|
||||
private readonly cacu = computed(() => this.domain() === 'cacu');
|
||||
private readonly cytologies = computed(() =>
|
||||
(this.data.value()?.reports ?? []).filter((r) => code(r.code) === 'cervical_cytology'),
|
||||
);
|
||||
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
|
||||
protected readonly stages = computed(() => {
|
||||
const opened = this.cytologies().find((r) => r.effectiveDateTime === this.citologia());
|
||||
return this.cacu() ? route(opened ?? this.cytologies()[0], this.cutoff()) : undefined;
|
||||
});
|
||||
protected readonly tests = computed(() => {
|
||||
const d = this.data.value();
|
||||
if (!d) return [];
|
||||
return d.reports.map((r) => {
|
||||
const results = (r.result ?? [])
|
||||
.map((x) => d.observations.get(x.reference?.split('/')[1]))
|
||||
.filter((o) => !!o) as Observation[];
|
||||
return {
|
||||
date: r.effectiveDateTime ?? '',
|
||||
reported: ext(r, 'report-date')?.valueDate,
|
||||
kind: label(r.code),
|
||||
status: r.status,
|
||||
results: [...results.map((o) => `${label(o.code)}: ${shown(o)}`)],
|
||||
};
|
||||
});
|
||||
/** CaCu: what each cytology's form declares, the one she was opened at first. */
|
||||
protected readonly forms = computed(() =>
|
||||
this.cacu() && this.data.hasValue() ? forms(this.data.value(), this.citologia()) : [],
|
||||
);
|
||||
|
||||
/** CaCu: the decisions `$eligibility` publishes for her indexed visits. */
|
||||
private readonly eligibility = resource({
|
||||
params: () => (this.cacu() ? { id: this.id(), cutoff: this.corte() } : undefined),
|
||||
loader: async ({ params }) => {
|
||||
try {
|
||||
const answer = await this.api.invoke(cacuEligibility, {
|
||||
domain: 'cacu',
|
||||
...params,
|
||||
} as never);
|
||||
return eligibilityView(answer as Parameters);
|
||||
} catch (error) {
|
||||
return eligibilityFailure(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
/** One model's latest risk assessment per model. */
|
||||
protected readonly models = computed(() => {
|
||||
const latest = new Map<string, RiskAssessment>();
|
||||
for (const r of this.data.value()?.risks ?? []) {
|
||||
const key = code(r.method) ?? '';
|
||||
if (
|
||||
!latest.has(key) ||
|
||||
(latest.get(key)!.occurrenceDateTime ?? '') < (r.occurrenceDateTime ?? '')
|
||||
)
|
||||
latest.set(key, r);
|
||||
}
|
||||
return [...latest.values()].map((r) => ({
|
||||
model: code(r.method) ?? '',
|
||||
text: r.method?.text ?? '',
|
||||
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
|
||||
index: r.occurrenceDateTime ?? '',
|
||||
// the clinical scenarios of the model's report she falls in
|
||||
scenarios: (r.extension ?? [])
|
||||
.filter((e) => e.url === EXT + 'escenario-clinico')
|
||||
.map((e) => e.valueString ?? ''),
|
||||
predictions: (r.prediction ?? []).map((p) => ({
|
||||
years: p.whenRange?.high?.value ?? 0,
|
||||
p: p.probabilityDecimal ?? 0,
|
||||
low: ext(p, 'ic-bajo')?.valueDecimal,
|
||||
high: ext(p, 'ic-alto')?.valueDecimal,
|
||||
})),
|
||||
}));
|
||||
/** CaCu: why she has no risk estimate: the backend's reason, else a hysterectomy her record
|
||||
* holds by the index (evidence loaded without the day it became available). */
|
||||
protected readonly riskExclusion = computed(() => {
|
||||
const p = this.patient();
|
||||
if (!this.cacu() || !p) return undefined;
|
||||
const sample = this.citologia()?.slice(0, 10);
|
||||
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
|
||||
const status = ext(p, 'follow-up-status')?.valueCoding?.code ?? '';
|
||||
const state = this.eligibility.value() ?? { kind: 'loading' as const };
|
||||
const recorded = ext(p, 'first-hysterectomy-recorded')?.valueDate;
|
||||
return (
|
||||
ineligibility(state, status, index) ??
|
||||
(recorded && recorded <= index
|
||||
? `No disponible por: histerectomía registrada el ${recorded}.`
|
||||
: undefined)
|
||||
);
|
||||
});
|
||||
/** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical
|
||||
* scenarios, from the report of the model version that scored her. */
|
||||
/** Each model's latest estimate of her; none when she is excluded. */
|
||||
protected readonly models = computed(() =>
|
||||
this.riskExclusion() ? [] : models(this.data.value()?.risks ?? []),
|
||||
);
|
||||
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
|
||||
protected readonly survivalModels = computed(() =>
|
||||
this.models().filter((m) => m.model.endsWith('.survival')),
|
||||
);
|
||||
/** CaCu: the cytology her estimates speak of, against her latest by the cut-off. */
|
||||
protected readonly currency = computed(() =>
|
||||
this.cacu()
|
||||
? currency(
|
||||
this.riskModels(),
|
||||
this.cytologies()
|
||||
.map((r) => r.effectiveDateTime ?? '')
|
||||
.filter((d) => d && d.slice(0, 10) <= this.cutoff()),
|
||||
)
|
||||
: {},
|
||||
);
|
||||
/** The one reason nothing of her risk is shown: the backend withholding it, her exclusion, or a
|
||||
* later cytology after her first post-colposcopy visit. */
|
||||
protected readonly excluded = computed(
|
||||
() =>
|
||||
(this.patient() && ext(this.patient(), 'risk-withheld')?.valueString) ??
|
||||
this.riskExclusion() ??
|
||||
this.currency().excluded,
|
||||
);
|
||||
/** CaCu: both horizons of every risk model, or both unavailable (with survival only, nothing). */
|
||||
protected readonly groups = computed(() =>
|
||||
this.cacu() && (this.riskModels().length || !survivalGroups(this.survivalModels()).length)
|
||||
? riskGroups(this.riskModels())
|
||||
: [],
|
||||
);
|
||||
/** "Análisis de supervivencia" and "de recurrencia" of her clinical scenarios. */
|
||||
protected readonly survival = this.analysis('survival');
|
||||
protected readonly recurrence = this.analysis('recurrence');
|
||||
protected readonly recurrenceModel = computed(() =>
|
||||
this.models().find((m) => m.model.endsWith('.recurrence') && m.version),
|
||||
);
|
||||
|
||||
private analysis(name: 'survival' | 'recurrence') {
|
||||
private analysis(kind: 'survival' | 'recurrence') {
|
||||
return resource({
|
||||
params: () => {
|
||||
const m = this.models().find(
|
||||
(x) => x.model === `${this.domain()}.${name}` && x.scenarios.length && x.version,
|
||||
);
|
||||
return m ? { m, domain: this.domain() } : undefined;
|
||||
},
|
||||
loader: async ({ params: { m, domain } }) => {
|
||||
const report = await this.api.invoke(readReport$Json, {
|
||||
domain: domain as Domain,
|
||||
name,
|
||||
version: m.version,
|
||||
report: 'interpretability',
|
||||
});
|
||||
const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
|
||||
if (name === 'recurrence') {
|
||||
const r = (report?.['recurrencia'] ?? {}) as any;
|
||||
return {
|
||||
scenarios: m.scenarios,
|
||||
figures: mine(r['escenarios'] ?? []).map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
|
||||
e,
|
||||
r['horizons_months'],
|
||||
'Supervivencia libre de recaída',
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
scenarios: m.scenarios,
|
||||
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
|
||||
scenarioFigure(
|
||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
|
||||
e,
|
||||
e.horizons_months,
|
||||
'Supervivencia S(t)',
|
||||
),
|
||||
),
|
||||
};
|
||||
const domain = this.domain();
|
||||
const m = this.models().find((x) => x.model === `${domain}.${kind}` && x.scenarios.length);
|
||||
return m?.version && !(kind === 'survival' && domain === 'cacu')
|
||||
? { domain, m }
|
||||
: undefined;
|
||||
},
|
||||
loader: ({ params: { domain, m } }) => analysis(this.api, domain, m),
|
||||
});
|
||||
}
|
||||
/** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's
|
||||
* `ados2.*` fields), item by item, and its totals. */
|
||||
protected readonly ados2 = computed(() => {
|
||||
const d = this.data.value();
|
||||
if (!d) return undefined;
|
||||
const field = (o: Observation) => (code(o.code) ?? '').replace(/^ados2\./, '');
|
||||
const scored = [...d.observations.values()].filter(
|
||||
(o) => (code(o.code) ?? '').startsWith('ados2.') && o.valueQuantity?.value !== undefined,
|
||||
);
|
||||
const latest = scored
|
||||
.map((o) => o.effectiveDateTime ?? '')
|
||||
.sort()
|
||||
.at(-1);
|
||||
if (latest === undefined) return undefined;
|
||||
const results = scored.filter((o) => (o.effectiveDateTime ?? '') === latest);
|
||||
const totals = ['social_affect_total', 'restricted_repetitive_total', 'overall_total'];
|
||||
const items = results.filter((o) => !totals.includes(field(o)));
|
||||
const figure: Figure = {
|
||||
data: [
|
||||
{
|
||||
type: 'bar',
|
||||
orientation: 'h',
|
||||
y: items.map((o) => label(o.code)),
|
||||
x: items.map((o) => o.valueQuantity!.value!),
|
||||
marker: { color: PALETTE[0] },
|
||||
hovertemplate: '%{y}: %{x}<extra></extra>',
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
showlegend: false,
|
||||
margin: { t: 10, r: 16, b: 40, l: 16 },
|
||||
xaxis: { title: { text: 'Puntaje (0 a 3)' }, range: [0, 3], dtick: 1 },
|
||||
yaxis: { autorange: 'reversed', automargin: true, type: 'category' },
|
||||
},
|
||||
};
|
||||
return {
|
||||
date: latest.slice(0, 10),
|
||||
figure,
|
||||
height: 60 + items.length * 22,
|
||||
totals: results
|
||||
.filter((o) => totals.includes(field(o)))
|
||||
.map((o) => ({ label: label(o.code), value: o.valueQuantity!.value! })),
|
||||
};
|
||||
});
|
||||
|
||||
/** TEA: her EEG as analysed (the latest), its quality and its metrics against the age
|
||||
* curves: those outside the band are its alterations. */
|
||||
protected readonly eeg = resource({
|
||||
params: () => (this.domain() === 'tea' ? this.id() : undefined),
|
||||
loader: async ({ params: person }) => {
|
||||
const mine = (await this.api.invoke(eegStudies))
|
||||
.filter((s) => s.person_id === person && s.analysed)
|
||||
.sort((a, b) => b.study_date.localeCompare(a.study_date));
|
||||
if (!mine.length) return { study: undefined, analysis: undefined };
|
||||
return {
|
||||
study: mine[0],
|
||||
analysis: await this.api.invoke(eegStudy, { eeg_id: mine[0].id }),
|
||||
};
|
||||
},
|
||||
});
|
||||
protected readonly alterations = computed(() =>
|
||||
(this.eeg.value()?.analysis?.metrics ?? []).filter((m) => m.outside),
|
||||
);
|
||||
protected readonly scored = computed(() =>
|
||||
(this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined),
|
||||
);
|
||||
protected readonly shown = signal<string | undefined>(undefined);
|
||||
protected readonly metricNames = METRIC_NAMES;
|
||||
protected readonly zoneNames = ZONE_NAMES;
|
||||
/** "Zonas más afectadas": the alteration chosen, its zones and electrodes. */
|
||||
protected readonly zone = signal<string | undefined>(undefined);
|
||||
protected readonly zoned = computed(() => {
|
||||
const m = this.alterations().find((a) => a.code === this.zone());
|
||||
return m ? { code: m.code, zones: m.zones ?? [], electrodes: m.electrodes ?? [] } : undefined;
|
||||
});
|
||||
protected readonly zonesScored = computed(() =>
|
||||
[...(this.zoned()?.zones ?? []), ...(this.zoned()?.electrodes ?? [])].some(
|
||||
(s) => s.z !== null && s.z !== undefined,
|
||||
),
|
||||
);
|
||||
protected readonly biomarkerNames = BIOMARKER_NAMES;
|
||||
protected readonly outcomeNames = OUTCOME_NAMES;
|
||||
/** "Relación con el ADOS-2": her altered zones (|z| ≥ 2) with a clear association in the
|
||||
* cohort (q < 0.05), clearest first, as the old summary showed them. */
|
||||
protected readonly related = computed(() =>
|
||||
(this.eeg.value()?.analysis?.relation ?? [])
|
||||
.filter((f) => Math.abs(f.z) >= 2 && f.q !== null && f.q !== undefined && f.q < 0.05)
|
||||
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1)),
|
||||
);
|
||||
protected qText(q?: number | null): string {
|
||||
return q === null || q === undefined ? '—' : q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`;
|
||||
}
|
||||
protected observed(f: Relation): string {
|
||||
if (f.observed === null || f.observed === undefined) return 'Sin dato';
|
||||
if (f.kind === 'item')
|
||||
return f.observed >= 1 ? `Alterado (${f.observed})` : 'Sin anormalidad (0)';
|
||||
return `CSS ${f.observed}`;
|
||||
}
|
||||
/** Whether what she shows is what the model leans to (above or below one half). */
|
||||
protected matches(f: Relation): string | undefined {
|
||||
if (f.observed === null || f.observed === undefined) return undefined;
|
||||
const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8;
|
||||
return present === f.probability >= 0.5
|
||||
? 'Coincide con lo que el modelo esperaba'
|
||||
: 'No coincide con lo que el modelo esperaba';
|
||||
}
|
||||
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
|
||||
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
|
||||
protected readonly curve = computed<Figure>(() => {
|
||||
const models = this.models().filter((m) => m.predictions.length > 1);
|
||||
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 {
|
||||
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
|
||||
}
|
||||
protected readonly name = name;
|
||||
protected readonly identity = computed(() => {
|
||||
const p = this.patient();
|
||||
return {
|
||||
name: p?.name?.[0]?.text,
|
||||
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((n): n is string => !!n),
|
||||
};
|
||||
});
|
||||
/** CaMa: her row on the follow-up list, as opened (else the widest window). */
|
||||
private readonly listed = resource({
|
||||
params: () =>
|
||||
this.domain() === 'cama'
|
||||
? { id: this.id(), window: Number(this.ventana()) || 12, cutoff: this.corte() || undefined }
|
||||
: undefined,
|
||||
loader: ({ params }) => listedRow(this.fhir, params),
|
||||
});
|
||||
protected readonly cama = computed(() => {
|
||||
const found = this.listed.value();
|
||||
return found && this.data.hasValue() ? camaSummary(this.data.value(), found) : undefined;
|
||||
});
|
||||
protected readonly status = computed(() => {
|
||||
const p = this.patient();
|
||||
return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : '';
|
||||
});
|
||||
|
||||
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();
|
||||
else await this.saveCacu();
|
||||
} catch {
|
||||
this.saveError.set('No se generó el archivo.');
|
||||
} finally {
|
||||
this.saving.set(false);
|
||||
}
|
||||
}
|
||||
private async saveCacu(): Promise<void> {
|
||||
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 probabilidad', this.riskExclusion()]);
|
||||
const scales = riskScales(this.riskModels());
|
||||
const sheets = recordSheets(
|
||||
facts,
|
||||
this.stages() ?? [],
|
||||
this.history(),
|
||||
this.tests(),
|
||||
scales,
|
||||
this.forms(),
|
||||
);
|
||||
await savePdf(sheets, 'expediente-cacu');
|
||||
}
|
||||
private async saveCama(): Promise<void> {
|
||||
// an analysis that failed to load is none: its absence is said, the file is still made
|
||||
const read = (title: string, r: typeof this.survival) => {
|
||||
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(
|
||||
camaFacts(this.identity(), this.patient(), this.cama()),
|
||||
camaStudies(this.cama()),
|
||||
this.history(),
|
||||
this.tests(),
|
||||
this.models(),
|
||||
[...read('Supervivencia', this.survival), ...read('Recurrencia', this.recurrence)],
|
||||
);
|
||||
await savePdf(sheets, 'expediente-cama');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/** A field of a study's form, as its Observation says it: `cervical_cytology.hpv` is the study
|
||||
* `cervical_cytology` and the field `hpv`. */
|
||||
export interface Fact {
|
||||
study: string;
|
||||
field: string;
|
||||
title: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
/** What the cytology's form declares before and at the sample: statements of the form, not
|
||||
* diagnoses. */
|
||||
export const ANTECEDENTS = [
|
||||
{ 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' },
|
||||
];
|
||||
const DECLARED = new Set(ANTECEDENTS.map((a) => a.field));
|
||||
const HPV = new Set(['hpv', 'hpv_16', 'hpv_18']);
|
||||
|
||||
/** A catalog code as its study and field. */
|
||||
export function split(code: string): { study: string; field: string } {
|
||||
const [study, ...field] = code.split('.');
|
||||
return field.length ? { study, field: field.join('.') } : { study: '', field: code };
|
||||
}
|
||||
|
||||
const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
|
||||
|
||||
/** A report's facts sorted by what they are: the form's antecedents (by field), the study's own
|
||||
* results, and the extra findings (the cytologist's text first, then each finding stated). */
|
||||
export function group(facts: Fact[]) {
|
||||
const antecedents: Record<string, string> = {};
|
||||
const results: string[] = [];
|
||||
const findings: string[] = [];
|
||||
for (const f of facts) {
|
||||
const form = f.study === 'cervical_cytology';
|
||||
if (form && DECLARED.has(f.field)) antecedents[f.field] = f.value;
|
||||
else if (form && f.field === 'findings') findings.unshift(`Texto del informe: ${f.value}`);
|
||||
else if (form && f.field.startsWith('finding_')) {
|
||||
const named = capital(f.title.replace(/^Hallazgo: /, ''));
|
||||
findings.push(f.value === 'positivo' ? named : `${named}: ${f.value}`);
|
||||
}
|
||||
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
|
||||
else results.push(f.value.startsWith(f.title) ? f.value : `${f.title}: ${f.value}`);
|
||||
}
|
||||
return { antecedents, results, findings };
|
||||
}
|
||||
|
||||
/** A cytology report's HPV results apart from the cytology's own: they are a study of their own. */
|
||||
export function hpvApart(facts: Fact[]) {
|
||||
const hpv = (f: Fact) => f.study === 'cervical_cytology' && HPV.has(f.field);
|
||||
return { hpv: facts.filter(hpv), rest: facts.filter((f) => !hpv(f)) };
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { Sheet } from '../export';
|
||||
import { ANTECEDENTS } from './record-groups';
|
||||
import type { Prediction, RiskScale } from './risk-scales';
|
||||
import { SOURCES, Stage, STATES } from './stages';
|
||||
|
||||
const NONE = 'No disponible';
|
||||
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
|
||||
const between = (p?: Prediction) =>
|
||||
p?.low === undefined || p.high === undefined ? NONE : `${percent(p.low)} a ${percent(p.high)}`;
|
||||
|
||||
type Facts = [string, string | undefined][];
|
||||
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 published estimate (risk, survival or recurrence) by horizon. */
|
||||
interface Estimate {
|
||||
text: string;
|
||||
index: string;
|
||||
predictions: Prediction[];
|
||||
}
|
||||
/** The curves of her clinical scenarios as the page lists them. */
|
||||
export interface Analysis {
|
||||
title: string;
|
||||
scenarios: string[];
|
||||
/** the titles of the figures drawn */
|
||||
figures: string[];
|
||||
/** her scenarios the report draws no curve for */
|
||||
undrawn: string[];
|
||||
}
|
||||
|
||||
const table = (title: string, facts: Facts): Sheet => ({
|
||||
title,
|
||||
head: ['Dato', 'Valor'],
|
||||
rows: facts.map(([k, v]) => [k, v || NONE]),
|
||||
});
|
||||
const historySheet = (history: Event[]): Sheet => ({
|
||||
title: 'Historial médico',
|
||||
head: ['Fecha', 'Tipo', 'Detalle'],
|
||||
rows: history.map((h) => [h.date, h.kind, h.text]),
|
||||
});
|
||||
const testsSheet = (tests: Test[]): Sheet => ({
|
||||
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(' · '),
|
||||
]),
|
||||
});
|
||||
|
||||
/** A CaCu patient's record as the tables of her PDF, in the page's order. */
|
||||
export function recordSheets(
|
||||
facts: Facts,
|
||||
stages: Stage[],
|
||||
history: Event[],
|
||||
tests: Test[],
|
||||
scales: RiskScale[],
|
||||
forms: Form[],
|
||||
): Sheet[] {
|
||||
return [
|
||||
table('Datos de la paciente', facts),
|
||||
{
|
||||
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(' · '),
|
||||
]),
|
||||
},
|
||||
historySheet(history),
|
||||
{
|
||||
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'),
|
||||
]),
|
||||
},
|
||||
testsSheet(tests),
|
||||
{
|
||||
title: 'Probabilidades',
|
||||
head: ['Estimación', 'Probabilidad', 'IC 95 %'],
|
||||
rows: scales.map(({ label, risk }) => [label, risk ? percent(risk.p) : NONE, between(risk)]),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
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: only what CaMa publishes, an absent value
|
||||
* said as such and no estimate made up. */
|
||||
export function camaRecordSheets(
|
||||
facts: Facts,
|
||||
studies: Facts,
|
||||
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), between(p)]),
|
||||
);
|
||||
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 [
|
||||
table('Datos de la paciente', facts),
|
||||
table('Última mastografía y resultado histopatológico', studies),
|
||||
historySheet(history),
|
||||
testsSheet(tests),
|
||||
{
|
||||
title: 'Riesgos y recomendaciones publicados',
|
||||
head: ['Estimación', 'Fecha índice', 'Horizonte', 'Probabilidad', 'IC 95 %'],
|
||||
rows: risks.length ? risks : [['Sin estimaciones publicadas', NONE, NONE, NONE, NONE]],
|
||||
},
|
||||
...(curves.length
|
||||
? [
|
||||
{
|
||||
title:
|
||||
'Supervivencia y recurrencia por escenario clínico (estimaciones del grupo, no predicciones individuales)',
|
||||
head: ['Análisis', 'Escenario', 'Estado'],
|
||||
rows: curves,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import type {
|
||||
Condition,
|
||||
DiagnosticReport,
|
||||
Observation,
|
||||
Patient,
|
||||
Procedure,
|
||||
RiskAssessment,
|
||||
} from 'fhir/r4';
|
||||
import { code, EXT, ext, label } from '../fhir';
|
||||
import { LABELS, name } from '../indicadores/labels';
|
||||
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
|
||||
|
||||
/** Her record as the FHIR API gives it. */
|
||||
export interface PatientRecord {
|
||||
patient: Patient;
|
||||
conditions: Condition[];
|
||||
procedures: Procedure[];
|
||||
/** latest first */
|
||||
reports: DiagnosticReport[];
|
||||
observations: Map<string | undefined, Observation>;
|
||||
risks: RiskAssessment[];
|
||||
}
|
||||
|
||||
/** An Observation's value as the screens say it, whatever its type. */
|
||||
export function shown(o: Observation): string {
|
||||
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
|
||||
if (o.valueCodeableConcept) {
|
||||
// the screens' own name for the code (BI-RADS 4C), else the server's display
|
||||
const c = code(o.valueCodeableConcept) ?? '';
|
||||
return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept);
|
||||
}
|
||||
if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim();
|
||||
return o.valueString ?? o.valueDateTime ?? '';
|
||||
}
|
||||
|
||||
/** A report's Observations. */
|
||||
export const results = (d: PatientRecord, r: DiagnosticReport) =>
|
||||
(r.result ?? [])
|
||||
.map((x) => d.observations.get(x.reference?.split('/')[1]))
|
||||
.filter((o): o is Observation => !!o);
|
||||
|
||||
/** Observations as facts of their study's form. */
|
||||
const facts = (observations: Observation[]): Fact[] =>
|
||||
observations.map((o) => ({
|
||||
...split(code(o.code) ?? ''),
|
||||
title: label(o.code),
|
||||
value: shown(o),
|
||||
}));
|
||||
|
||||
/** Her diagnoses and procedures, latest first. */
|
||||
export function history(d: PatientRecord) {
|
||||
return [
|
||||
...d.conditions.map((c) => ({
|
||||
date: c.recordedDate ?? '',
|
||||
kind: 'Diagnóstico',
|
||||
text: label(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) => ({
|
||||
date: p.performedDateTime ?? '',
|
||||
kind: 'Procedimiento',
|
||||
text: label(p.code),
|
||||
code: undefined,
|
||||
})),
|
||||
].sort((a, b) => b.date.localeCompare(a.date));
|
||||
}
|
||||
|
||||
/** Her studies and their own results; the form's antecedents have their section, the extra
|
||||
* findings are collapsed, and an HPV result is a study of its own row. */
|
||||
export function tests(d: PatientRecord) {
|
||||
return d.reports.flatMap((r) => {
|
||||
const { hpv, rest } = hpvApart(facts(results(d, r)));
|
||||
const found = group(rest);
|
||||
const row = {
|
||||
date: r.effectiveDateTime ?? '',
|
||||
reported: ext(r, 'report-date')?.valueDate,
|
||||
kind: label(r.code),
|
||||
status: r.status,
|
||||
results: found.results,
|
||||
findings: found.findings,
|
||||
};
|
||||
if (!hpv.length) return [row];
|
||||
return [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }];
|
||||
});
|
||||
}
|
||||
|
||||
/** What each cytology's form declares (statements, not diagnoses), the one she was opened at
|
||||
* first; forms that declare nothing are left out. */
|
||||
export function forms(d: PatientRecord, opened?: string) {
|
||||
const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology');
|
||||
const first = cytologies.find((r) => r.effectiveDateTime === opened) ?? cytologies[0];
|
||||
return [first, ...cytologies.filter((r) => r !== first)]
|
||||
.filter((r) => !!r)
|
||||
.map((r) => ({
|
||||
date: r.effectiveDateTime ?? '',
|
||||
values: group(facts(results(d, r))).antecedents,
|
||||
}))
|
||||
.filter((f) => ANTECEDENTS.some((a) => f.values[a.field]));
|
||||
}
|
||||
|
||||
/** The JSON of a model's inputs as an object; anything else is none. */
|
||||
function inputs(value?: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const found: unknown = value && JSON.parse(value);
|
||||
return found && typeof found === 'object' && !Array.isArray(found)
|
||||
? (found as never)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The day of an instant at the hospital (America/Monterrey). */
|
||||
const localDay = (instant?: string) =>
|
||||
instant && new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' });
|
||||
|
||||
/** Each model's latest assessment of her. */
|
||||
export function models(risks: RiskAssessment[]) {
|
||||
const latest = new Map<string, RiskAssessment>();
|
||||
for (const r of risks) {
|
||||
const key = code(r.method) ?? '';
|
||||
const held = latest.get(key)?.occurrenceDateTime;
|
||||
if (held === undefined || held < (r.occurrenceDateTime ?? '')) latest.set(key, r);
|
||||
}
|
||||
return [...latest.values()].map((r) => ({
|
||||
model: code(r.method) ?? '',
|
||||
text: r.method?.text ?? '',
|
||||
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
|
||||
index: r.occurrenceDateTime ?? '',
|
||||
/** risk, mortality (survival) or other (recurrence) */
|
||||
measure: ext(r, 'prediction-measure')?.valueCode,
|
||||
inputs: inputs(ext(r, 'model-inputs')?.valueString),
|
||||
evaluated: localDay(r.meta?.lastUpdated),
|
||||
// the clinical scenarios of the model's report she falls in
|
||||
scenarios: (r.extension ?? [])
|
||||
.filter((e) => e.url === EXT + 'escenario-clinico')
|
||||
.map((e) => e.valueString ?? ''),
|
||||
predictions: (r.prediction ?? []).map((p) => ({
|
||||
years: p.whenRange?.high?.value ?? 0,
|
||||
p: p.probabilityDecimal ?? 0,
|
||||
low: ext(p, 'ic-bajo')?.valueDecimal,
|
||||
high: ext(p, 'ic-alto')?.valueDecimal,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
export type Model = ReturnType<typeof models>[number];
|
||||
@@ -0,0 +1,65 @@
|
||||
<mat-card appearance="outlined" data-section="riesgos">
|
||||
@if (excluded(); as reason) {
|
||||
<mat-card-header>
|
||||
<mat-card-title>Sin estimación de riesgo: criterio de exclusión</mat-card-title>
|
||||
</mat-card-header>
|
||||
<mat-card-content>
|
||||
<p role="status" data-state="excluded">{{ reason }}</p>
|
||||
</mat-card-content>
|
||||
} @else {
|
||||
<mat-card-content>
|
||||
@if (note(); as said) {
|
||||
<p class="muted note" data-state="toma">{{ said }}</p>
|
||||
}
|
||||
<app-risk-scales [groups]="groups()" />
|
||||
@if (models().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 models(); track m.model) {
|
||||
@for (p of m.predictions; track p.years) {
|
||||
<tr>
|
||||
<td>{{ $first ? m.text : '' }}</td>
|
||||
<td>{{ $first ? m.index : '' }}</td>
|
||||
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
|
||||
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
|
||||
<td>
|
||||
@if (p.low !== undefined && p.high !== undefined) {
|
||||
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high * 100 | number: '1.1-2' }} %
|
||||
} @else {
|
||||
—
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
}
|
||||
@if (models().length || drawn()) {
|
||||
<details class="curves" open data-section="curvas">
|
||||
<summary>Curvas de probabilidad con su intervalo</summary>
|
||||
@if (drawn(); as series) {
|
||||
<app-risk-series [series]="series" />
|
||||
} @else {
|
||||
<app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
|
||||
}
|
||||
</details>
|
||||
}
|
||||
@if (!models().length) {
|
||||
<p class="muted">Sin evaluación de un modelo en producción.</p>
|
||||
}
|
||||
</mat-card-content>
|
||||
}
|
||||
</mat-card>
|
||||
@@ -0,0 +1,79 @@
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Component, computed, inject, input, resource } from '@angular/core';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import type { Parameters } from 'fhir/r4';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { Plot } from '../plot';
|
||||
import type { Model } from './record';
|
||||
import { curveFigure } from './risk-curve';
|
||||
import { RiskGroup, RiskScales } from './risk-scales';
|
||||
import { parseSeries, RiskSeries } from './risk-series';
|
||||
|
||||
/** Her risk: why she has none, or the scales of each model, its values and its curves (CaCu: with
|
||||
* the series `$risk-series` publishes, when the API has them on). */
|
||||
@Component({
|
||||
selector: 'app-risk-card',
|
||||
imports: [DecimalPipe, MatCardModule, Plot, RiskScales, RiskSeries],
|
||||
templateUrl: './risk-card.html',
|
||||
styles: `
|
||||
.note {
|
||||
font-size: 12px;
|
||||
margin: 8px 0 12px;
|
||||
}
|
||||
.curves {
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
margin-top: 12px;
|
||||
padding: 8px 12px;
|
||||
summary {
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class RiskCard {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly root = inject(ApiConfiguration).rootUrl;
|
||||
readonly domain = input.required<string>();
|
||||
readonly id = input.required<string>();
|
||||
readonly cutoff = input<string>();
|
||||
/** the day of the cytology her estimates speak of */
|
||||
readonly sample = input<string>();
|
||||
/** the models whose estimate is a risk (not survival or recurrence) */
|
||||
readonly models = input.required<Model[]>();
|
||||
readonly groups = input.required<RiskGroup[]>();
|
||||
/** why she has no estimate, when she has none */
|
||||
readonly excluded = input<string>();
|
||||
readonly note = input<string>();
|
||||
|
||||
/** CaCu, experimental: the series her record compares; none while the API has them off. */
|
||||
protected readonly series = resource({
|
||||
params: () =>
|
||||
this.domain() === 'cacu'
|
||||
? { id: this.id(), cutoff: this.cutoff(), sample: this.sample()?.slice(0, 10) }
|
||||
: undefined,
|
||||
loader: async ({ params: { id, ...asked } }) => {
|
||||
const params = Object.fromEntries(Object.entries(asked).filter(([, v]) => !!v)) as never;
|
||||
const url = `${this.root}/cacu/fhir/Patient/${id}/$risk-series`;
|
||||
try {
|
||||
return parseSeries(await firstValueFrom(this.http.get<Parameters>(url, { params })));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
});
|
||||
protected readonly drawn = computed(() =>
|
||||
this.series.hasValue() && this.series.value()?.some((s) => s.points.length)
|
||||
? this.series.value()
|
||||
: undefined,
|
||||
);
|
||||
protected readonly curve = computed(() =>
|
||||
curveFigure(
|
||||
this.models(),
|
||||
Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Figure, PALETTE } from '../plot';
|
||||
import type { Prediction } from './risk-scales';
|
||||
|
||||
/** A model's (or a source's) probabilities by horizon. */
|
||||
export interface CurveModel {
|
||||
/** its own title, with its version */
|
||||
text: string;
|
||||
/** its index date ('' when it has none) */
|
||||
index: string;
|
||||
predictions: Prediction[];
|
||||
}
|
||||
|
||||
const title = (m: CurveModel) =>
|
||||
m.text
|
||||
.replace(/ v\d+$/, '')
|
||||
.replace(/riesgo/gi, (w) => (w[0] === 'R' ? 'Probabilidad' : 'probabilidad'));
|
||||
const bounded = (p: Prediction) => p.low !== undefined && p.high !== undefined;
|
||||
const percent = (n: number | undefined) => (n === undefined ? null : n * 100);
|
||||
|
||||
/** One series per model drawn only at the horizons it publishes (one horizon is a point); its
|
||||
* 95 % interval a band where two or more horizons have one, else an error bar. Nothing is made up
|
||||
* between horizons: a gap in the intervals stays a gap. */
|
||||
export function curveFigure(models: CurveModel[], top: number): Figure {
|
||||
const shown = models.filter((m) => m.predictions.length);
|
||||
const ticks = [...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))];
|
||||
const 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 banded = sorted.filter(bounded).length;
|
||||
const edge = (pick: (p: Prediction) => number | undefined) => ({
|
||||
x,
|
||||
y: sorted.map((p) => (bounded(p) ? percent(pick(p)) : null)),
|
||||
mode: 'lines',
|
||||
line: { width: 0 },
|
||||
connectgaps: false,
|
||||
legendgroup: name,
|
||||
hoverinfo: 'skip',
|
||||
});
|
||||
const band =
|
||||
banded > 1
|
||||
? [
|
||||
{ ...edge((p) => p.high), showlegend: false },
|
||||
{
|
||||
...edge((p) => p.low),
|
||||
fill: 'tonexty',
|
||||
fillcolor: color + '33',
|
||||
name: `IC 95 % ${name}`,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const bar = sorted.map((p) => (bounded(p) ? (p.high! - p.p) * 100 : 0));
|
||||
const barMinus = sorted.map((p) => (bounded(p) ? (p.p - p.low!) * 100 : 0));
|
||||
return [
|
||||
...band,
|
||||
{
|
||||
x,
|
||||
y: sorted.map((p) => p.p * 100),
|
||||
mode: sorted.length > 1 ? 'lines+markers' : 'markers',
|
||||
name,
|
||||
legendgroup: name,
|
||||
line: { color },
|
||||
marker: { color, size: 8 },
|
||||
...(banded === 1
|
||||
? { error_y: { type: 'data', symmetric: false, color, array: bar, arrayminus: barMinus } }
|
||||
: {}),
|
||||
hovertemplate: `${name}<br>%{x} años: %{y:.2f} %<extra></extra>`,
|
||||
},
|
||||
];
|
||||
});
|
||||
const at = dates.length === 1 && dates[0] ? ` (${dates[0]})` : '';
|
||||
return {
|
||||
data,
|
||||
layout: {
|
||||
xaxis: {
|
||||
title: { text: `Horizonte (años desde la fecha índice${at})` },
|
||||
tickmode: 'array',
|
||||
tickvals: ticks,
|
||||
ticktext: ticks.map(String),
|
||||
},
|
||||
// at least 0–5 %: a near-zero probability reads as near zero, not as a full axis
|
||||
yaxis: {
|
||||
title: { text: 'Probabilidad (%)' },
|
||||
range: [0, Math.max(5, top * 110)],
|
||||
tickformat: '.0f',
|
||||
},
|
||||
},
|
||||
} as Figure;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
@for (g of groups(); track $index) {
|
||||
@if (g.title) {
|
||||
<h3>{{ g.title }}</h3>
|
||||
}
|
||||
@for (s of g.scales; track s.label) {
|
||||
<div class="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="plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
|
||||
<div class="line" aria-hidden="true"></div>
|
||||
@if (s.risk; as r) {
|
||||
@if (r.low !== undefined && r.high !== undefined) {
|
||||
<span
|
||||
class="interval"
|
||||
[style.left.%]="r.low * 100"
|
||||
[style.width.%]="(r.high - r.low) * 100"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
}
|
||||
<span class="marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
|
||||
<strong
|
||||
class="value"
|
||||
[style.left]="'clamp(2.5rem, ' + r.p * 100 + '%, calc(100% - 2.5rem))'"
|
||||
>{{ r.p * 100 | number: '1.1-2' }} %</strong
|
||||
>
|
||||
}
|
||||
</div>
|
||||
<div class="ticks" aria-hidden="true">
|
||||
@for (t of [0, 25, 50, 75, 100]; track t) {
|
||||
<span>{{ t }} %</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 (i of entries(g.inputs); track i[0]) {
|
||||
<div>
|
||||
<dt>{{ inputName(i[0]) }}</dt>
|
||||
<dd>{{ inputValue(i[0], i[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 (i of entries(g.inputs); track i[0]) {
|
||||
<div>{{ inputName(i[0]) }}: {{ inputValue(i[0], i[1]) }}</div>
|
||||
} @empty {
|
||||
No disponibles para esta estimación.
|
||||
}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
$ink: #17324d;
|
||||
|
||||
.scale {
|
||||
margin: 8px 0 14px;
|
||||
max-width: 740px;
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
.plot {
|
||||
padding-top: 30px;
|
||||
position: relative;
|
||||
}
|
||||
// four equal parts, low to high; survival reads the other way
|
||||
.line {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
#42a77e 0 25%,
|
||||
#a8c243 25% 50%,
|
||||
#df8640 50% 75%,
|
||||
#c24269 75% 100%
|
||||
);
|
||||
height: 12px;
|
||||
}
|
||||
.survival .line {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
#c24269 0 25%,
|
||||
#df8640 25% 50%,
|
||||
#a8c243 50% 75%,
|
||||
#42a77e 75% 100%
|
||||
);
|
||||
}
|
||||
.unavailable .line {
|
||||
background: repeating-linear-gradient(
|
||||
to right,
|
||||
#d9dfe2 0,
|
||||
#d9dfe2 calc(25% - 1px),
|
||||
#fff calc(25% - 1px),
|
||||
#fff 25%
|
||||
);
|
||||
}
|
||||
.interval {
|
||||
border-left: 2px solid $ink;
|
||||
border-right: 2px solid $ink;
|
||||
height: 8px;
|
||||
min-width: 2px;
|
||||
position: absolute;
|
||||
top: 32px;
|
||||
&::before {
|
||||
background: $ink;
|
||||
content: '';
|
||||
height: 2px;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 3px;
|
||||
}
|
||||
}
|
||||
.marker {
|
||||
background: $ink;
|
||||
bottom: -2px;
|
||||
height: 20px;
|
||||
position: absolute;
|
||||
transform: translateX(-50%);
|
||||
width: 3px;
|
||||
}
|
||||
.value {
|
||||
color: $ink;
|
||||
font-size: 13px;
|
||||
position: absolute;
|
||||
top: 1px;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ticks {
|
||||
display: flex;
|
||||
font-size: 12px;
|
||||
justify-content: space-between;
|
||||
margin-top: 3px;
|
||||
}
|
||||
.foot {
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { curveFigure } from './risk-curve';
|
||||
import { group, hpvApart } from './record-groups';
|
||||
import { horizon, riskGroups, survivalGroups, titleParts } from './risk-scales';
|
||||
import { parseSeries, seriesName } from './risk-series';
|
||||
import { insufficientText, sortUndrawn } from './survival';
|
||||
|
||||
describe('risk scales', () => {
|
||||
it('take a horizon only as published, zero included, and an interval only when whole', () => {
|
||||
const p = [
|
||||
{ years: 0, p: 0 },
|
||||
{ years: 5, p: 0.2, low: 0.3, high: 0.1 },
|
||||
{ years: 3, p: 1.4 },
|
||||
];
|
||||
expect(horizon(p, 0)).toEqual({ years: 0, p: 0 });
|
||||
expect(horizon(p, 5)).toEqual({ years: 5, p: 0.2 });
|
||||
expect(horizon(p, 3)).toBeUndefined();
|
||||
expect(horizon(p, 1)).toBeUndefined();
|
||||
});
|
||||
it('name a model by its outcome and scenario, and say both horizons even when none is known', () => {
|
||||
expect(titleParts('Riesgo de CIN3+ en precolposcopía v2')).toEqual({
|
||||
title: 'Probabilidad de CIN3+',
|
||||
scenario: 'precolposcopía',
|
||||
});
|
||||
expect(riskGroups([])[0].scales.map((s) => s.risk)).toEqual([undefined, undefined]);
|
||||
});
|
||||
it('turn survival models (mortality) into S(t), the interval turned too', () => {
|
||||
const [g] = survivalGroups([
|
||||
{
|
||||
text: 'Supervivencia v1',
|
||||
index: '2026-01-01',
|
||||
predictions: [{ years: 5, p: 0.1, low: 0.05, high: 0.2 }],
|
||||
},
|
||||
]);
|
||||
const risk = g.scales[0].risk!;
|
||||
expect([risk.p, risk.low, risk.high].map((v) => +v!.toFixed(2))).toEqual([0.9, 0.8, 0.95]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('risk curves', () => {
|
||||
it('band an interval published at two horizons and bar one published at one', () => {
|
||||
const banded = curveFigure(
|
||||
[
|
||||
{
|
||||
text: 'Riesgo de CIN3+ v1',
|
||||
index: '2026-01-01',
|
||||
predictions: [
|
||||
{ years: 0, p: 0.1, low: 0.05, high: 0.2 },
|
||||
{ years: 5, p: 0.2, low: 0.1, high: 0.3 },
|
||||
],
|
||||
},
|
||||
],
|
||||
0.3,
|
||||
);
|
||||
expect(banded.data.map((t) => t.name)).toEqual([
|
||||
undefined,
|
||||
'IC 95 % Probabilidad de CIN3+',
|
||||
'Probabilidad de CIN3+',
|
||||
]);
|
||||
const point = curveFigure(
|
||||
[{ text: 'x', index: '', predictions: [{ years: 5, p: 0.2, low: 0.1, high: 0.3 }] }],
|
||||
0.3,
|
||||
);
|
||||
expect(point.data).toHaveLength(1);
|
||||
expect((point.data[0] as { error_y?: object }).error_y).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('series and report gaps', () => {
|
||||
it('read a series as published and name the platform own as the hospital', () => {
|
||||
const [s] = parseSeries({
|
||||
resourceType: 'Parameters',
|
||||
parameter: [
|
||||
{
|
||||
name: 'series',
|
||||
part: [
|
||||
{ name: 'id', valueString: 'institutional-CIN3+' },
|
||||
{ name: 'source', valueString: 'Institucional' },
|
||||
{ name: 'outcome', valueString: 'CIN3+' },
|
||||
{
|
||||
name: 'point',
|
||||
part: [
|
||||
{ name: 'years', valueInteger: 5 },
|
||||
{ name: 'probability', valueDecimal: 0.04 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(seriesName(s)).toBe('ISSSTELEON, CIN3+');
|
||||
expect(s.points).toEqual([{ years: 5, p: 0.04, low: undefined, high: undefined }]);
|
||||
});
|
||||
it('tell a scenario short of deaths from one the report does not mention', () => {
|
||||
const report = {
|
||||
escenarios_sin_curvas: [{ escenario: 'A', n: 12, fallecidos: 1 }],
|
||||
min_fallecidos_escenario: 5,
|
||||
};
|
||||
const { insufficient, missing } = sortUndrawn(report, ['A', 'B']);
|
||||
expect(missing).toEqual(['B']);
|
||||
expect(insufficientText(insufficient[0])).toBe(
|
||||
'Datos insuficientes para trazar la curva (n = 12, fallecidos = 1; mínimo requerido: 5 fallecidos).',
|
||||
);
|
||||
});
|
||||
it('keep the form apart from the study: antecedents, results, findings and HPV', () => {
|
||||
const fact = (field: string, title: string, value: string) => ({
|
||||
study: 'cervical_cytology',
|
||||
field,
|
||||
title,
|
||||
value,
|
||||
});
|
||||
const { hpv, rest } = hpvApart([
|
||||
fact('hpv', 'VPH', 'positivo'),
|
||||
fact('screening_history', 'Detección', 'Subsecuente'),
|
||||
fact('result', 'Resultado', 'LIEBG'),
|
||||
fact('finding_trichomonas', 'Hallazgo: tricomonas', 'positivo'),
|
||||
fact('findings', 'Texto', 'inflamación'),
|
||||
]);
|
||||
expect(hpv.map((f) => f.field)).toEqual(['hpv']);
|
||||
expect(group(rest)).toEqual({
|
||||
antecedents: { screening_history: 'Subsecuente' },
|
||||
results: ['Resultado: LIEBG'],
|
||||
findings: ['Texto del informe: inflamación', 'Tricomonas'],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { Component, input } from '@angular/core';
|
||||
|
||||
export interface Prediction {
|
||||
years: number;
|
||||
p: number;
|
||||
low?: number;
|
||||
high?: number;
|
||||
}
|
||||
export interface RiskScale {
|
||||
label: string;
|
||||
risk?: Prediction;
|
||||
}
|
||||
/** One model's scales: its title, scenario and index, what it was fed and who scored her. */
|
||||
export interface RiskGroup {
|
||||
title?: string;
|
||||
scenario?: string;
|
||||
index?: string;
|
||||
/** S(t): its scale reads the other way (high is good) */
|
||||
survival?: boolean;
|
||||
inputs?: Record<string, unknown>;
|
||||
model?: string;
|
||||
evaluated?: string;
|
||||
scales: RiskScale[];
|
||||
}
|
||||
interface Scored {
|
||||
text: string;
|
||||
index: string;
|
||||
predictions: Prediction[];
|
||||
inputs?: Record<string, unknown>;
|
||||
evaluated?: string;
|
||||
scenarios?: string[];
|
||||
}
|
||||
|
||||
/** "Riesgo" as "probabilidad", its capital kept. */
|
||||
const probability = (text: string) =>
|
||||
text.replace(/riesgo/gi, (w) => (w[0] === 'R' ? 'Probabilidad' : 'probabilidad'));
|
||||
const unit = (n?: number): n is number => typeof n === 'number' && n >= 0 && n <= 1;
|
||||
const years = (n: number) => `${n} ${n === 1 ? 'año' : 'años'}`;
|
||||
|
||||
/** A model's prediction at one horizon when it is a probability: zero is a value, a missing
|
||||
* horizon or a value outside 0–1 is none, and an interval stands only when it is whole. */
|
||||
export function horizon(predictions: Prediction[], at: number): Prediction | undefined {
|
||||
const found = predictions.find((p) => p.years === at);
|
||||
if (!found || !unit(found.p)) return undefined;
|
||||
const whole = unit(found.low) && unit(found.high) && found.low <= found.high;
|
||||
return whole ? found : { years: at, p: found.p };
|
||||
}
|
||||
|
||||
/** Each model's probability at its index visit and at five years (the record's PDF). */
|
||||
export function riskScales(models: Scored[]): RiskScale[] {
|
||||
return models.flatMap((m) =>
|
||||
[0, 5].map((at) => ({
|
||||
label: `${probability(m.text)}, probabilidad ${at ? 'a 5 años' : 'inmediata'}`,
|
||||
risk: horizon(m.predictions, at),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
/** "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: probability(title), scenario };
|
||||
}
|
||||
|
||||
const HORIZONS: [number, string][] = [
|
||||
[0, 'Probabilidad inmediata (al índice)'],
|
||||
[5, 'Probabilidad a 5 años'],
|
||||
];
|
||||
|
||||
/** Both horizons of every risk model; with no model, both horizons unavailable. */
|
||||
export function riskGroups(models: Scored[]): RiskGroup[] {
|
||||
const scales = (p: Prediction[]) =>
|
||||
HORIZONS.map(([at, label]) => ({ label, risk: horizon(p, at) }));
|
||||
if (!models.length) return [{ scales: scales([]) }];
|
||||
return models.map((m) => ({
|
||||
...titleParts(m.text),
|
||||
index: m.index,
|
||||
inputs: m.inputs,
|
||||
model: m.text,
|
||||
evaluated: m.evaluated,
|
||||
scales: scales(m.predictions),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Survival models publish mortality: their scales are its complement, S(t), interval swapped. */
|
||||
export function survivalGroups(models: Scored[]): RiskGroup[] {
|
||||
const complement = (n?: number) => (n === undefined ? undefined : 1 - n);
|
||||
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
|
||||
.map((p) => horizon(m.predictions, p.years))
|
||||
.filter((v) => !!v)
|
||||
.map((v) => ({
|
||||
label: `Supervivencia a ${years(v.years)}`,
|
||||
risk: { years: v.years, p: 1 - v.p, low: complement(v.high), high: complement(v.low) },
|
||||
})),
|
||||
}))
|
||||
.filter((g) => g.scales.length);
|
||||
}
|
||||
|
||||
const INPUTS: Record<string, string> = {
|
||||
age_group: 'Edad al diagnóstico',
|
||||
cytology: 'Citología',
|
||||
bethesda: 'Citología',
|
||||
hpv: 'VPH',
|
||||
hpv_positive: 'VPH',
|
||||
hpv_16_18: 'VPH 16/18',
|
||||
hpv_16: 'VPH 16',
|
||||
hpv_18: 'VPH 18',
|
||||
referral_grade: 'Citología de referencia',
|
||||
};
|
||||
|
||||
/** A model input's value as the screens say it. */
|
||||
export function inputValue(name: string, value: unknown): string {
|
||||
if (value === null || value === undefined) return 'No documentado';
|
||||
if (name === 'referral_grade' && (value === 'high' || value === 'low'))
|
||||
return value === 'high' ? 'Alto grado' : 'Bajo grado';
|
||||
if (name.startsWith('hpv')) {
|
||||
if (value === 1 || value === true || value === 'positive') return 'Positivo';
|
||||
if (value === 0 || value === false || value === 'negative') return 'Negativo';
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/** Scales of 0 to 100 % in four equal parts (descriptive, not clinical thresholds), the
|
||||
* probability marked with its interval; one with no prediction is grey and says so. */
|
||||
@Component({
|
||||
selector: 'app-risk-scales',
|
||||
imports: [DecimalPipe],
|
||||
templateUrl: './risk-scales.html',
|
||||
styleUrl: './risk-scales.scss',
|
||||
})
|
||||
export class RiskScales {
|
||||
readonly groups = input.required<RiskGroup[]>();
|
||||
protected readonly entries = (o?: Record<string, unknown>) => Object.entries(o ?? {});
|
||||
protected readonly inputName = (name: string) => INPUTS[name] ?? name;
|
||||
protected readonly inputValue = inputValue;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user