Compare commits

...

24 Commits

Author SHA1 Message Date
Roberto Treviño fe4dd55452 CaCu's page by readings, screening stages, ages and exports 2026-11-30 23:31:58 -06:00
Roberto Treviño 053679c817 Connecting a database no longer freezes the page: the columns field keeps one empty list 2026-11-30 05:17:14 -06:00
Roberto Treviño ffa732df12 The page test follows the pages as they are 2026-11-30 02:14:16 -06:00
Roberto Treviño 786b199203 The generated API client matches the API 2026-11-29 21:15:12 -06:00
Roberto Treviño ca887c29ab Wording: formal, precise, no narrative; the missing reports of a promotion in Spanish 2026-11-29 15:24:25 -06:00
Roberto Treviño bb506c3926 Conectar: Configuración and Avanzado tabs, rows instead of JSON, field titles as keys, captions that fit their nodes 2026-11-29 15:24:24 -06:00
Roberto Treviño b48c025400 Page test: no overlapping, clipped or wrapped labels at 1440 and 820 px 2026-11-29 12:39:07 -06:00
Roberto Treviño a93cd71126 Cosmetic pass: legends above plots, readable hovers and ticks, KPI qualifiers, a header that never wraps 2026-11-29 12:39:07 -06:00
Roberto Treviño 979b7cf34d Gobernanza: the header's domain switcher, model titles, confirmations, a stop button, an upload button 2026-11-29 12:39:07 -06:00
Roberto Treviño cde9b1cfb1 Revisión: documents no route recognises; reasons and fields in Spanish 2026-11-29 12:39:07 -06:00
Roberto Treviño edc32af67e CaMa record as the old card: summary, mammography, histopathology, prognosis, risk of death and its scenarios' risk factors 2026-11-29 12:39:07 -06:00
Roberto Treviño 2216186d26 Patient lists have a search box; TEA alterations by their Spanish names 2026-11-29 12:39:07 -06:00
Roberto Treviño 55c4e0b173 OpenAPI client: model titles, run termination, Patient name and identifier 2026-11-29 12:39:07 -06:00
Roberto Treviño 52cca0a84c Record history shows only ICD-10 codes beside a diagnosis 2026-11-29 07:13:57 -06:00
Roberto Treviño 7e50ff9b90 OpenAPI spec names the configured promotion reports and CaMa's history 2026-11-29 06:58:38 -06:00
Roberto Treviño ac1d8fc4fa Records show the server's names for coded results; risk lists say empty only once loaded 2026-11-29 06:43:10 -06:00
Roberto Treviño d09e8c59ed Proxy waits up to two minutes for the API 2026-11-29 01:32:09 -06:00
Roberto Treviño 4a8e2e22bd Name breast recurrences in Revisión 2026-11-29 01:06:40 -06:00
Roberto Treviño 1655d464e1 Regenerate the API client for breast recurrences 2026-11-28 23:05:21 -06:00
Roberto Treviño e275782198 Recurrence scenarios leave Gobernanza: the record draws them 2026-11-28 21:30:01 -06:00
Roberto Treviño 133092f8c8 Record: Relación con el ADOS-2 and Análisis de recurrencia; Gobernanza draws the association 2026-11-28 21:28:42 -06:00
Roberto Treviño 6ea54d6e6d Trazabilidad, Datos y definiciones and the risk lists as the old app: declared panels, old labels and order; page tests against the capture 2026-11-28 17:24:29 -06:00
Roberto Treviño cbec0d431e Governance figures spec: scenarios are drawn by the record 2026-11-28 17:16:25 -06:00
Roberto Treviño fd19fdaefa TEA record: Zonas más afectadas (head map and zones by deviation); survival scenarios leave Gobernanza 2026-11-28 17:15:43 -06:00
83 changed files with 5168 additions and 602 deletions
+69
View File
@@ -0,0 +1,69 @@
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 de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', '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: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).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
View File
@@ -0,0 +1,122 @@
import type { Page } from '@playwright/test';
/** What breaks a page's layout, measured in the browser: overlapping texts (also inside
* Plotly figures: legend against axis titles, tick labels), labels clipped at a figure's
* edge, labels that wrap where they should not (buttons, badges), a header taller than one
* row, text cut by its own box, and a page wider than the window. Empty: nothing found. */
export async function layoutProblems(page: Page): Promise<string[]> {
return page.evaluate(() => {
const found: string[] = [];
const box = (e: Element) => e.getBoundingClientRect();
const hit = (a: DOMRect, b: DOMRect) =>
a.width > 0 &&
b.width > 0 &&
a.left < b.right - 1 &&
b.left < a.right - 1 &&
a.top < b.bottom - 1 &&
b.top < a.bottom - 1;
const where = (el: Element) => {
const card = el.closest('mat-card, section, .card');
const h = card?.querySelector('h1,h2,h3,h4,mat-card-title');
return (h?.textContent ?? '').trim().slice(0, 60);
};
if (document.documentElement.scrollWidth > window.innerWidth + 1)
found.push(
`page overflows horizontally: ${document.documentElement.scrollWidth} > ${window.innerWidth}`,
);
for (const plot of document.querySelectorAll('.js-plotly-plot')) {
const texts = [
...plot.querySelectorAll(
'.legend, .g-xtitle text, .g-ytitle text, .xtitle, .ytitle, .gtitle',
),
];
for (let i = 0; i < texts.length; i++)
for (let j = i + 1; j < texts.length; j++)
if (
!texts[i].contains(texts[j]) &&
!texts[j].contains(texts[i]) &&
hit(box(texts[i]), box(texts[j]))
)
found.push(
`plot "${where(plot)}": ${texts[i].getAttribute('class')} overlaps ${texts[j].getAttribute('class')}`,
);
const host = box(plot);
for (const t of plot.querySelectorAll('.slicetext, .xtick text, .ytick text, .legendtext')) {
const b = box(t);
if (b.width && (b.left < host.left - 1 || b.right > host.right + 1))
found.push(`plot "${where(plot)}": text "${t.textContent}" clipped at the edge`);
}
const ticks = [...plot.querySelectorAll('.xtick text')].map(box);
for (let i = 1; i < ticks.length; i++)
if (hit(ticks[i - 1], ticks[i])) {
found.push(`plot "${where(plot)}": x tick labels overlap`);
break;
}
}
// Text elements overlapping each other (headings, labels, buttons, table cells).
const els = [
...document.querySelectorAll<HTMLElement>(
'h1,h2,h3,h4,p,label,button,a,dt,dd,th,td,mat-card-title,.mdc-tab__text-label,mat-label,li',
),
].filter(
(e: any) =>
e.offsetParent &&
box(e).width > 0 &&
box(e).height > 0 &&
!e.closest('.js-plotly-plot, .cdk-overlay-container') &&
!e.closest('details:not([open]) > :not(summary)'),
);
for (let i = 0; i < els.length; i++)
for (let j = i + 1; j < Math.min(els.length, i + 40); j++) {
const a = els[i],
b = els[j];
if (a.contains(b) || b.contains(a)) continue;
if (hit(box(a), box(b)))
found.push(
`"${(a.textContent ?? '').trim().slice(0, 30)}" overlaps "${(b.textContent ?? '').trim().slice(0, 30)}" (${where(a)})`,
);
}
// Text cut by its own box (ellipsis or overflow hidden).
for (const e of document.querySelectorAll<HTMLElement>(
'button, .mdc-tab__text-label, th, mat-label, .mat-mdc-select-value-text',
))
if (
e.offsetParent &&
e.scrollWidth > e.clientWidth + 2 &&
getComputedStyle(e).overflow !== 'visible'
)
found.push(`text cut: "${(e.textContent ?? '').trim().slice(0, 40)}"`);
const header = document.querySelector('.header');
if (header && header.getBoundingClientRect().height > 90 && window.innerWidth > 720)
found.push(
`header taller than one row: ${Math.round(header.getBoundingClientRect().height)}px`,
);
for (const b of document.querySelectorAll<HTMLElement>(
'button:not(.mat-button-toggle-button), a.mdc-button, .badge, .mat-mdc-chip',
)) {
const label = (b.querySelector('.mdc-button__label') as HTMLElement | null) ?? b;
const lines =
label.getClientRects().length &&
Math.round(
label.getBoundingClientRect().height /
parseFloat(getComputedStyle(label).lineHeight || '20'),
);
if (b.offsetParent && lines > 1 && (label.textContent ?? '').trim().length < 40)
found.push(`label wraps: "${(label.textContent ?? '').trim()}"`);
}
const icons = [
...document.querySelectorAll('header mat-icon, header a, header button, header .title'),
];
for (let i = 0; i < icons.length; i++)
for (let j = i + 1; j < icons.length; j++)
if (
!icons[i].contains(icons[j]) &&
!icons[j].contains(icons[i]) &&
hit(box(icons[i]), box(icons[j]))
)
found.push(
`header: "${(icons[i].textContent ?? '').trim().slice(0, 20)}" overlaps "${(icons[j].textContent ?? '').trim().slice(0, 20)}"`,
);
return [...new Set(found)];
});
}
+127 -10
View File
@@ -1,5 +1,6 @@
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test'; import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */ /** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] { function watch(page: Page): string[] {
@@ -58,10 +59,10 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14); await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14); await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
@@ -72,7 +73,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(rows).toHaveCount(Math.min(20, bundle.total)); await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first); await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click(); await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(`21–`)).toBeVisible(); await expect(page.getByText('Página 2 de')).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click(); await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click(); await rows.first().locator('a').first().click();
@@ -101,12 +102,17 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar'); await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click(); await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible(); await expect(page.locator('vflow')).toBeVisible();
await page.getByText('Fuente de datos · Patients').click(); // a node's caption: its kind, then its name
await expect(page.locator('formly-form')).toBeVisible(); // drawn by hand: its raw form await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click(); await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible(); await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows. // A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Traducir códigos · cytology', { exact: true }).click(); await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible(); await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect await expect
.poll(() => .poll(() =>
@@ -139,13 +145,13 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
}) => { }) => {
const problems = watch(page); const problems = watch(page);
await page.goto('/gobernanza/cama'); await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'survival' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' }); const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible(); await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click(); await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible(); await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click(); await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('clinical_validation'); await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]); expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
}); });
@@ -171,7 +177,7 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible(); await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados'); await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click(); await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.getByText('Fuente de datos · Resultados')).toBeVisible(); await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace. // A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click(); await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it'); await page.locator('[data-field="password"]').fill('not-it');
@@ -199,7 +205,8 @@ function captured(domain: string) {
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>'); const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) { // CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({ test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page, page,
}) => { }) => {
@@ -227,3 +234,113 @@ for (const domain of ['cacu', 'cama', 'tea']) {
for (const types of drawn) expect(kinds).toContain(kindOf(types)); for (const types of drawn) expect(kinds).toContain(kindOf(types));
}); });
} }
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,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
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 drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).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([]);
});
}
+1 -1
View File
@@ -3,7 +3,7 @@ server {
root /usr/share/nginx/html; root /usr/share/nginx/html;
location /api/ { location /api/ {
proxy_pass http://api:8000/; proxy_pass http://api:8000/;
proxy_read_timeout 30s; proxy_read_timeout 120s;
} }
location / { location / {
try_files $uri $uri/ /index.html; try_files $uri $uri/ /index.html;
+488 -12
View File
@@ -36,6 +36,14 @@
"title": "Metrics", "title": "Metrics",
"type": "array" "type": "array"
}, },
"relation": {
"default": [],
"items": {
"$ref": "#/components/schemas/Relation"
},
"title": "Relation",
"type": "array"
},
"valid": { "valid": {
"anyOf": [ "anyOf": [
{ {
@@ -289,6 +297,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -413,6 +422,7 @@
}, },
"default": {}, "default": {},
"description": "Dato \u2192 columna, sin leer el texto.", "description": "Dato \u2192 columna, sin leer el texto.",
"keys": "field",
"title": "Datos tomados de columnas", "title": "Datos tomados de columnas",
"type": "object" "type": "object"
}, },
@@ -438,6 +448,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -445,13 +456,70 @@
"eeg" "eeg"
], ],
"title": "Estudio", "title": "Estudio",
"type": "string" "type": "string",
"widget": {
"formlyConfig": {
"props": {
"options": [
{
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
},
{
"label": "Biopsia cervical",
"value": "cervical_biopsy"
},
{
"label": "Mastograf\u00eda",
"value": "mammography"
},
{
"label": "Biopsia de mama",
"value": "breast_biopsy"
},
{
"label": "Tratamiento de c\u00e1ncer de mama",
"value": "breast_treatment"
},
{
"label": "Recurrencia de c\u00e1ncer de mama",
"value": "breast_recurrence"
},
{
"label": "Nota m\u00e9dica",
"value": "clinical_note"
},
{
"label": "Defunci\u00f3n",
"value": "death"
},
{
"label": "M-CHAT-R/F",
"value": "mchat"
},
{
"label": "ADOS-2",
"value": "ados2"
},
{
"label": "Electroencefalograma",
"value": "eeg"
}
]
}
}
}
}, },
"formats": { "formats": {
"additionalProperties": { "additionalProperties": {
"type": "string" "type": "string"
}, },
"default": {}, "default": {},
"keys": "field",
"title": "Formatos de fecha", "title": "Formatos de fecha",
"type": "object" "type": "object"
}, },
@@ -525,6 +593,7 @@
}, },
"default": {}, "default": {},
"description": "Dato \u2192 expresi\u00f3n con un grupo ( ).", "description": "Dato \u2192 expresi\u00f3n con un grupo ( ).",
"keys": "field",
"title": "Patrones", "title": "Patrones",
"type": "object" "type": "object"
}, },
@@ -577,6 +646,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -584,7 +654,63 @@
"eeg" "eeg"
], ],
"title": "Estudio", "title": "Estudio",
"type": "string" "type": "string",
"widget": {
"formlyConfig": {
"props": {
"options": [
{
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
},
{
"label": "Biopsia cervical",
"value": "cervical_biopsy"
},
{
"label": "Mastograf\u00eda",
"value": "mammography"
},
{
"label": "Biopsia de mama",
"value": "breast_biopsy"
},
{
"label": "Tratamiento de c\u00e1ncer de mama",
"value": "breast_treatment"
},
{
"label": "Recurrencia de c\u00e1ncer de mama",
"value": "breast_recurrence"
},
{
"label": "Nota m\u00e9dica",
"value": "clinical_note"
},
{
"label": "Defunci\u00f3n",
"value": "death"
},
{
"label": "M-CHAT-R/F",
"value": "mchat"
},
{
"label": "ADOS-2",
"value": "ados2"
},
{
"label": "Electroencefalograma",
"value": "eeg"
}
]
}
}
}
}, },
"id": { "id": {
"maxLength": 40, "maxLength": 40,
@@ -694,7 +820,8 @@
"url", "url",
"oauth", "oauth",
"table", "table",
"format" "format",
"columns"
], ],
"title": "Type", "title": "Type",
"type": "string" "type": "string"
@@ -817,7 +944,7 @@
"type": "string" "type": "string"
}, },
"on": { "on": {
"description": "Pares [columna izquierda, derecha].", "description": "Columna de la primera entrada = columna de la segunda.",
"items": { "items": {
"maxItems": 2, "maxItems": 2,
"minItems": 2, "minItems": 2,
@@ -992,6 +1119,7 @@
"type": "string" "type": "string"
}, },
"description": "Dato de la plataforma \u2192 columna del sitio.", "description": "Dato de la plataforma \u2192 columna del sitio.",
"keys": "field",
"title": "Campos", "title": "Campos",
"type": "object" "type": "object"
}, },
@@ -1001,6 +1129,7 @@
}, },
"default": {}, "default": {},
"description": "Por ejemplo %d/%m/%Y.", "description": "Por ejemplo %d/%m/%Y.",
"keys": "field",
"title": "Formatos de fecha", "title": "Formatos de fecha",
"type": "object" "type": "object"
}, },
@@ -1048,6 +1177,7 @@
}, },
"default": {}, "default": {},
"description": "Un dato igual para todas las filas.", "description": "Un dato igual para todas las filas.",
"keys": "field",
"title": "Valores fijos", "title": "Valores fijos",
"type": "object" "type": "object"
} }
@@ -1065,6 +1195,14 @@
"title": "Code", "title": "Code",
"type": "string" "type": "string"
}, },
"electrodes": {
"default": [],
"items": {
"$ref": "#/components/schemas/Site"
},
"title": "Electrodes",
"type": "array"
},
"median": { "median": {
"anyOf": [ "anyOf": [
{ {
@@ -1134,6 +1272,14 @@
} }
], ],
"title": "Z" "title": "Z"
},
"zones": {
"default": [],
"items": {
"$ref": "#/components/schemas/Site"
},
"title": "Zones",
"type": "array"
} }
}, },
"required": [ "required": [
@@ -1146,6 +1292,24 @@
"title": "Metric", "title": "Metric",
"type": "object" "type": "object"
}, },
"Model": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"title": {
"title": "Title",
"type": "string"
}
},
"required": [
"name",
"title"
],
"title": "Model",
"type": "object"
},
"Option": { "Option": {
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
@@ -1371,6 +1535,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -1397,6 +1562,122 @@
"title": "Rejection", "title": "Rejection",
"type": "object" "type": "object"
}, },
"Relation": {
"description": "One pair of the champion EEG\u2013ADOS-2 association, for this EEG (models.tea.association).",
"properties": {
"biomarker": {
"title": "Biomarker",
"type": "string"
},
"ci_high": {
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
],
"title": "Ci High"
},
"ci_low": {
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
],
"title": "Ci Low"
},
"event": {
"title": "Event",
"type": "string"
},
"kind": {
"title": "Kind",
"type": "string"
},
"metric": {
"title": "Metric",
"type": "string"
},
"model": {
"title": "Model",
"type": "string"
},
"n": {
"title": "N",
"type": "number"
},
"observed": {
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
],
"title": "Observed"
},
"odds_ratio": {
"title": "Odds Ratio",
"type": "number"
},
"outcome_code": {
"title": "Outcome Code",
"type": "string"
},
"probability": {
"title": "Probability",
"type": "number"
},
"q": {
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
],
"title": "Q"
},
"reference_probability": {
"title": "Reference Probability",
"type": "number"
},
"z": {
"title": "Z",
"type": "number"
},
"zone": {
"title": "Zone",
"type": "string"
}
},
"required": [
"biomarker",
"metric",
"zone",
"outcome_code",
"kind",
"event",
"z",
"probability",
"reference_probability",
"odds_ratio",
"ci_low",
"ci_high",
"q",
"n",
"model"
],
"title": "Relation",
"type": "object"
},
"Route": { "Route": {
"additionalProperties": false, "additionalProperties": false,
"description": "Only the rows where every condition holds (e.g. reports titled \"Citolog\u00eda\"). An\n`otherwise` route takes the rows of its input that none of the other routes on that\ninput take (documents nobody recognises, for a reviewer), then its own conditions.", "description": "Only the rows where every condition holds (e.g. reports titled \"Citolog\u00eda\"). An\n`otherwise` route takes the rows of its input that none of the other routes on that\ninput take (documents nobody recognises, for a reviewer), then its own conditions.",
@@ -1512,18 +1793,50 @@
"title": "SignIn", "title": "SignIn",
"type": "object" "type": "object"
}, },
"Site": {
"properties": {
"site": {
"title": "Site",
"type": "string"
},
"value": {
"title": "Value",
"type": "number"
},
"z": {
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
],
"title": "Z"
}
},
"required": [
"site",
"value",
"z"
],
"title": "Site",
"type": "object"
},
"Source": { "Source": {
"additionalProperties": false, "additionalProperties": false,
"description": "One table, file set or API resource, copied as it is (dlt). Merged on the source's\nown primary key or `primary_key`; replaced whole when it has none.", "description": "One table, file set or API resource, copied as it is (dlt). Merged on the source's\nown primary key or `primary_key`; replaced whole when it has none.",
"properties": { "properties": {
"args": { "args": {
"additionalProperties": true, "additionalProperties": true,
"advanced": true,
"default": {}, "default": {},
"description": "Los de la fuente dlt.", "description": "Los de la fuente dlt.",
"title": "Argumentos (JSON)", "title": "Argumentos",
"type": "object" "type": "object"
}, },
"guided": { "guided": {
"advanced": true,
"anyOf": [ "anyOf": [
{ {
"$ref": "#/components/schemas/Guided" "$ref": "#/components/schemas/Guided"
@@ -1531,7 +1844,8 @@
{ {
"type": "null" "type": "null"
} }
] ],
"title": "Asistente"
}, },
"id": { "id": {
"maxLength": 40, "maxLength": 40,
@@ -1572,6 +1886,7 @@
] ]
}, },
"primary_key": { "primary_key": {
"advanced": true,
"default": [], "default": [],
"description": "Columnas que identifican una fila.", "description": "Columnas que identifican una fila.",
"items": { "items": {
@@ -1581,6 +1896,7 @@
"type": "array" "type": "array"
}, },
"resource": { "resource": {
"advanced": true,
"anyOf": [ "anyOf": [
{ {
"type": "string" "type": "string"
@@ -1593,12 +1909,14 @@
"title": "Recurso" "title": "Recurso"
}, },
"source": { "source": {
"advanced": true,
"description": "M\u00f3dulo:funci\u00f3n de la fuente dlt.", "description": "M\u00f3dulo:funci\u00f3n de la fuente dlt.",
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$", "pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
"title": "Fuente dlt", "title": "Fuente dlt",
"type": "string" "type": "string"
}, },
"then": { "then": {
"advanced": true,
"anyOf": [ "anyOf": [
{ {
"pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$", "pattern": "^[A-Za-z_][\\w.]*:[A-Za-z_]\\w*$",
@@ -1804,6 +2122,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -1811,7 +2130,63 @@
"eeg" "eeg"
], ],
"title": "Estudio", "title": "Estudio",
"type": "string" "type": "string",
"widget": {
"formlyConfig": {
"props": {
"options": [
{
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
},
{
"label": "Biopsia cervical",
"value": "cervical_biopsy"
},
{
"label": "Mastograf\u00eda",
"value": "mammography"
},
{
"label": "Biopsia de mama",
"value": "breast_biopsy"
},
{
"label": "Tratamiento de c\u00e1ncer de mama",
"value": "breast_treatment"
},
{
"label": "Recurrencia de c\u00e1ncer de mama",
"value": "breast_recurrence"
},
{
"label": "Nota m\u00e9dica",
"value": "clinical_note"
},
{
"label": "Defunci\u00f3n",
"value": "death"
},
{
"label": "M-CHAT-R/F",
"value": "mchat"
},
{
"label": "ADOS-2",
"value": "ados2"
},
{
"label": "Electroencefalograma",
"value": "eeg"
}
]
}
}
}
}, },
"id": { "id": {
"maxLength": 40, "maxLength": 40,
@@ -3223,6 +3598,7 @@
}, },
"/models/{domain}": { "/models/{domain}": {
"get": { "get": {
"description": "The domain's registered models, with their names on screen.",
"operationId": "models", "operationId": "models",
"parameters": [ "parameters": [
{ {
@@ -3240,7 +3616,7 @@
"application/json": { "application/json": {
"schema": { "schema": {
"items": { "items": {
"type": "string" "$ref": "#/components/schemas/Model"
}, },
"title": "Response Models", "title": "Response Models",
"type": "array" "type": "array"
@@ -3470,7 +3846,7 @@
}, },
"/models/{domain}/{name}/versions/{version}/promote": { "/models/{domain}/{name}/versions/{version}/promote": {
"post": { "post": {
"description": "The version risk batches come from from now on; refused (409) without its three\nreports: technical validation, interpretability and clinical validation.", "description": "The version risk batches come from from now on; refused (409) without the reports\nthe site requires (PROMOTION_REPORTS; default: technical validation, interpretability\nand clinical validation).",
"operationId": "promote", "operationId": "promote",
"parameters": [ "parameters": [
{ {
@@ -3532,7 +3908,7 @@
}, },
"/models/{domain}/{name}/versions/{version}/reports/clinical_validation": { "/models/{domain}/{name}/versions/{version}/reports/clinical_validation": {
"post": { "post": {
"description": "The clinical team's validation of a version: the third report promotion needs.", "description": "The clinical team's validation of a version: the third report, which promotion needs\nunless the site left it out of PROMOTION_REPORTS.",
"operationId": "add_clinical_validation", "operationId": "add_clinical_validation",
"parameters": [ "parameters": [
{ {
@@ -3685,6 +4061,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -3792,6 +4169,7 @@
"mammography", "mammography",
"breast_biopsy", "breast_biopsy",
"breast_treatment", "breast_treatment",
"breast_recurrence",
"clinical_note", "clinical_note",
"death", "death",
"mchat", "mchat",
@@ -4086,6 +4464,53 @@
] ]
} }
}, },
"/runs/{run_id}/terminate": {
"post": {
"description": "Stop a run (one started by mistake): Dagster cancels it.",
"operationId": "terminate_run",
"parameters": [
{
"in": "path",
"name": "run_id",
"required": true,
"schema": {
"title": "Run Id",
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"additionalProperties": {
"type": "string"
},
"title": "Response Terminate Run",
"type": "object"
}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Terminate Run",
"tags": [
"runs"
]
}
},
"/tea/eegs": { "/tea/eegs": {
"get": { "get": {
"operationId": "studies", "operationId": "studies",
@@ -4596,7 +5021,7 @@
}, },
"/{domain}/fhir/Condition": { "/{domain}/fhir/Condition": {
"get": { "get": {
"description": "What clinical notes diagnosed.", "description": "What clinical notes diagnosed (CaMa: and each recurrence).",
"operationId": "search_condition", "operationId": "search_condition",
"parameters": [ "parameters": [
{ {
@@ -5266,6 +5691,57 @@
"title": "Follow-Up-Status" "title": "Follow-Up-Status"
} }
}, },
{
"description": "each word starts a word of her name (case and accents ignored)",
"in": "query",
"name": "name",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "each word starts a word of her name (case and accents ignored)",
"title": "Name"
}
},
{
"description": "[system|]value: a CURP or record number (case ignored)",
"in": "query",
"name": "identifier",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "[system|]value: a CURP or record number (case ignored)",
"title": "Identifier"
}
},
{
"description": "gt, ge, lt or le and a day (2000-12-31)",
"in": "query",
"name": "birthdate",
"required": false,
"schema": {
"default": [],
"description": "gt, ge, lt or le and a day (2000-12-31)",
"items": {
"type": "string"
},
"title": "Birthdate",
"type": "array"
}
},
{ {
"description": "-recent or -risk-<outcome>", "description": "-recent or -risk-<outcome>",
"in": "query", "in": "query",
@@ -5433,7 +5909,7 @@
}, },
"/{domain}/fhir/Procedure": { "/{domain}/fhir/Procedure": {
"get": { "get": {
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments).", "description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
"operationId": "search_procedure", "operationId": "search_procedure",
"parameters": [ "parameters": [
{ {
+285 -2
View File
@@ -25,9 +25,11 @@
"d3-zoom": "3.0.0", "d3-zoom": "3.0.0",
"material-symbols": "0.48.3", "material-symbols": "0.48.3",
"ngx-vflow": "2.7.0", "ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2", "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"tslib": "^2.3.0" "tslib": "^2.3.0",
"write-excel-file": "4.1.1"
}, },
"devDependencies": { "devDependencies": {
"@angular/build": "^22.3.0", "@angular/build": "^22.3.0",
@@ -38,6 +40,7 @@
"@types/d3-selection": "3.0.13", "@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9", "@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
@@ -2402,6 +2405,30 @@
"@ngx-formly/core": "11.2.0" "@ngx-formly/core": "11.2.0"
} }
}, },
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": { "node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.158.0", "version": "0.158.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz", "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
@@ -3465,6 +3492,12 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": { "node_modules/@tybys/wasm-util": {
"version": "0.10.5", "version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
@@ -3570,6 +3603,37 @@
"license": "MIT", "license": "MIT",
"peer": true "peer": true
}, },
"node_modules/@types/node": {
"version": "26.6.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/pdfkit": {
"version": "0.17.7",
"resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz",
"integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/pdfmake": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@types/pdfmake/-/pdfmake-0.3.5.tgz",
"integrity": "sha512-AQI4ISWzt7qmnKaipkikibz9x2XIvU/1zqfEHwKhBU7vP6oIhlGoLB9KsSIAryH7f9uuJebXScldb6F4ebwFxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/pdfkit": "*"
}
},
"node_modules/@types/plotly.js": { "node_modules/@types/plotly.js": {
"version": "3.0.15", "version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz", "resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
@@ -3816,6 +3880,15 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": { "node_modules/baseline-browser-mapping": {
"version": "2.11.39", "version": "2.11.39",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz",
@@ -3891,6 +3964,35 @@
"url": "https://github.com/sponsors/fb55" "url": "https://github.com/sponsors/fb55"
} }
}, },
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": { "node_modules/browserslist": {
"version": "4.29.6", "version": "4.29.6",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
@@ -4119,6 +4221,15 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1" "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
} }
}, },
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/colorjs.io": { "node_modules/colorjs.io": {
"version": "0.7.1", "version": "0.7.1",
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz", "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz",
@@ -4326,6 +4437,12 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": { "node_modules/dom-serializer": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
@@ -4561,7 +4678,6 @@
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-string-truncated-width": { "node_modules/fast-string-truncated-width": {
@@ -4626,6 +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": { "node_modules/flru": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -4636,6 +4758,23 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/fs-extra": { "node_modules/fs-extra": {
"version": "11.4.1", "version": "11.4.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
@@ -5366,6 +5505,16 @@
"url": "https://opencollective.com/parcel" "url": "https://opencollective.com/parcel"
} }
}, },
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": { "node_modules/listr2": {
"version": "11.4.1", "version": "11.4.1",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz", "resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz",
@@ -5844,6 +5993,12 @@
"@oxc-parser/binding-win32-x64-msvc": "0.158.0" "@oxc-parser/binding-win32-x64-msvc": "0.158.0"
} }
}, },
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": { "node_modules/parse5": {
"version": "8.1.1", "version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
@@ -5922,6 +6077,34 @@
"url": "https://github.com/fb55/entities?sponsor=1" "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": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -5990,6 +6173,14 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==", "integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.33", "version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6165,6 +6356,12 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": { "node_modules/rolldown": {
"version": "1.3.1", "version": "1.3.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz",
@@ -6663,6 +6860,15 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": { "node_modules/saxes": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -6852,6 +7058,12 @@
"node": ">=16.0.0" "node": ">=16.0.0"
} }
}, },
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": { "node_modules/tinybench": {
"version": "6.2.5", "version": "6.2.5",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
@@ -6979,6 +7191,53 @@
"node": ">=22.19.0" "node": ">=22.19.0"
} }
}, },
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/universalify": { "node_modules/universalify": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -7676,6 +7935,18 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1" "url": "https://github.com/chalk/ansi-styles?sponsor=1"
} }
}, },
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": { "node_modules/xml-name-validator": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -7693,6 +7964,18 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/xxhash-wasm": { "node_modules/xxhash-wasm": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz", "resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+4 -1
View File
@@ -29,9 +29,11 @@
"d3-zoom": "3.0.0", "d3-zoom": "3.0.0",
"material-symbols": "0.48.3", "material-symbols": "0.48.3",
"ngx-vflow": "2.7.0", "ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2", "plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
"tslib": "^2.3.0" "tslib": "^2.3.0",
"write-excel-file": "4.1.1"
}, },
"devDependencies": { "devDependencies": {
"@angular/build": "^22.3.0", "@angular/build": "^22.3.0",
@@ -42,6 +44,7 @@
"@types/d3-selection": "3.0.13", "@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9", "@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44", "@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15", "@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0", "jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0", "ng-openapi-gen": "^1.1.0",
+18
View File
@@ -24,6 +24,21 @@ export interface SearchPatient$Params {
'follow-up-cutoff'?: (string | null); 'follow-up-cutoff'?: (string | null);
'follow-up-status'?: (string | null); 'follow-up-status'?: (string | null);
/**
* each word starts a word of her name (case and accents ignored)
*/
name?: (string | null);
/**
* [system|]value: a CURP or record number (case ignored)
*/
identifier?: (string | null);
/**
* gt, ge, lt or le and a day (2000-12-31)
*/
birthdate?: Array<string>;
/** /**
* -recent or -risk-<outcome> * -recent or -risk-<outcome>
*/ */
@@ -56,6 +71,9 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-window', params['follow-up-window'], {}); rb.query('follow-up-window', params['follow-up-window'], {});
rb.query('follow-up-cutoff', params['follow-up-cutoff'], {}); rb.query('follow-up-cutoff', params['follow-up-cutoff'], {});
rb.query('follow-up-status', params['follow-up-status'], {}); rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('birthdate', params.birthdate, {});
rb.query('_sort', params['_sort'], {}); rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {}); rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {}); rb.query('_revinclude', params['_revinclude'], {});
+3 -2
View File
@@ -8,12 +8,13 @@ import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder'; import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain'; import { Domain } from '../../models/domain';
import { Model } from '../../models/model';
export interface Models$Params { export interface Models$Params {
domain: Domain; domain: Domain;
} }
export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<string>>> { export function models(http: HttpClient, rootUrl: string, params: Models$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<Model>>> {
const rb = new RequestBuilder(rootUrl, models.PATH, 'get'); const rb = new RequestBuilder(rootUrl, models.PATH, 'get');
if (params) { if (params) {
rb.path('domain', params.domain, {}); rb.path('domain', params.domain, {});
@@ -24,7 +25,7 @@ export function models(http: HttpClient, rootUrl: string, params: Models$Params,
).pipe( ).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse), filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => { map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<Array<string>>; return r as StrictHttpResponse<Array<Model>>;
}) })
); );
} }
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params { export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params { export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
} }
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{ export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+35
View File
@@ -0,0 +1,35 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
export interface TerminateRun$Params {
run_id: string;
}
export function terminateRun(http: HttpClient, rootUrl: string, params: TerminateRun$Params, context?: HttpContext): Observable<StrictHttpResponse<{
[key: string]: string;
}>> {
const rb = new RequestBuilder(rootUrl, terminateRun.PATH, 'post');
if (params) {
rb.path('run_id', params.run_id, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
[key: string]: string;
}>;
})
);
}
terminateRun.PATH = '/runs/{run_id}/terminate';
+2
View File
@@ -75,6 +75,8 @@ export type { Unrecognised$Params as Unrecognised$Params } from './fn/review/unr
export { unrecognised as unrecognised } from './fn/review/unrecognised'; export { unrecognised as unrecognised } from './fn/review/unrecognised';
export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status'; export type { RunStatus$Params as RunStatus$Params } from './fn/runs/run-status';
export { runStatus as runStatus } from './fn/runs/run-status'; export { runStatus as runStatus } from './fn/runs/run-status';
export type { TerminateRun$Params as TerminateRun$Params } from './fn/runs/terminate-run';
export { terminateRun as terminateRun } from './fn/runs/terminate-run';
export type { Studies$Params as Studies$Params } from './fn/eeg/studies'; export type { Studies$Params as Studies$Params } from './fn/eeg/studies';
export { studies as studies } from './fn/eeg/studies'; export { studies as studies } from './fn/eeg/studies';
export type { Study$Params as Study$Params } from './fn/eeg/study'; export type { Study$Params as Study$Params } from './fn/eeg/study';
+3
View File
@@ -24,6 +24,7 @@ export type { Listing } from './models/listing';
export type { Login } from './models/login'; export type { Login } from './models/login';
export type { Map } from './models/map'; export type { Map } from './models/map';
export type { Metric } from './models/metric'; export type { Metric } from './models/metric';
export type { Model } from './models/model';
export type { Option } from './models/option'; export type { Option } from './models/option';
export type { PersonDecision } from './models/person-decision'; export type { PersonDecision } from './models/person-decision';
export type { Pipeline } from './models/pipeline'; export type { Pipeline } from './models/pipeline';
@@ -31,10 +32,12 @@ export type { Position } from './models/position';
export type { Provider } from './models/provider'; export type { Provider } from './models/provider';
export type { Read } from './models/read'; export type { Read } from './models/read';
export type { Rejection } from './models/rejection'; export type { Rejection } from './models/rejection';
export type { Relation } from './models/relation';
export type { Route } from './models/route'; export type { Route } from './models/route';
export type { RunRequest } from './models/run-request'; export type { RunRequest } from './models/run-request';
export type { SavedPipeline } from './models/saved-pipeline'; export type { SavedPipeline } from './models/saved-pipeline';
export type { SignIn } from './models/sign-in'; export type { SignIn } from './models/sign-in';
export type { Site } from './models/site';
export type { Source } from './models/source'; export type { Source } from './models/source';
export type { SourceRef } from './models/source-ref'; export type { SourceRef } from './models/source-ref';
export type { SourceType } from './models/source-type'; export type { SourceType } from './models/source-type';
+2
View File
@@ -2,10 +2,12 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Metric } from '../models/metric'; import { Metric } from '../models/metric';
import { Relation } from '../models/relation';
export interface Analysis { export interface Analysis {
age_months: (number | null); age_months: (number | null);
id: string; id: string;
level: (string | null); level: (string | null);
metrics: Array<Metric>; metrics: Array<Metric>;
relation?: Array<Relation>;
valid: (boolean | null); valid: (boolean | null);
} }
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable). * field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/ */
export interface Correction { export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string; field: string;
record: string; record: string;
value: string; value: string;
+1 -1
View File
@@ -25,7 +25,7 @@ export interface Extract {
/** /**
* Qué estudio se saca del documento. * Qué estudio se saca del documento.
*/ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: { formats?: {
[key: string]: string; [key: string]: string;
}; };
+1 -1
View File
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir { export interface Fhir {
column?: string; column?: string;
concept_map?: (string | null); concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'fhir'; kind?: 'fhir';
+1 -1
View File
@@ -11,5 +11,5 @@ export interface FieldSpec {
placeholder?: string; placeholder?: string;
provider?: (string | null); provider?: (string | null);
required?: boolean; required?: boolean;
type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format'; type?: 'text' | 'number' | 'password' | 'select' | 'folder' | 'server_file' | 'upload' | 'url' | 'oauth' | 'table' | 'format' | 'columns';
} }
+1 -1
View File
@@ -18,7 +18,7 @@ export interface Join {
label?: string; label?: string;
/** /**
* Pares [columna izquierda, derecha]. * Columna de la primera entrada = columna de la segunda.
*/ */
on: Array<[string, string]>; on: Array<[string, string]>;
position?: (Position | null); position?: (Position | null);
+3
View File
@@ -1,8 +1,10 @@
/* eslint-disable */ /* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
import { Site } from '../models/site';
export interface Metric { export interface Metric {
code: string; code: string;
electrodes?: Array<Site>;
median?: (number | null); median?: (number | null);
model: (string | null); model: (string | null);
outside: (number | null); outside: (number | null);
@@ -10,4 +12,5 @@ export interface Metric {
p95?: (number | null); p95?: (number | null);
value: number; value: number;
z: (number | null); z: (number | null);
zones?: Array<Site>;
} }
+7
View File
@@ -0,0 +1,7 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Model {
name: string;
title: string;
}
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */ /* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection { export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string; reason: string;
record: string; record: string;
} }
+25
View File
@@ -0,0 +1,25 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
/**
* One pair of the champion EEG–ADOS-2 association, for this EEG (models.tea.association).
*/
export interface Relation {
biomarker: string;
ci_high: (number | null);
ci_low: (number | null);
event: string;
kind: string;
metric: string;
model: string;
n: number;
observed?: (number | null);
odds_ratio: number;
outcome_code: string;
probability: number;
q: (number | null);
reference_probability: number;
z: number;
zone: string;
}
+8
View File
@@ -0,0 +1,8 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Site {
site: string;
value: number;
z: (number | null);
}
+1 -1
View File
@@ -12,7 +12,7 @@ export interface Target {
/** /**
* En qué estudio de la plataforma se guarda. * En qué estudio de la plataforma se guarda.
*/ */
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg'; entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string; id: string;
inputs?: Array<string>; inputs?: Array<string>;
kind?: 'target'; kind?: 'target';
+5 -3
View File
@@ -4,7 +4,9 @@
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" /> <img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a> </a>
@if (domain(); as current) { @if (domain(); as current) {
<span class="title">Plataforma de Indicadores</span> <span class="title">{{
section() === 'gobernanza' ? 'Gobernanza de modelos' : 'Plataforma de Indicadores'
}}</span>
<button <button
mat-flat-button mat-flat-button
class="domain" class="domain"
@@ -16,7 +18,7 @@
</button> </button>
<mat-menu #menu="matMenu"> <mat-menu #menu="matMenu">
@for (d of others(); track d) { @for (d of others(); track d) {
<a mat-menu-item [routerLink]="['/indicadores', d]">{{ labels[d] }}</a> <a mat-menu-item [routerLink]="['/' + section(), d]">{{ labels[d] }}</a>
} }
</mat-menu> </mat-menu>
} @else { } @else {
@@ -31,7 +33,7 @@
</nav> </nav>
@if (auth.user(); as u) { @if (auth.user(); as u) {
<button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta"> <button mat-button class="user" [matMenuTriggerFor]="account" aria-label="Cuenta">
<mat-icon>account_circle</mat-icon> {{ u.name || u.email }} <mat-icon>account_circle</mat-icon><span class="who-name">{{ u.name || u.email }}</span>
</button> </button>
<mat-menu #account="matMenu"> <mat-menu #account="matMenu">
<span class="who" mat-menu-item disabled>{{ u.email }}</span> <span class="who" mat-menu-item disabled>{{ u.email }}</span>
+38 -1
View File
@@ -21,10 +21,22 @@
.title { .title {
flex: 1; flex: 1;
min-width: 0; // gives way to the switcher and the sections, on one line
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 1.25rem; font-size: 1.25rem;
font-weight: 500; font-weight: 500;
} }
// Nothing in the header wraps or shrinks: the title gives way first, then hides.
.domain,
.sections a,
.user {
flex-shrink: 0;
white-space: nowrap;
}
.domain { .domain {
--mat-button-filled-container-color: var(--color-primary); --mat-button-filled-container-color: var(--color-primary);
--mat-button-filled-label-text-color: var(--color-text); --mat-button-filled-label-text-color: var(--color-text);
@@ -67,10 +79,35 @@
width: clamp(155px, 15vw, 185px); width: clamp(155px, 15vw, 185px);
} }
@media (max-width: 720px) { @media (max-width: 1100px) {
.title { .title {
display: none; display: none;
} }
.header {
justify-content: space-between;
gap: var(--space-3);
}
.sections {
gap: var(--space-3);
}
// the account by its icon alone; the switcher's name cut short if it must be
.user .who-name {
display: none;
}
.domain {
max-width: 15rem;
}
.domain ::ng-deep .mdc-button__label {
overflow: hidden;
text-overflow: ellipsis;
}
}
@media (max-width: 720px) {
.header {
flex-wrap: wrap;
padding-block: var(--space-2);
}
} }
.user { .user {
+5 -4
View File
@@ -43,10 +43,11 @@ export class App {
), ),
{ initialValue: '' }, { initialValue: '' },
); );
/** The domain of an indicator page, if this is one. */ /** The section and domain of a page that has one (indicators, governance): the switcher
protected readonly domain = computed( * moves between that section's domains. */
() => /^\/indicadores\/(\w+)/.exec(this.url())?.[1] as Domain | undefined, private readonly place = computed(() => /^\/(indicadores|gobernanza)\/(\w+)/.exec(this.url()));
); protected readonly section = computed(() => this.place()?.[1] ?? 'indicadores');
protected readonly domain = computed(() => this.place()?.[2] as Domain | undefined);
protected readonly others = computed(() => protected readonly others = computed(() =>
(this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)), (this.domains.value() ?? []).filter((d) => d !== this.domain() && this.auth.canSee(d)),
); );
+62 -35
View File
@@ -73,10 +73,6 @@
</button> </button>
</div> </div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p> <p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) { @if (d.inputs?.length) {
<div class="inputs"> <div class="inputs">
Entradas: Entradas:
@@ -87,40 +83,71 @@
} }
</div> </div>
} @else if (d.kind !== 'source') { } @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p> <p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
} }
@if (guided(d); as g) { <mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
<div class="source-summary"> <mat-tab label="Configuración">
<p> @if (d.kind === 'source') {
<mat-icon>check_circle</mat-icon> @if (guided(d)) {
{{ d.label || d.id }} <div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
} @else {
<p class="muted">
Esta fuente no corresponde a ningún tipo del asistente. Edítela en «Avanzado» o
vuelva a conectarla con el asistente.
</p>
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con el asistente
</button>
}
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
[options]="formOptions"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
</mat-tab>
<mat-tab label="Avanzado">
<p class="hint">
Para personal técnico: el nodo completo como lo guarda la plataforma.
@if (guided(d)) {
Si cambia su fuente aquí, deja de editarse con el asistente.
}
</p> </p>
<button mat-flat-button (click)="connectSource(d.id)"> <mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-icon>edit</mat-icon> Editar conexión <mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
<mat-hint>Nombre interno: minúsculas, números y _.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full raw">
<mat-label>Nodo (JSON)</mat-label>
<textarea
matInput
rows="16"
[value]="raw(d)"
(input)="rawDraft.set($any($event.target).value)"
></textarea>
</mat-form-field>
@if (rawError()) {
<p class="error" role="alert">{{ rawError() }}</p>
}
<button mat-stroked-button [disabled]="rawDraft() === undefined" (click)="applyRaw()">
Aplicar
</button> </button>
</div> </mat-tab>
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)"> </mat-tab-group>
Avanzado (para personal técnico)
</mat-slide-toggle>
} @else if (d.kind === 'source') {
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con ayuda
</button>
}
@if (!guided(d) || advanced()) {
@if (guided(d)) {
<p class="muted">Si cambia algo aquí, la fuente deja de editarse con ayuda.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
}
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
<button mat-stroked-button (click)="show()">Vista previa</button> <button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) { @if (preview(); as rows) {
<div class="preview"> <div class="preview">
+52
View File
@@ -140,3 +140,55 @@ h2 {
color: var(--color-success, #2e7d32); color: var(--color-success, #2e7d32);
} }
} }
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node {
box-sizing: border-box;
overflow: hidden;
padding: 4px 10px;
display: flex;
align-items: center;
}
:host ::ng-deep .node-caption {
min-width: 0;
width: 100%;
line-height: 1.2;
}
:host ::ng-deep .node-caption .kind {
display: block;
font-size: 10px;
color: var(--color-text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
:host ::ng-deep .node-caption .name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: 12px;
font-weight: 500;
overflow-wrap: anywhere;
}
.panel-tabs {
margin-top: var(--space-2);
}
.panel-tabs .hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: var(--space-3) 0;
}
.raw textarea {
font-family: monospace;
font-size: 12px;
}
.error {
color: var(--mat-sys-error);
font-size: 13px;
}
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3);
}
+86 -15
View File
@@ -1,5 +1,13 @@
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core'; import {
Component,
computed,
effect,
inject,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
@@ -7,7 +15,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list'; import { MatListModule } from '@angular/material/list';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatTabsModule } from '@angular/material/tabs';
import { MatTableModule } from '@angular/material/table'; import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core'; import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
@@ -57,21 +65,21 @@ export const KINDS: Record<Kind, string> = {
read: 'Leer documentos', read: 'Leer documentos',
route: 'Separar por tipo', route: 'Separar por tipo',
map: 'Traducir códigos', map: 'Traducir códigos',
extract: 'Sacar datos', extract: 'Extraer datos',
fhir: 'Leer FHIR', fhir: 'Leer FHIR',
join: 'Juntar', join: 'Unir',
link: 'Identificar a la persona', link: 'Identificar a la persona',
target: 'Guardar en la plataforma', target: 'Guardar en la plataforma',
}; };
export const HELP: Record<Kind, string> = { export const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.', source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Saca el texto de cada documento (PDF, Word, escaneos con OCR).', read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route: route:
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.', 'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.', map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Toma de cada documento los datos de un estudio: fechas, resultados, nombres.', extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee paquetes FHIR que un sistema envió y saca de ellos los estudios.', fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
join: 'Junta dos entradas que hablan de lo mismo; por ejemplo, un resultado con su orden.', join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.', link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.', target: 'Guarda los estudios ya revisados en la plataforma.',
}; };
@@ -90,7 +98,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule, MatIconModule,
MatInputModule, MatInputModule,
MatListModule, MatListModule,
MatSlideToggleModule, MatTabsModule,
MatTableModule, MatTableModule,
MatTooltipModule, MatTooltipModule,
Vflow, Vflow,
@@ -107,8 +115,9 @@ export class Conectar {
private readonly dialog = inject(MatDialog); private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][]; protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP; protected readonly help = HELP;
/** The raw form of a source drawn with the dialog ("Avanzado"). */ /** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly advanced = signal(false); protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) }); protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) }); private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -132,6 +141,20 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
}); });
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({}); protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {}; protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */ /** The selected node's form, generated from its kind's JSON Schema. */
@@ -264,7 +287,8 @@ export class Conectar {
); );
this.form = new UntypedFormGroup({}); this.form = new UntypedFormGroup({});
this.preview.set(undefined); this.preview.set(undefined);
this.advanced.set(false); this.rawDraft.set(undefined);
this.rawError.set('');
} }
/** A source the dialog drew (its answers make its dlt fields). */ /** A source the dialog drew (its answers make its dlt fields). */
@@ -279,13 +303,46 @@ export class Conectar {
const values = Object.fromEntries( const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null), Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
); );
if (this.advanced()) delete values['guided']; // drawn by hand from here on
this.update( this.update(
id, id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc, (d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
); );
} }
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2);
}
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void {
const d = this.doc();
const text = this.rawDraft();
if (!d || text === undefined) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(text);
} catch {
this.rawError.set('El texto no es JSON válido.');
return;
}
if (parsed['kind'] !== d.kind) {
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
return;
}
if (d.kind === 'source') {
const dlt = ['source', 'args', 'resource', 'then'] as const;
const before = d as unknown as Record<string, unknown>;
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
delete parsed['guided'];
}
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
this.select(d.id);
}
protected rename(to: string): void { protected rename(to: string): void {
const from = this.selected(); const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return; if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
@@ -363,7 +420,7 @@ export class Conectar {
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source }) ? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 }); : await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows); this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.'); this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
} catch (e) { } catch (e) {
this.message.set(problem(e)); this.message.set(problem(e));
} }
@@ -389,7 +446,14 @@ export class Conectar {
} }
function text(d: Doc): string { function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`; // ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
`<div class="node-caption" title="${kind} · ${name}">` +
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
);
} }
/** Each node's distance from the sources: its column when it has no saved position. */ /** Each node's distance from the sources: its column when it has no saved position. */
@@ -416,3 +480,10 @@ function problem(e: unknown): string {
} }
return String(e); return String(e);
} }
function escape(text: string): string {
return text.replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!,
);
}
+15 -3
View File
@@ -16,6 +16,12 @@ const PIPELINE = {
when: { type: 'array', items: { $ref: '#/$defs/Condition' } }, when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' }, resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' }, values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
on: {
type: 'array',
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
},
extra: { type: 'object', title: 'Extra' },
source: { type: 'string', advanced: true },
}, },
}, },
}, },
@@ -25,7 +31,7 @@ describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any; const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => { it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']); expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
expect(schema.required).toEqual(['when']); expect(schema.required).toEqual(['when']);
}); });
@@ -34,7 +40,13 @@ describe('node forms from the pipeline schema', () => {
expect(schema.properties.resource.type).toBe('string'); expect(schema.properties.resource.type).toBe('string');
}); });
it('edits maps as JSON', () => { it('edits maps of texts and pairs as rows', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json'); expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
});
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
expect(schema.properties.extra).toBeUndefined();
expect(schema.properties.source).toBeUndefined();
}); });
}); });
+236 -2
View File
@@ -3,6 +3,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { import {
ConfigOption, ConfigOption,
@@ -27,11 +28,29 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!; )!;
const node = structuredClone(defs[name]); const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field]; for (const field of CANVAS_FIELDS) delete node.properties?.[field];
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f)); // The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
delete node.properties![field];
}
node.required = (node.required ?? []).filter(
(f) => !CANVAS_FIELDS.includes(f) && f in (node.properties ?? {}),
);
delete node.additionalProperties; delete node.additionalProperties;
return simplify(node, defs); return simplify(node, defs);
} }
function isJson(schema: Schema): boolean {
return (
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
'json'
);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema { function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) { if (schema.$ref) {
const { $ref, ...rest } = schema; const { $ref, ...rest } = schema;
@@ -45,6 +64,34 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return simplify({ ...kept[0], ...rest }, defs); return simplify({ ...kept[0], ...rest }, defs);
} }
} }
const values = schema.additionalProperties as Schema | boolean | undefined;
if (
schema.type === 'object' &&
!schema.properties &&
typeof values === 'object' &&
values.type === 'string'
) {
const byField = (schema as { keys?: string }).keys === 'field';
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
} as Schema;
}
const pair = schema.items as Schema | undefined;
if (
schema.type === 'array' &&
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'pairs' } },
} as Schema;
}
const isMap = schema.type === 'object' && !schema.properties; const isMap = schema.type === 'object' && !schema.properties;
const isTuple = const isTuple =
schema.type === 'array' && schema.type === 'array' &&
@@ -117,7 +164,7 @@ export class ArrayType extends FieldArrayType {}
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule], imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: ` template: `
<mat-form-field appearance="outline" class="json"> <mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }} (JSON)</mat-label> <mat-label>{{ props.label }}</mat-label>
<textarea <textarea
matInput matInput
rows="4" rows="4"
@@ -152,11 +199,198 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
} }
} }
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
@if (props['fieldKeys']) {
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
@for (o of keyOptions(row[0]); track o[0]) {
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[value]="row[0]"
(change)="edit(i, $any($event.target).value, row[1])"
/>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
<mat-label>Valor</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
column-gap: 4px;
row-gap: 6px;
padding: 8px 0;
border-bottom: 1px solid var(--color-border);
}
.key,
.value {
min-width: 0;
grid-column: 1;
}
.row button {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
string | undefined;
const titles: Record<string, string> = entity
? (all[entity] ?? {})
: Object.assign({}, ...Object.values(all));
const options = Object.entries(titles);
if (current && !(current in titles)) options.unshift([current, current]);
return options;
}
protected rows(): [string, string][] {
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
this.formControl.markAsDirty();
}
protected edit(i: number, key: string, value: string): void {
const rows = this.rows();
rows[i] = [key.trim(), value];
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
: undefined;
let n = rows.length + 1;
while (used.has(`campo_${n}`)) n++;
this.save([...rows, [free ?? `campo_${n}`, '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Primera entrada</mat-label>
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
</mat-form-field>
<span>=</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Segunda entrada</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 6px;
}
.half {
flex: 1;
min-width: 0;
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(rows);
this.formControl.markAsDirty();
}
protected edit(i: number, side: 0 | 1, value: string): void {
const rows = this.rows();
rows[i][side] = value.trim();
this.save(rows);
}
protected add(): void {
this.save([...this.rows(), ['', '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
export const FORMLY_TYPES: ConfigOption = { export const FORMLY_TYPES: ConfigOption = {
types: [ types: [
{ name: 'object', component: ObjectType }, { name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType }, { name: 'array', component: ArrayType },
{ name: 'json', component: JsonType }, { name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ name: 'enum', extends: 'select' }, { name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' }, { name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } }, { name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
+20 -1
View File
@@ -128,6 +128,25 @@
} }
</mat-form-field> </mat-form-field>
} }
@case ('columns') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
multiple
[ngModel]="listed(name)"
(ngModelChange)="set(name, $event.length ? $event : null)"
[attr.data-field]="name"
placeholder="Todas"
>
@for (c of columnOptions(name); track c) {
<mat-option [value]="c">{{ c }}</mat-option>
}
</mat-select>
<mat-hint>{{
columnOptions(name).length ? f.help : 'Pulse «Probar conexión» para ver las columnas.'
}}</mat-hint>
</mat-form-field>
}
@case ('folder') { @case ('folder') {
<div class="picker"> <div class="picker">
<mat-form-field appearance="outline" class="grow"> <mat-form-field appearance="outline" class="grow">
@@ -319,7 +338,7 @@
</p> </p>
@if (t.detail) { @if (t.detail) {
<details> <details>
<summary>Lo que respondió el sistema</summary> <summary>Respuesta de la fuente</summary>
<pre>{{ t.detail }}</pre> <pre>{{ t.detail }}</pre>
</details> </details>
} }
+12
View File
@@ -33,6 +33,8 @@ export interface SourceDialogData {
guided?: Guided | null; guided?: Guided | null;
label?: string; label?: string;
} }
const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */ /** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult { export interface SourceDialogResult {
guided: Guided; guided: Guided;
@@ -203,6 +205,16 @@ export class SourceDialog {
} }
} }
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
/** The tables a database listed, for its table field. */ /** The tables a database listed, for its table field. */
protected tables(): string[] { protected tables(): string[] {
return this.tableList(); return this.tableList();
+144
View File
@@ -0,0 +1,144 @@
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)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
/** The zones the metrics are summed over (models.tea.eeg.spindles.ZONES). */
export const ZONE_NAMES: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal media',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
/** 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',
posterior_rhythm: 'Ritmo posterior',
gradient: 'Gradiente anteroposterior',
};
/** ADOS-2 items by their number (core.tea.association.ITEMS), and the CSS. */
export const OUTCOME_NAMES: Record<string, string> = {
ados2_item_01: 'Vocalización espontánea dirigida a otros',
ados2_item_02: 'Señalar',
ados2_item_03: 'Gestos',
ados2_item_04: 'Contacto visual inusual',
ados2_item_05: 'Expresiones faciales dirigidas a otros',
ados2_item_06: 'Integración de la mirada con otras conductas',
ados2_item_07: 'Disfrute compartido en la interacción',
ados2_item_08: 'Respuesta al nombre',
ados2_item_09: 'Búsqueda de atención cuando se le ignora',
ados2_item_10: 'Pedir',
ados2_item_11: 'Mostrar',
ados2_item_12: 'Iniciación espontánea de la atención conjunta',
ados2_item_13: 'Respuesta a la atención conjunta',
ados2_item_14: 'Calidad de los acercamientos sociales',
ados2_item_15: 'Cantidad de acercamientos sociales al cuidador',
ados2_item_16: 'Cantidad de comunicación social recíproca',
ados2_item_17: 'Calidad general de la relación',
ados2_item_18: 'Entonación de vocalizaciones o verbalizaciones',
ados2_item_19: 'Uso estereotipado o idiosincrático de palabras',
ados2_item_20: 'Interés sensorial inusual',
ados2_item_21: 'Manierismos de manos y dedos',
ados2_item_22: 'Intereses repetitivos o conductas estereotipadas',
CSS: 'Puntuación de severidad (CSS)',
};
/** Where each electrode of the 10-20 system sits on a head seen from above (nose up). */
const AT: Record<string, [number, number]> = {
Fp1: [-0.31, 0.95], Fp2: [0.31, 0.95],
F7: [-0.81, 0.59], F3: [-0.4, 0.53], Fz: [0, 0.5], F4: [0.4, 0.53], F8: [0.81, 0.59],
T3: [-1, 0], C3: [-0.5, 0], Cz: [0, 0], C4: [0.5, 0], T4: [1, 0],
T5: [-0.81, -0.59], P3: [-0.4, -0.53], Pz: [0, -0.5], P4: [0.4, -0.53], T6: [0.81, -0.59],
O1: [-0.31, -0.95], O2: [0.31, -0.95],
}; // prettier-ignore
export interface Site {
site: string;
value: number;
z?: number | null;
}
/** Her electrodes on the head, coloured by how far each is from its age curve (z, blue
* below and red above), or by her own value where no curve scores electrodes. */
export function headMap(electrodes: Site[]): Figure {
const placed = electrodes.filter((e) => AT[e.site]);
const scored = placed.some((e) => e.z !== null && e.z !== undefined);
const colour = placed.map((e) => (scored ? (e.z ?? 0) : e.value));
const ring = Array.from({ length: 73 }, (_, i) => (i * 2 * Math.PI) / 72);
return {
data: [
{
x: ring.map((t) => 1.12 * Math.sin(t)),
y: ring.map((t) => 1.12 * Math.cos(t)),
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: [-0.12, 0, 0.12],
y: [1.1, 1.24, 1.1],
mode: 'lines',
line: { color: '#9aa0a6', width: 1 },
hoverinfo: 'skip',
showlegend: false,
},
{
x: placed.map((e) => AT[e.site][0]),
y: placed.map((e) => AT[e.site][1]),
text: placed.map((e) => e.site),
customdata: colour,
mode: 'markers+text',
textposition: 'top center',
marker: {
size: 22,
color: colour,
colorscale: 'RdBu',
reversescale: true,
...(scored ? { cmin: -3, cmax: 3, cmid: 0 } : {}),
colorbar: { title: { text: scored ? 'z' : 'valor' }, thickness: 10 },
line: { color: '#ffffff', width: 1 },
},
hovertemplate: scored ? '%{text}: z = %{customdata:.2f}<extra></extra>'
: '%{text}: %{customdata:.3f}<extra></extra>', // prettier-ignore
showlegend: false,
},
],
layout: {
xaxis: { visible: false, range: [-1.35, 1.35], scaleanchor: 'y' },
yaxis: { visible: false, range: [-1.25, 1.35] },
margin: { l: 10, r: 10, t: 10, b: 10 },
},
} as Figure;
}
/** The zones, most affected first: by how far from the age curve, else by value. */
export function byDeviation(zones: Site[]): Site[] {
const scored = zones.some((z) => z.z !== null && z.z !== undefined);
return [...zones].sort((a, b) =>
scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value,
);
}
/** An EEG's quality level (models.tea.eeg.checks): how much of it the analysis could use. */
export const LEVEL_NAMES: Record<string, string> = {
complete: 'registro completo',
partial: 'registro parcial: menos de la mitad limpio',
no_ear_reference: 'sin referencia auricular',
not_analyzable: 'no analizable',
};
+69
View File
@@ -0,0 +1,69 @@
import type { Content, TDocumentDefinitions } from 'pdfmake/interfaces';
/** A table to save, as the page shows it: its headers and rows, and what it was asked with. */
export interface Sheet {
title: string;
query?: [string, string][];
head: string[];
rows: string[][];
}
/** Every cell is text: nothing in it runs as a formula. */
export async function saveExcel(sheet: Sheet, file: string): Promise<void> {
const { default: write } = await import('write-excel-file/browser');
const text = (value: string) => ({ value, type: String });
const head = sheet.head.map((value) => ({ ...text(value), fontWeight: 'bold' as const }));
await write([
{ sheet: 'Resultados', data: [head, ...sheet.rows.map((r) => r.map(text))] },
{ sheet: 'Consulta', data: (sheet.query ?? []).map((q) => q.map(text)) },
]).toFile(`${file}.xlsx`);
}
/** The tables on the institutional page: logo, date and page numbers. */
export async function savePdf(sheets: Sheet[], file: string, wide = false): Promise<void> {
const [pdfmake, fonts, logo] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
fetch('assets/branding/isssteleon-logo.png').then((r) => r.blob()),
]);
const image = await new Promise<string>((done, fail) => {
const reader = new FileReader();
reader.onload = () => done(reader.result as string);
reader.onerror = () => fail(reader.error);
reader.readAsDataURL(logo);
});
const made = new Date().toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
const definition: TDocumentDefinitions = {
pageSize: 'LETTER',
pageOrientation: wide ? 'landscape' : 'portrait',
pageMargins: [36, 60, 36, 40],
defaultStyle: { fontSize: 7.5 },
header: { image, width: 110, margin: [36, 18, 0, 0] },
footer: (page, pages) => ({
columns: [
`Generado: ${made}`,
{ text: 'Confidencial, uso interno', alignment: 'center' },
{ text: `Página ${page} de ${pages}`, alignment: 'right' },
],
margin: [36, 12],
fontSize: 7,
}),
content: sheets.flatMap((s): Content[] => [
{ text: s.title, fontSize: 13, bold: true, margin: [0, 10, 0, 4] },
...(s.query ?? []).map(([k, v]) => ({ text: [{ text: `${k}: `, bold: true }, v] })),
s.rows.length
? {
layout: 'lightHorizontalLines',
margin: [0, 6, 0, 0],
table: {
headerRows: 1,
dontBreakRows: true,
body: [s.head.map((text) => ({ text, bold: true })), ...s.rows],
},
}
: 'Sin registros.',
]),
};
pdfmake.default.addVirtualFileSystem(fonts.default);
await pdfmake.default.createPdf(definition).download(`${file}.pdf`);
}
+9 -9
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures } from './figures'; import { interpretabilityFigures, scenarioFigure } from './figures';
describe('governance figures', () => { describe('governance figures', () => {
it('draws a survival report as curves with bands and the model points', () => { it('draws a survival report as curves with bands and the model points', () => {
@@ -13,7 +13,7 @@ describe('governance figures', () => {
expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05); expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05);
}); });
it("draws each survival scenario after the cohort's curves, titled with its deaths", () => { it('leaves the survival scenarios to the patient record, which draws them whole', () => {
const scenario = { const scenario = {
escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)', escenario: 'HER2+ · ≥60 años · estadio III–IV (Alto)',
n: 1142, n: 1142,
@@ -30,14 +30,14 @@ describe('governance figures', () => {
predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] }, predicted: { name: 'Modelo', months: [6], survival: [0.9], low: [0.8], high: [0.95] },
escenarios: [scenario], escenarios: [scenario],
}); });
expect(found.length).toBe(2); expect(found.length).toBe(1); // the cohort's curves only
expect(found[1].title).toContain('fallecidos = 308'); const drawn = scenarioFigure(scenario.escenario, scenario, scenario.horizons_months, 'S(t)');
expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points expect(drawn.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points
expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]); expect((drawn.figure.data[4] as any).x).toEqual([6, 12, 18]);
}); });
it('draws a recurrence scenario: KM band, both Weibulls and the model points', () => { it('leaves recurrence scenarios to the patient record', () => {
const [found] = interpretabilityFigures({ const found = interpretabilityFigures({
kind: 'scenarios', kind: 'scenarios',
recurrencia: { recurrencia: {
horizons_months: [12, 36], horizons_months: [12, 36],
@@ -55,7 +55,7 @@ describe('governance figures', () => {
], ],
}, },
}); });
expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points expect(found).toEqual([]);
}); });
it('draws an age curve with its centile band', () => { it('draws an age curve with its centile band', () => {
+64 -22
View File
@@ -1,5 +1,6 @@
import type { Figure } from '../plot'; import type { Figure } from '../plot';
import { PALETTE } 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. */
interface Band { interface Band {
@@ -70,15 +71,7 @@ export function interpretabilityFigures(
}, },
}, },
}, },
// Its clinical scenarios, those with enough deaths to draw. // Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
...((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)',
),
),
]; ];
} }
case 'subgroups': case 'subgroups':
@@ -147,17 +140,8 @@ export function interpretabilityFigures(
}, },
]; ];
} }
case 'scenarios': case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return (report['recurrencia']['escenarios'] as any[]) return [];
.slice(0, 6)
.map((e) =>
scenarioFigure(
`${e.cohorte_nombre} · ${e.escenario} (n = ${e.n}, ${e.recaidas} recaídas)`,
e,
report['recurrencia']['horizons_months'],
'Supervivencia libre de recaída',
),
);
case 'age_curves': { case 'age_curves': {
// The metric's own curve; a topography has only electrodes: its first one. // The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0]; const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
@@ -205,6 +189,62 @@ export function interpretabilityFigures(
}, },
]; ];
} }
case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
const label = (r: any) =>
`${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${
OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code
}`;
return [
{
title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${
report['level'] === 'item' ? 'reactivo' : 'dominio'
})`,
figure: {
data: [
{
type: 'scatter',
mode: 'markers',
x: rows.map((r) => r.odds_ratio),
y: rows.map(label),
error_x: {
type: 'data',
symmetric: false,
array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio),
arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)),
},
marker: {
color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')),
size: 9,
},
customdata: rows.map((r) => r.q),
hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}<extra>%{y}</extra>',
showlegend: false,
},
],
layout: {
xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' },
yaxis: { automargin: true, autorange: 'reversed' },
shapes: [
{
type: 'line',
x0: 1,
x1: 1,
yref: 'paper',
y0: 0,
y1: 1,
line: { color: '#9aa0a6', dash: 'dot' },
},
],
height: Math.max(320, 22 * rows.length + 80),
},
},
},
];
}
default: default:
return []; return [];
} }
@@ -246,8 +286,10 @@ export function scenarioFigure(
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB), points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
], ],
layout: { layout: {
xaxis: { title: { text: 'Meses desde el diagnóstico' } }, // One label per month with every curve's survival there, as percentages.
yaxis: { title: { text: yTitle } }, hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
}, },
}, },
}; };
+67 -33
View File
@@ -1,10 +1,6 @@
<section class="page"> <section class="page">
<h1>Gobernanza de modelos</h1> <h1>{{ labels[domain()] ?? domain() }}</h1>
<nav class="domains" aria-label="Dominios"> <p class="muted subtitle">Versiones, informes, promoción y ejecuciones de sus modelos.</p>
@for (d of domains.value() ?? []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
}
</nav>
<form class="card actions" (submit)="$event.preventDefault()"> <form class="card actions" (submit)="$event.preventDefault()">
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -17,13 +13,44 @@
name="asOf" name="asOf"
/> />
</mat-form-field> </mat-form-field>
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button> @if (confirming(); as c) {
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button> <span class="confirm" role="alert">
@if (domain() === 'tea') { {{
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button> c === 'train'
? '¿Entrenar todos los modelos de este dominio ahora?'
: '¿Calcular los riesgos de todas las pacientes con los modelos en producción?'
}}
<button mat-flat-button type="button" (click)="start(c)">Sí, iniciar</button>
<button mat-button type="button" (click)="confirming.set(undefined)">Cancelar</button>
</span>
} @else {
<button
mat-flat-button
type="button"
[disabled]="running()"
(click)="confirming.set('train')"
>
Entrenar
</button>
<button
mat-stroked-button
type="button"
[disabled]="running()"
(click)="confirming.set('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button mat-stroked-button type="button" [disabled]="running()" (click)="analyzeEegs()">
Analizar EEG
</button>
}
} }
@if (run(); as r) { @if (run(); as r) {
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span> <span class="muted" role="status">{{ r.kind }}: {{ STATUS[r.status] ?? r.status }}</span>
@if (running()) {
<button mat-button type="button" class="stop" (click)="stop()">Detener</button>
}
} }
</form> </form>
@if (message()) { @if (message()) {
@@ -33,17 +60,19 @@
@if (models.isLoading()) { @if (models.isLoading()) {
<app-loading what="los modelos" /> <app-loading what="los modelos" />
} @else if (!models.value()?.length) { } @else if (!models.value()?.length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p> <p class="muted empty">Sin modelos entrenados en este dominio.</p>
} }
@for (m of models.value() ?? []; track m.name) { @for (m of models.value() ?? []; track m.name) {
<div class="card model"> <div class="card model">
<h2>{{ m.name }}</h2> <h2>
{{ m.title }} <code class="muted code">{{ m.name }}</code>
</h2>
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
<th>Versión</th> <th>Versión</th>
<th>Creada</th> <th>Creada</th>
<th>Entrenamiento / prueba</th> <th>Datos</th>
<th>Informes</th> <th>Informes</th>
<th>Validación clínica</th> <th>Validación clínica</th>
<th></th> <th></th>
@@ -59,32 +88,37 @@
} }
</td> </td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td> <td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num"> <td class="nowrap">{{ sizes(v) }}</td>
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td>
<td> <td>
@for (r of v.reports; track r) { <div class="reports">
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{ @for (r of v.reports; track r) {
reportNames[r] ?? r <a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
}}</a> reportNames[r] ?? r
} }}</a>
@if (v.reports.includes('interpretability')) { }
<button @if (v.reports.includes('interpretability')) {
mat-button <button
type="button" mat-button
(click)="chosen.set({ name: m.name, version: v.version })" type="button"
> (click)="chosen.set({ name: m.name, version: v.version })"
Ver gráficas >
</button> Ver gráficas
} </button>
}
</div>
</td> </td>
<td> <td>
@if (!v.reports.includes('clinical_validation')) { @if (!v.reports.includes('clinical_validation')) {
<input <input
#file
type="file" type="file"
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version" hidden
[attr.aria-label]="'Validación clínica de ' + m.title + ' v' + v.version"
(change)="upload(m.name, v.version, $event)" (change)="upload(m.name, v.version, $event)"
/> />
<button mat-stroked-button type="button" (click)="file.click()">
Subir validación clínica
</button>
} @else { } @else {
Agregada Agregada
} }
@@ -105,7 +139,7 @@
@if (chosen(); as c) { @if (chosen(); as c) {
<div class="card"> <div class="card">
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2> <h2>Interpretabilidad · {{ titleOf(c.name) }} v{{ c.version }}</h2>
@for (f of figures(); track f.title) { @for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3> <h3>{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="360" /> <app-plot [figure]="f.figure" [height]="360" />
+32 -12
View File
@@ -1,18 +1,8 @@
:host { :host {
display: block; display: block;
} }
h1 { .subtitle {
text-align: center; margin: 4px 0 var(--space-4);
}
.domains {
display: flex;
justify-content: center;
gap: var(--space-4);
margin-bottom: var(--space-4);
}
.domains a.active {
font-weight: 600;
text-decoration: underline;
} }
.actions { .actions {
display: flex; display: flex;
@@ -30,6 +20,7 @@ h1 {
white-space: nowrap; white-space: nowrap;
} }
.badge { .badge {
white-space: nowrap;
margin-left: var(--space-2); margin-left: var(--space-2);
padding: 2px 8px; padding: 2px 8px;
border-radius: 999px; border-radius: 999px;
@@ -45,3 +36,32 @@ td a {
padding: 48px 0; padding: 48px 0;
text-align: center; text-align: center;
} }
.reports {
display: flex;
flex-wrap: wrap;
align-items: center;
column-gap: var(--space-3);
row-gap: 2px;
}
.reports a {
margin-right: 0;
}
h2 .code {
font-size: 12px;
font-weight: 400;
margin-left: var(--space-2);
}
.confirm {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: 4px 4px 4px 12px;
border-radius: 8px;
background: var(--color-surface-warning, #fdf3dc);
}
td button {
white-space: nowrap;
}
+62 -18
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { DatePipe, DecimalPipe } from '@angular/common'; import { DatePipe, DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
@@ -5,7 +6,6 @@ import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api'; import { Api } from '../api/api';
import { ApiConfiguration } from '../api/api-configuration'; import { ApiConfiguration } from '../api/api-configuration';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
@@ -16,9 +16,9 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import { score } from '../api/fn/models/score'; import { score } from '../api/fn/models/score';
import { train } from '../api/fn/models/train'; import { train } from '../api/fn/models/train';
import { versions } from '../api/fn/models/versions'; import { versions } from '../api/fn/models/versions';
import { domains } from '../api/fn/operations/domains';
import { studies } from '../api/fn/eeg/studies'; import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study'; import { study } from '../api/fn/eeg/study';
import { terminateRun } from '../api/fn/runs/terminate-run';
import { runStatus } from '../api/fn/runs/run-status'; import { runStatus } from '../api/fn/runs/run-status';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import type { Version } from '../api/models/version'; import type { Version } from '../api/models/version';
@@ -46,7 +46,6 @@ const REPORTS: Record<string, string> = {
MatButtonModule, MatButtonModule,
MatFormFieldModule, MatFormFieldModule,
MatInputModule, MatInputModule,
RouterLink,
Plot, Plot,
], ],
templateUrl: './gobernanza.html', templateUrl: './gobernanza.html',
@@ -59,15 +58,15 @@ export class Gobernanza {
protected readonly labels = DOMAINS as Record<string, string>; protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS; protected readonly reportNames = REPORTS;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
private readonly refreshed = signal(0); private readonly refreshed = signal(0);
protected readonly models = resource({ protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }), params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
loader: async ({ params: { domain } }) => { loader: async ({ params: { domain } }) => {
const names = await this.api.invoke(models, { domain }); const found = await this.api.invoke(models, { domain });
return Promise.all( return Promise.all(
names.map(async (name) => ({ found.map(async ({ name, title }) => ({
name, name,
title,
versions: await this.api.invoke(versions, { domain, name }), versions: await this.api.invoke(versions, { domain, name }),
})), })),
); );
@@ -93,15 +92,43 @@ export class Gobernanza {
params: () => this.eeg(), params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }), loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
}); });
protected readonly metricNames: Record<string, string> = { protected readonly metricNames = METRIC_NAMES;
posterior_rhythm: 'Ritmo posterior (Hz)',
spindles_n2: 'Husos de sueño N2 (por min)',
spindles_n3: 'Husos de sueño N3 (por min)',
paroxysmal_spikes: 'Picos paroxísticos (por min)',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
protected readonly asOf = signal(''); protected readonly asOf = signal('');
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined); protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>(
undefined,
);
/** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */
protected readonly confirming = signal<'train' | 'score' | undefined>(undefined);
protected readonly running = computed(() => {
const r = this.run();
return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status);
});
protected readonly STATUS: Record<string, string> = {
QUEUED: 'en cola',
NOT_STARTED: 'por iniciar',
STARTING: 'iniciando',
STARTED: 'en curso',
SUCCESS: 'terminado',
FAILURE: 'con error',
CANCELING: 'deteniéndose',
CANCELED: 'detenido',
};
/** A model's title by its name, for messages. */
protected titleOf(name: string): string {
return this.models.value()?.find((m) => m.name === name)?.title ?? name;
}
/** What a version learned from, as its metrics say it (each kind of model its own). */
protected sizes(v: Version): string {
const m = v.metrics;
const n = (x: number) => x.toLocaleString('es-MX');
if (m['n_train'] !== undefined)
return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`;
if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`;
if (m['children'] !== undefined) return `${n(m['children'])} niños`;
const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox'));
if (c) return `C-index ${c[1].toFixed(3)}`;
return '—';
}
protected readonly message = signal(''); protected readonly message = signal('');
protected champion(v: Version): boolean { protected champion(v: Version): boolean {
@@ -122,18 +149,27 @@ export class Gobernanza {
// OpenAPI's binary is typed as a string; the request builder sends the File as is. // OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string }, body: { file: file as unknown as string },
}); });
this.message.set(`Validación clínica agregada a ${name} v${version}.`); this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`);
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} }
protected async promote(name: string, version: number): Promise<void> { protected async promote(name: string, version: number): Promise<void> {
try { try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
this.message.set(`${name} v${version} es ahora la versión en producción.`); this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`);
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} catch (e) { } catch (e) {
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
this.message.set(`No se promovió: ${detail ?? 'error'}`); // "<model> v1 has no clinical_validation, interpretability": the reports it lacks
const missing = /has no (.+)$/.exec(String(detail ?? ''))?.[1];
this.message.set(
missing
? `No se promovió: faltan informes (${missing
.split(', ')
.map((r) => this.reportNames[r] ?? r)
.join(', ')}).`
: `No se promovió: ${detail ?? 'error de la plataforma'}`,
);
} }
} }
@@ -145,14 +181,22 @@ export class Gobernanza {
private async follow(run_id: string, label: string): Promise<void> { private async follow(run_id: string, label: string): Promise<void> {
for (;;) { for (;;) {
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
this.run.set({ kind: label, status }); this.run.set({ id: run_id, kind: label, status });
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
await new Promise((r) => setTimeout(r, 2000)); await new Promise((r) => setTimeout(r, 2000));
} }
this.refreshed.update((n) => n + 1); this.refreshed.update((n) => n + 1);
} }
protected async stop(): Promise<void> {
const r = this.run();
if (!r) return;
const found = await this.api.invoke(terminateRun, { run_id: r.id });
this.run.set({ ...r, status: found['status'] });
}
protected async start(kind: 'train' | 'score'): Promise<void> { protected async start(kind: 'train' | 'score'): Promise<void> {
this.confirming.set(undefined);
const domain = this.domain() as Domain; const domain = this.domain() as Domain;
const { run_id } = const { run_id } =
kind === 'train' kind === 'train'
+27
View File
@@ -0,0 +1,27 @@
import { bars } from './bars';
import { Reading } from './measures';
describe('bars', () => {
it('list every category, so the shares add up', () => {
const r: Reading = {
populations: {},
strata: {
category: { a: { 'initial-population': 3 }, other: { 'initial-population': 1 } },
},
};
const catalog = [{ code: 'a', label: 'A', color: '#000' }];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '75.0 %'],
['1', '25.0 %'],
]);
});
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: {},
strata: { s: { initial: { numerator: 0, denominator: 0 } } },
};
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
});
+146
View File
@@ -0,0 +1,146 @@
import { CIE10 } from './cie10';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */
export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = { label: string; caption?: string } & (
| { kind: 'counts'; measure: string; catalog: Category[] }
| { kind: 'shares'; measure: string; stratum: string; order: string[] }
| { kind: 'positives'; measure: string; stratum: string; order: string[] }
| { kind: 'signs'; measure: string; strata: string[] }
| { kind: 'days'; steps: { label: string; measure: string }[] }
| { kind: 'days-by'; measure: string; stratum: string }
| { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] }
);
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar {
label: string;
color?: string;
width: number;
marks: number[];
cells: string[];
}
export interface Bars {
head: string[];
rows: Bar[];
}
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) {
case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
if (!total) return undefined;
// a category outside the catalog is listed after it, so the shares add up
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c));
const all = [
...mode.catalog,
...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
];
const most = Math.max(...Object.values(cells).map(size));
return {
head: ['n', '%'],
rows: all.map(({ code, label, color }) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
};
}
case 'shares': {
const cells = of(mode.measure)?.strata[mode.stratum] ?? {};
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]),
);
}
case 'positives': {
const cells = of(mode.measure)?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`])];
}),
);
}
case 'signs': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative'])];
}),
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
);
}
default:
return undefined;
}
}
function ratios(rows: [string, number, number][]): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', '%'],
rows: rows.map(([label, n, total]) => ({
label,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = { score?: number; low?: number; high?: number };
function medians(rows: { label: string; n: number; score?: Score }[]): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
};
}),
};
}
+19
View File
@@ -0,0 +1,19 @@
/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
+68 -37
View File
@@ -1,6 +1,6 @@
import type { Figure } from '../plot'; import { type Figure, PALETTE } from '../plot';
import type { Reading } from './measures'; import { name, type Reading } from './measures';
import type { Catalog, Category } from './pages'; import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
@@ -12,38 +12,6 @@ function rgba(hex: string, alpha: number): string {
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`; return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
} }
/** The screening route: each step's median days from the sample, with Q1–Q3. */
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}<br>n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: '%{y}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
/** A category's count in the report (the composition's `category` stratum). */ /** A category's count in the report (the composition's `category` stratum). */
function counted(r: Reading, code: string): number { function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0; return r.strata['category']?.[code]?.['initial-population'] ?? 0;
@@ -108,6 +76,8 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
labels: catalog.categories.map((c) => c.label), labels: catalog.categories.map((c) => c.label),
hole: 0.74, hole: 0.74,
domain: { x: [0, 1], y: [0, 1] }, domain: { x: [0, 1], y: [0, 1] },
// along the thin ring, so a label fits its slice
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')), text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: { marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)), colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
@@ -150,7 +120,8 @@ export function scenarioBars(
xaxis: { xaxis: {
title: { text: '% de pacientes del escenario con resultado' }, title: { text: '% de pacientes del escenario con resultado' },
ticksuffix: ' %', ticksuffix: ' %',
range: [0, 100], range: [0, 100.5],
dtick: 20,
}, },
yaxis: { yaxis: {
type: 'category', type: 'category',
@@ -159,7 +130,6 @@ export function scenarioBars(
categoryarray: y, categoryarray: y,
automargin: true, automargin: true,
}, },
legend: { orientation: 'h', y: -0.25 },
}, },
}; };
} }
@@ -415,3 +385,64 @@ export function ageShare(r: Reading, axis: string): Figure {
}, },
}; };
} }
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
* closed shape. */
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string) => ({
xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
return {
data: named.map((c) => ({
type: 'bar',
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
})),
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
return {
data: [
{
x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
mode: 'lines',
fill: 'toself',
fillcolor: line + '33',
line: { width: 0 },
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
hoverinfo: 'skip',
},
{
x,
y: series.map((s) => at(s.r?.score)),
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
};
}
+52
View File
@@ -0,0 +1,52 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
const HEAD = [
'Paciente',
'CURP',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
'LIEAG+',
'Cáncer',
'Días a diagnóstico',
];
/** A cytology's result, or why it has none. */
export function cytologyResult(c: NonNullable<Row['cytology']>): string {
if (c.result) return name(c.result);
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */
export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
return {
title: 'Resultados de seguimiento',
query: [...query, ['Registros', `${rows.length}`]],
head: HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
`${r.age ?? NONE}`,
name(r.status),
r.stages
.filter((s) => s.state !== 'unknown')
.map((s) => `${s.label}: ${s.day ?? STATES[s.state]}`)
.join('\n'),
r.cytology ? `${cytologyResult(r.cytology)} (${r.cytology.date})` : NONE,
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'} (${r.hpv.date})` : NONE,
r.biopsy ? `${name(r.biopsy.histology ?? '') || 'Sin grado'} (${r.biopsy.date})` : NONE,
percent(r.risk.cin2),
percent(r.risk.cancer),
`${r.daysToDiagnosis ?? NONE}`,
]),
};
}
+12 -1
View File
@@ -1,5 +1,5 @@
import type { RiskAssessment } from 'fhir/r4'; import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart } from './follow-up'; import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import { periods } from './measures'; import { periods } from './measures';
describe('follow-up list', () => { describe('follow-up list', () => {
@@ -45,3 +45,14 @@ describe('follow-up list', () => {
]); ]);
}); });
}); });
describe('ages', () => {
it('ask for the birth dates whose completed years fall in the range', () => {
expect(bornFor('2026-06-30', 36, 40)).toEqual(['le1990-06-30', 'gt1985-06-30']);
expect(bornFor('2026-06-30', null, null)).toEqual([]);
expect(bornFor('2024-02-29', 1, null)).toEqual(['le2023-02-28']);
expect([ageAt('1990-06-30', '2026-06-30'), ageAt('1990-07-01', '2026-06-30')]).toEqual([
36, 35,
]);
});
});
+34 -6
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir'; import { code, ext, resources } from '../fhir';
import { route, Stage } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */ /** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row { export interface Row {
@@ -8,6 +9,8 @@ export interface Row {
curp?: string; curp?: string;
status: string; status: string;
ageGroup: string; ageGroup: string;
age?: number;
stages: Stage[];
cytology?: { date: string; result?: string; adequacy?: string }; cytology?: { date: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean }; hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number; daysToDiagnosis?: number;
@@ -24,15 +27,36 @@ const AGE_GROUPS: [number, number][] = [
[55, 64], [55, 64],
]; ];
/** Completed years at a day. */
export function ageAt(birth: string | undefined, at: string): number | undefined {
if (!birth) return undefined;
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
return y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
}
/** The birth dates of who has completed between `from` and `to` years at a day, as FHIR's
* `birthdate` parameter. */
export function bornFor(at: string, from: number | null, to: number | null): string[] {
const back = (years: number) => `${Number(at.slice(0, 4)) - years}${at.slice(4)}`;
return [
...(from === null ? [] : [`le${valid(back(from))}`]),
...(to === null ? [] : [`gt${valid(back(to + 1))}`]),
];
}
/** February 29th in a year without one: the 28th. */
const valid = (day: string) =>
day.endsWith('-02-29') && new Date(`${day}T00:00:00Z`).getUTCMonth() !== 1
? `${day.slice(0, 8)}28`
: day;
export function ageGroup( export function ageGroup(
birth: string | undefined, birth: string | undefined,
at: string, at: string,
groups: [number, number][] = AGE_GROUPS, groups: [number, number][] = AGE_GROUPS,
): string { ): string {
if (!birth) return 'Sin dato'; const age = ageAt(birth, at);
const [by, bm, bd] = birth.split('-').map(Number); if (age === undefined) return 'Sin dato';
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const found = groups.find(([lo, hi]) => lo <= age && age <= hi); const found = groups.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`; if (found) return `${found[0]}-${found[1]}`;
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`; return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
@@ -103,6 +127,8 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff), ageGroup: ageGroup(patient.birthDate, cutoff),
age: ageAt(patient.birthDate, cutoff),
stages: route(last, cutoff),
cytology: last && { cytology: last && {
date: last.effectiveDateTime!, date: last.effectiveDateTime!,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept), result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
@@ -146,11 +172,12 @@ export interface CamaRow {
status: string; status: string;
priority: string; priority: string;
ageGroup: string; ageGroup: string;
mammogram: { date: string; birads?: string }; /** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
mammogram: { date: string; birads?: string; days?: number };
biopsy?: { date: string; histology?: string }; biopsy?: { date: string; histology?: string };
} }
const CAMA_AGE_GROUPS: [number, number][] = [ export const CAMA_AGE_GROUPS: [number, number][] = [
[40, 49], [40, 49],
[50, 59], [50, 59],
[60, 69], [60, 69],
@@ -196,6 +223,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
birads: mammogram birads: mammogram
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept) ? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
: undefined, : undefined,
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
}, },
biopsy: biopsy && { biopsy: biopsy && {
date: reported(biopsy)!, date: reported(biopsy)!,
+1 -1
View File
@@ -65,7 +65,7 @@ import { Loading } from '../loading';
} }
<mat-tab label="Datos y definiciones"> <mat-tab label="Datos y definiciones">
<ng-template matTabContent> <ng-template matTabContent>
<app-tab-definiciones [measures]="measures.value()!" /> <app-tab-definiciones [domain]="domain()" [measures]="measures.value()!" />
</ng-template> </ng-template>
</mat-tab> </mat-tab>
</mat-tab-group> </mat-tab-group>
+34 -1
View File
@@ -50,6 +50,8 @@ export interface Reading {
high?: number; high?: number;
unit?: string; unit?: string;
strata: Record<string, Record<string, Record<string, number>>>; strata: Record<string, Record<string, Record<string, number>>>;
/** A stratum value's own score (a median and its quartiles). */
scores?: Record<string, Record<string, { score?: number; low?: number; high?: number }>>;
} }
function counts(group: { function counts(group: {
@@ -65,6 +67,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined; if (!group) return undefined;
const score = group.measureScore; const score = group.measureScore;
const strata: Reading['strata'] = {}; const strata: Reading['strata'] = {};
const scores: NonNullable<Reading['scores']> = {};
for (const s of group.stratifier ?? []) { for (const s of group.stratifier ?? []) {
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`. // A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
@@ -76,6 +79,13 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
counts(x), counts(x),
]), ]),
); );
for (const { value, measureScore: own } of s.stratum ?? [])
if (own)
(scores[name] ??= {})[value?.text ?? ''] = {
score: own.value,
low: ext(own, 'q1')?.valueDecimal,
high: ext(own, 'q3')?.valueDecimal,
};
} }
return { return {
populations: counts(group), populations: counts(group),
@@ -84,11 +94,12 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit, unit: score?.unit,
strata, strata,
scores,
}; };
} }
/** Codes as the screens name them. */ /** Codes as the screens name them. */
const LABELS: Record<string, string> = { export const LABELS: Record<string, string> = {
NILM: 'Normal (NILM)', NILM: 'Normal (NILM)',
LSIL: 'LIEBG', LSIL: 'LIEBG',
HSIL: 'LIEAG', HSIL: 'LIEAG',
@@ -122,6 +133,21 @@ const LABELS: Record<string, string> = {
good: 'Bueno', good: 'Bueno',
bad: 'Malo', bad: 'Malo',
not_analyzed: 'Sin analizar', not_analyzed: 'Sin analizar',
initial: 'Inicial',
subsequent: 'Subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries( ...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
), ),
@@ -134,6 +160,13 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento', follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado', result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía', birads: 'BI-RADS de la mastografía',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}; };
export const name = (value: string) => LABELS[value] ?? value; export const name = (value: string) => LABELS[value] ?? value;
+280
View File
@@ -0,0 +1,280 @@
import type { Mode } from './bars';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: '#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'],
};
/** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#A8C243' },
{ code: 'positive_16', label: 'VPH 16', color: '#C24269' },
{ code: 'positive_18', label: 'VPH 18', color: '#9C42C2' },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' },
{ code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' },
{ code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' },
];
const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: '#C24269' },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' },
{ code: 'pending', label: 'Pendiente', color: '#C9CDD2' },
{ code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' },
];
/** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
kind: 'readings',
title,
headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut' },
{
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',
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
},
{
kind: 'shares',
label: 'VPH previo',
caption: 'Los grupos se traslapan.',
measure,
stratum: 'hpv',
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
},
{
kind: 'shares',
label: 'Nivel de histología',
measure,
stratum: 'level',
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
},
{
kind: 'shares',
label: 'Tamizaje',
measure,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
...more,
],
});
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
export const CACU: Page = {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: '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,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempos de la ruta del tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [
{
kind: 'days',
label: 'Acumulado desde la toma',
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: 'days',
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
],
},
{
kind: 'days-by',
label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
stratum: 'diagnosis_code',
},
],
},
],
clinical: [
{
kind: 'columns',
title: 'Resultados de citología, VPH y biopsia',
sections: [
{
kind: 'readings',
title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
},
{
kind: 'figure',
label: 'Por escenario clínico',
measure: 'CACU_EU7',
figure: 'scenarios',
catalog: CYTOLOGY.categories,
},
],
},
{
kind: 'readings',
title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.',
modes: [{ kind: 'counts', label: 'General', measure: 'CACU_VPH_GENOTIPO', catalog: HPV }],
},
{
kind: 'readings',
title: 'Resultados de biopsia cervical',
note: 'Reportes, por fecha de reporte.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories,
},
],
},
],
},
{
kind: 'readings',
title: 'Pacientes evaluadas por resultado de VPH',
headline: 'CACU_VPH',
note: 'Una vez cada paciente, por su última muestra con resultado.',
modes: [
{ kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' },
{
kind: 'positives',
label: 'Por grupo de edad',
measure: 'CACU_VPH',
stratum: 'age_group',
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
},
{
kind: 'positives',
label: 'Por estatus de seguimiento',
measure: 'CACU_VPH',
stratum: 'follow_up_status',
order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
},
{
kind: 'signs',
label: 'Por genotipo',
measure: 'CACU_VPH',
strata: ['hpv_16', 'hpv_18'],
},
{
kind: 'positives',
label: 'Por tamizaje',
measure: 'CACU_VPH',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
],
},
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
choices: [
{
label: 'Colposcopía',
section: ppv(
'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
},
),
},
],
},
],
};
+201 -106
View File
@@ -1,3 +1,6 @@
import type { Mode } from './bars';
import { CACU } from './pages-cacu';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui): /** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures. * the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */ * Measures are named by their code (`Measure.name`). */
@@ -17,8 +20,20 @@ export interface Kpi {
value?: string; value?: string;
note?: string; note?: string;
} }
/** A card read one mode at a time; `headline` is the measure its score comes from. */
export interface ReadingsCard {
kind: 'readings';
title: string;
headline?: string;
note?: string;
modes: Mode[];
}
export type Section = export type Section =
| { kind: 'route'; title: string; steps: { label: string; measure: string }[] } | ReadingsCard
/** Cards side by side; the last one alone when odd. */
| { kind: 'columns'; title: string; sections: ReadingsCard[] }
/** One section at a time. */
| { kind: 'choice'; title: string; choices: { label: string; section: ReadingsCard }[] }
| { kind: 'figures'; title?: string; figures: FigureSpec[] } | { kind: 'figures'; title?: string; figures: FigureSpec[] }
| { | {
kind: 'boxes'; kind: 'boxes';
@@ -80,47 +95,11 @@ export interface Catalog {
const OLIVE = '#A8C243'; const OLIVE = '#A8C243';
const ROSE = '#C24269'; const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
],
faded: ['normal', 'LSIL'],
};
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = { const CAMA_DAYS = {
value: '{median} días (mediana)', value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.', note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
}; };
const PENDING = 'Este indicador aún no está publicado por el catálogo institucional.'; const PENDING = 'Indicador no publicado en el catálogo institucional.';
/** BI-RADS 4 to 6 as the old app named and coloured them. */ /** BI-RADS 4 to 6 as the old app named and coloured them. */
const BIRADS: Catalog = { const BIRADS: Catalog = {
@@ -342,89 +321,205 @@ export const PAGES: Record<string, Page> = {
}, },
], ],
}, },
cacu: CACU,
};
/** 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: { cacu: {
anchor: 'CACU_EU7', line: '#6A8000',
kpis: [ months: 5,
{ panels: [
measure: 'CACU_EU7', stack('Distribución de resultados citológicos', 'CACU_EU7', 'Pacientes', [
title: 'Pacientes evaluadas', ['NILM', 'Normal', '#9DBFE3'],
value: '{n} pacientes', ['ASC-US', 'ASC-US', '#2F6DB3'],
note: 'Pacientes con citología tomada en el periodo.', ['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', measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado', kind: 'median',
...CACU_DAYS,
}, },
{ {
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico', title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS, measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
}, },
{ {
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento', title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS, measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
kind: 'median',
}, },
{ {
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento', title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS, measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
}, kind: 'median',
],
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: 'Riesgo CIN2+ por banda',
title: 'Distribución de resultados citológicos', measure: 'CACU_RIESGO_BANDA',
figures: [ kind: 'stack',
{ axis: 'Pacientes',
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',
},
],
}, },
], ],
}, },
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],
]),
],
},
}; };
@@ -0,0 +1,19 @@
import { matchesSearch, patientSearch } from './patient-search';
describe('patient search', () => {
it('asks the API by identifier for one word with a digit, else by name', () => {
expect(patientSearch(' IARM800101MNLBVR09 ')).toEqual({ identifier: 'IARM800101MNLBVR09' });
expect(patientSearch('0451A')).toEqual({ identifier: '0451A' });
expect(patientSearch('martha ibarra')).toEqual({ name: 'martha ibarra' });
expect(patientSearch('')).toEqual({});
});
it('matches in the browser by word starts, case and accents ignored', () => {
const texts = ['IBARRA RIVERA MARTHA', 'd5a6a924-f2ad', 'N0183'];
expect(matchesSearch('már riv', texts)).toBe(true);
expect(matchesSearch('d5a6', texts)).toBe(true);
expect(matchesSearch('n0183', texts)).toBe(true);
expect(matchesSearch('arth', texts)).toBe(false);
expect(matchesSearch('', texts)).toBe(true);
});
});
+83
View File
@@ -0,0 +1,83 @@
import { Component, model, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
/** A search box's text as FHIR Patient search parameters: one word with a digit is an
* identifier (a CURP or a record number); anything else is her name. */
export function patientSearch(text: string): { name?: string; identifier?: string } {
const t = text.trim();
if (!t) return {};
return /\d/.test(t) && !/\s/.test(t) ? { identifier: t } : { name: t };
}
const fold = (s: string) => s.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase();
/** Whether a row matches the search in the browser (lists loaded whole): each word starts a
* word of one of its texts (a name, an identifier, the pseudonymous id). */
export function matchesSearch(text: string, texts: (string | undefined)[]): boolean {
const words = fold(text).split(/\s+/).filter(Boolean);
if (!words.length) return true;
const known = texts.filter((t): t is string => !!t).map((t) => fold(t).split(/\s+/));
return known.some((parts) => words.every((w) => parts.some((p) => p.startsWith(w))));
}
/** "Buscar paciente": applied on Enter or the search button, cleared with the cross. */
@Component({
selector: 'app-patient-search',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="patient-search">
<mat-label>Buscar paciente</mat-label>
<input
matInput
type="search"
name="patient-search"
[placeholder]="hint"
[ngModel]="draft()"
[ngModelOptions]="{ standalone: true }"
(ngModelChange)="draft.set($event)"
(keydown.enter)="$event.preventDefault(); apply()"
/>
@if (value()) {
<button
mat-icon-button
matSuffix
type="button"
aria-label="Limpiar búsqueda"
(click)="clear()"
>
<mat-icon>close</mat-icon>
</button>
} @else {
<button mat-icon-button matSuffix type="button" aria-label="Buscar" (click)="apply()">
<mat-icon>search</mat-icon>
</button>
}
</mat-form-field>
`,
styles: `
.patient-search {
min-width: 18rem;
}
`,
})
export class PatientSearch {
/** The search as applied. */
readonly value = model('');
readonly searched = output<string>();
protected readonly draft = signal('');
protected readonly hint = 'Nombre, CURP o expediente';
protected apply(): void {
const text = this.draft().trim();
this.value.set(text);
this.searched.emit(text);
}
protected clear(): void {
this.draft.set('');
this.apply();
}
}
+144
View File
@@ -0,0 +1,144 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { bars, Mode } from './bars';
import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars. */
@Component({
selector: 'app-readings',
imports: [Loading, MatButtonToggleModule, Plot],
template: `
<h3 class="title">{{ title() }}</h3>
@if (headline()) {
<p class="headline">{{ headline() }}</p>
}
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1) {
<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 (loading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figure(); as f) {
<app-plot [figure]="f" [height]="300" />
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
<tr>
<th></th>
@for (h of t.head; track h) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
<span class="track" aria-hidden="true">
<span
class="bar"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m"></span>
}
</span>
</th>
@for (c of row.cells; track $index) {
<td>{{ c }}</td>
}
</tr>
}
</tbody>
</table>
} @else {
<p class="state">Sin datos en el periodo.</p>
}
`,
styles: `
:host {
display: block;
min-width: 0;
}
.title {
margin: 0 0 8px;
}
.headline {
font-weight: 500;
}
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;
}
th[scope='row'] {
text-align: left;
white-space: normal;
width: 60%;
}
.track {
background: rgba(0, 0, 0, 0.06);
display: block;
height: 8px;
position: relative;
}
.bar {
background: #a8c243;
display: block;
height: 100%;
}
.mark {
background: #333;
height: 12px;
position: absolute;
top: -2px;
width: 2px;
}
`,
})
export class Readings {
readonly title = input.required<string>();
readonly headline = input('');
readonly note = input('');
readonly modes = input.required<Mode[]>();
readonly loading = input(false);
/** A measure's reading in the applied period, and the figure of a mode that has one. */
readonly read = input.required<(measure: string) => Reading | undefined>();
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal('');
protected readonly mode = computed(
() => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0],
);
protected readonly table = computed(() => bars(this.mode(), this.read()));
protected readonly figure = computed(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
);
}
+105
View File
@@ -0,0 +1,105 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure } from 'fhir/r4';
import { Mode } from './bars';
import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { Section } from './pages';
import { Readings } from './readings';
/** The applied period's readings and the measures they are of. */
export interface Source {
loading: boolean;
reading: (measure: string) => Reading | undefined;
measure: (name: string) => Measure | undefined;
}
type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
/** A card of readings, several side by side, or one of several at a time. */
@Component({
selector: 'app-section',
imports: [MatButtonToggleModule, MatCardModule, Readings],
template: `
@let s = section();
@if (s.kind === 'readings') {
<mat-card appearance="outlined">
<mat-card-content>
<app-readings
[title]="s.title"
[headline]="headline()"
[note]="s.note ?? ''"
[modes]="s.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
</mat-card-content>
</mat-card>
} @else {
<h2>{{ s.title }}</h2>
@if (s.kind === 'columns') {
<div class="columns">
@for (inner of s.sections; track $index) {
<app-section [section]="inner" [of]="of()" />
}
</div>
} @else {
@let open = chosen() || s.choices[0].label;
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-section [section]="c.section" [of]="of()" />
}
}
}
}
`,
styles: `
:host {
display: block;
margin-top: 16px;
min-width: 0;
}
.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>();
protected readonly chosen = signal('');
protected readonly headline = computed(() => {
const s = this.section();
const code = s.kind === 'readings' ? s.headline : undefined;
const measure = code && this.of().measure(code);
const r = code && this.of().reading(code);
if (!measure || !r) return '';
const words = detail(measure, r);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
});
protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure);
const measure = this.of().measure(mode.measure);
if (!measure || !r?.populations['initial-population']) return undefined;
if (mode.figure === 'donut') return donut(measure, r);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(r, { groups: [], categories }, 'follow_up_status', name);
});
}
+106 -32
View File
@@ -1,5 +1,7 @@
import { Component, input } from '@angular/core'; import { Component, computed, input } from '@angular/core';
import type { Measure } from 'fhir/r4'; import type { Measure } from 'fhir/r4';
import { DOMAINS } from '../app';
import type { Domain } from '../api/models/domain';
import { code, label } from '../fhir'; import { code, label } from '../fhir';
import { periodTypes, STRATA } from './measures'; import { periodTypes, STRATA } from './measures';
@@ -14,48 +16,120 @@ const IMPROVEMENT: Record<string, string> = {
}; };
const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' }; const PERIODS: Record<string, string> = { semester: 'Semestral', month: 'Mensual' };
/** What each measure is: how it scores, which way is better, its periods and strata. */ /** "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
* strata). */
@Component({ @Component({
selector: 'app-tab-definiciones', selector: 'app-tab-definiciones',
template: ` template: `
<table class="plain card"> <section class="card">
<thead> <h2>Datos y definiciones de {{ domainName() }}</h2>
<tr> <section aria-labelledby="domain-info-title">
<th>Indicador</th> <h3 id="domain-info-title">Información del dominio</h3>
<th>Clave</th> @if (domain() === 'cacu') {
<th>Cálculo</th> <p>
<th>Mejora</th> Pacientes evaluadas incluye a las pacientes con citología tomada en el periodo cuyo
<th>Periodos</th> espécimen fue insatisfactorio.
<th>Estratos</th> </p>
</tr>
</thead>
<tbody>
@for (m of measures(); track m.id) {
<tr>
<td>{{ m.title }}</td>
<td>
<code>{{ m.name }}</code> v{{ m.version }}
</td>
<td>{{ scoring[code(m.scoring) ?? ''] }}</td>
<td>{{ improvement[code(m.improvementNotation) ?? ''] ?? '—' }}</td>
<td>{{ types(m) }}</td>
<td>{{ strata(m) }}</td>
</tr>
} }
</tbody> @if (available().length) {
</table> <p>Periodicidad disponible: {{ available().join(', ') }}.</p>
} @else {
<p>Periodicidad: pendiente de información.</p>
}
</section>
<section aria-labelledby="definitions-catalog-title">
<h3 id="definitions-catalog-title">Catálogo de indicadores</h3>
<p>Consulta las gráficas disponibles y la periodicidad de cada indicador.</p>
@for (m of measures(); track m.id) {
<details>
<summary>{{ m.title || 'Nombre pendiente de publicación' }}</summary>
<div class="indicator-detail">
@if (m.description) {
<p>{{ m.description }}</p>
}
<h4>Cálculo</h4>
<p>
{{ scoring[code(m.scoring) ?? ''] }}
@if (improvement[code(m.improvementNotation) ?? '']; as better) {
· {{ better }}
}
</p>
<h4>Tipos de periodo admitidos</h4>
@if (types(m).length) {
<ul>
@for (t of types(m); track t) {
<li>{{ t }}</li>
}
</ul>
} @else {
<p>Pendiente de información.</p>
}
<h4>Estratos</h4>
<p>{{ strata(m) }}</p>
<p class="muted">
Clave <code>{{ m.name }}</code> · versión {{ m.version }}
</p>
</div>
</details>
} @empty {
<p role="status">
No hay indicadores disponibles en el catálogo. Las definiciones están pendientes de
información.
</p>
}
</section>
</section>
`,
styles: `
:host {
display: block;
padding-top: 16px;
}
.card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
}
h2,
h3 {
font-size: 20px;
font-weight: 500;
}
h4 {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
details {
border-bottom: 1px solid var(--mat-sys-outline-variant);
padding: 8px 0;
}
summary {
cursor: pointer;
font-weight: 500;
}
.indicator-detail {
padding: 4px 0 8px 16px;
}
`, `,
styles: ':host { display: block; padding-top: 16px; overflow-x: auto; }',
}) })
export class TabDefiniciones { export class TabDefiniciones {
readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly scoring = SCORING; protected readonly scoring = SCORING;
protected readonly improvement = IMPROVEMENT; protected readonly improvement = IMPROVEMENT;
protected readonly code = code; protected readonly code = code;
protected types(m: Measure): string { protected readonly domainName = computed(
return periodTypes(m) () => DOMAINS[this.domain() as Domain]?.toLocaleLowerCase('es-MX') ?? this.domain(),
.map((p) => PERIODS[p] ?? p) );
.join(', '); /** The periodicities any of its indicators admits. */
protected readonly available = computed(() =>
[...new Set(this.measures().flatMap((m) => periodTypes(m)))].map((p) => PERIODS[p] ?? p),
);
protected types(m: Measure): string[] {
return periodTypes(m).map((p) => PERIODS[p] ?? p);
} }
protected strata(m: Measure): string { protected strata(m: Measure): string {
const names = (m.group?.[0]?.stratifier ?? []).map((s) => code(s.code) ?? label(s.code)); const names = (m.group?.[0]?.stratifier ?? []).map((s) => code(s.code) ?? label(s.code));
+20 -13
View File
@@ -34,7 +34,7 @@
@if (reports.error()) { @if (reports.error()) {
<div class="load-error" role="alert"> <div class="load-error" role="alert">
<p>No se pudieron leer los indicadores del periodo. Vuelve a intentar.</p> <p>No se obtuvieron los indicadores del periodo.</p>
<button mat-stroked-button (click)="reports.reload()">Reintentar</button> <button mat-stroked-button (click)="reports.reload()">Reintentar</button>
</div> </div>
} }
@@ -53,7 +53,13 @@
@if (reports.isLoading() && k.measure) { @if (reports.isLoading() && k.measure) {
<app-loading [what]="k.title.toLowerCase()" /> <app-loading [what]="k.title.toLowerCase()" />
} @else { } @else {
<div class="kpi-value" [class.pending]="!k.measure">{{ kpiValue(k) }}</div> <div class="kpi-value" [class.pending]="!k.measure">
@let v = kpiParts(kpiValue(k));
{{ v[0] }}
@if (v[1]) {
<span class="kpi-qualifier">{{ v[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(k) }}</div> <div class="kpi-detail">{{ kpiNote(k) }}</div>
} }
</mat-card-content> </mat-card-content>
@@ -79,15 +85,10 @@
<ng-template #sectionView let-section let-period="period"> <ng-template #sectionView let-section let-period="period">
@switch (section.kind) { @switch (section.kind) {
@case ('route') { @case ('readings')
<h3 class="route-title">{{ section.title }}</h3> @case ('columns')
@if (reports.isLoading()) { @case ('choice') {
<app-loading what="los tiempos de la ruta" [figure]="true" /> <app-section [section]="section" [of]="of()" />
} @else if (routeOf(section); as fig) {
<app-plot [figure]="fig" [height]="300" />
} @else {
<p class="state">Sin tiempos publicados en el periodo.</p>
}
} }
@case ('tea-summary') { @case ('tea-summary') {
@if (teaSummary(); as t) { @if (teaSummary(); as t) {
@@ -152,7 +153,7 @@
<mat-card-content> <mat-card-content>
<h2 class="box-title">{{ b.title }}</h2> <h2 class="box-title">{{ b.title }}</h2>
@if (!b.measure) { @if (!b.measure) {
<p class="state"><strong>Integración pendiente.</strong> {{ pending }}</p> <p class="state">{{ pending }}</p>
<div class="empty-figure">Sin datos publicados</div> <div class="empty-figure">Sin datos publicados</div>
} @else { } @else {
<p class="state">Filtro general aplicado: {{ period }}</p> <p class="state">Filtro general aplicado: {{ period }}</p>
@@ -177,7 +178,13 @@
<mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure"> <mat-card appearance="outlined" class="kpi closing" [attr.data-measure]="section.measure">
<mat-card-content> <mat-card-content>
<h3 class="kpi-title">{{ section.title }}</h3> <h3 class="kpi-title">{{ section.title }}</h3>
<div class="kpi-value">{{ kpiValue(section) }}</div> <div class="kpi-value">
@let w = kpiParts(kpiValue(section));
{{ w[0] }}
@if (w[1]) {
<span class="kpi-qualifier">{{ w[1] }}</span>
}
</div>
<div class="kpi-detail">{{ kpiNote(section) }}</div> <div class="kpi-detail">{{ kpiNote(section) }}</div>
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+8
View File
@@ -61,6 +61,14 @@ h2 {
font-size: 2rem; font-size: 2rem;
font-weight: 500; font-weight: 500;
margin: var(--space-2) 0; margin: var(--space-2) 0;
line-height: 1.15;
}
.kpi-qualifier {
display: block;
font-size: 14px;
font-weight: 400;
color: var(--color-text-secondary);
} }
.kpi-detail { .kpi-detail {
+18 -9
View File
@@ -17,7 +17,6 @@ import {
fill, fill,
nestedDonut, nestedDonut,
rateDots, rateDots,
routeFigure,
scenarioBars, scenarioBars,
shareDonut, shareDonut,
} from './figures'; } from './figures';
@@ -38,6 +37,7 @@ import {
strataBars, strataBars,
} from './measures'; } from './measures';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { ReadingsSection, Source } from './section';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per /** The period's indicators: the timeliness KPIs, the screening route, and a card per
* clinical measure with its figures. */ * clinical measure with its figures. */
@@ -52,6 +52,7 @@ import { Loading } from '../loading';
MatCardModule, MatCardModule,
MatSelectModule, MatSelectModule,
Plot, Plot,
ReadingsSection,
], ],
templateUrl: './tab-indicadores.html', templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss', styleUrl: './tab-indicadores.scss',
@@ -71,8 +72,7 @@ export class TabIndicadores {
protected readonly layout = computed( protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
); );
protected readonly pending = protected readonly pending = 'Indicador no publicado en el catálogo institucional.';
'Este indicador aún no está publicado por el catálogo institucional.';
/** The old app's page for this domain, when it is rebuilt as it was (else today's). */ /** The old app's page for this domain, when it is rebuilt as it was (else today's). */
protected readonly page = computed(() => PAGES[this.domain()]); protected readonly page = computed(() => PAGES[this.domain()]);
private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m]))); private readonly byName = computed(() => new Map(this.measures().map((m) => [m.name!, m])));
@@ -202,6 +202,12 @@ export class TabIndicadores {
return this.byName().get(code); return this.byName().get(code);
} }
/** A card's value and note, from its templates (a card with no measure: its words). */ /** A card's value and note, from its templates (a card with no measure: its words). */
/** "27 días (mediana)" as the value and its qualifier, shown smaller beneath it. */
protected kpiParts(text: string): [string, string] {
const found = /^(.*?)\s*(\([^)]*\))$/.exec(text);
return found ? [found[1], found[2]] : [text, ''];
}
protected kpiValue(k: Kpi): string { protected kpiValue(k: Kpi): string {
if (!k.measure) return k.value ?? ''; if (!k.measure) return k.value ?? '';
const r = this.rd(k.measure); const r = this.rd(k.measure);
@@ -259,12 +265,15 @@ export class TabIndicadores {
protected measureTitle(code: string | undefined): string { protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || ''; return (code && this.byName().get(code)?.title) || '';
} }
/** A clinical section's route or figures, drawn from the applied period's reports. */ /** What a section of readings is drawn from. */
protected routeOf(section: Section): Figure | undefined { protected readonly of = computed<Source>(() => {
if (section.kind !== 'route') return undefined; const found = this.loaded();
const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) })); return {
return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined; loading: this.reports.isLoading(),
} reading: (code) => found?.get(code),
measure: (code) => this.byName().get(code),
};
});
protected figureOf(spec: FigureSpec): Figure | undefined { protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure); const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined; if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
+2 -1
View File
@@ -1,6 +1,7 @@
<section class="card risk-tea" aria-labelledby="tea-risk-title"> <section class="card risk-tea" aria-labelledby="tea-risk-title">
<h2 id="tea-risk-title" class="risk-title">Alteraciones de EEG relacionadas al TEA</h2> <h2 id="tea-risk-title" class="risk-title">Alteraciones de EEG relacionadas al TEA</h2>
<div class="filters"> <div class="filters">
<app-patient-search [(value)]="search" (searched)="pageIndex.set(0)" />
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" /> <input matInput type="date" [ngModel]="cutoff()" (ngModelChange)="cutoff.set($event)" />
@@ -147,7 +148,7 @@
</tr> </tr>
} @empty { } @empty {
<tr> <tr>
<td colspan="7" class="muted">Nadie en la lista con estos filtros.</td> <td colspan="7" class="muted">No hay registros para los filtros aplicados.</td>
</tr> </tr>
} }
</tbody> </tbody>
+17 -3
View File
@@ -1,3 +1,4 @@
import { METRIC_NAMES } from '../eeg-labels';
import { KeyValuePipe } from '@angular/common'; import { KeyValuePipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
@@ -11,6 +12,7 @@ import { EXT, Fhir, resources } from '../fhir';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { ageLabel } from './figures'; import { ageLabel } from './figures';
import { name } from './measures'; import { name } from './measures';
import { matchesSearch, PatientSearch } from './patient-search';
/** One child on TEA's list, as the list shows her (core.tea.follow_up). */ /** One child on TEA's list, as the list shows her (core.tea.follow_up). */
export interface TeaRow { export interface TeaRow {
@@ -67,14 +69,18 @@ const CASE: Record<string, string> = {
not_confirmed: 'Sin TEA', not_confirmed: 'Sin TEA',
}; };
/** `theta_power:above` → "theta_power (aumentado)". */ /** `theta_power:above` → "theta_power (aumentado)". */
export const alteration = (a: string) => export const alteration = (a: string) => {
a.replace(/:(above|below)$/, (_, s) => (s === 'above' ? ' (aumentado)' : ' (disminuido)')); const [metric, side] = a.split(':');
const shown = (METRIC_NAMES[metric] ?? metric).replace(/ \(.*\)$/, '');
return side ? `${shown} (${side === 'above' ? 'aumentado' : 'disminuido'})` : shown;
};
/** "Análisis de Riesgo" for TEA: the children active in the window, what their EEGs show, /** "Análisis de Riesgo" for TEA: the children active in the window, what their EEGs show,
* filtered as the old page filtered them. */ * filtered as the old page filtered them. */
@Component({ @Component({
selector: 'app-tab-riesgos-tea', selector: 'app-tab-riesgos-tea',
imports: [ imports: [
PatientSearch,
FormsModule, FormsModule,
KeyValuePipe, KeyValuePipe,
Loading, Loading,
@@ -100,6 +106,8 @@ export class TabRiesgosTea {
protected readonly caseState = signal(''); protected readonly caseState = signal('');
protected readonly altered = signal(''); protected readonly altered = signal('');
protected readonly size = signal(50); protected readonly size = signal(50);
/** "Buscar paciente": the pseudonymous id, a record number or a name. */
protected readonly search = signal('');
protected readonly pageIndex = signal(0); protected readonly pageIndex = signal(0);
/** The query as last asked for ("Consultar"). */ /** The query as last asked for ("Consultar"). */
private readonly asked = signal({ cutoff: '', window: 3 }); private readonly asked = signal({ cutoff: '', window: 3 });
@@ -141,7 +149,13 @@ export class TabRiesgosTea {
(!band || (r.mchat !== undefined && band.test(r.mchat))) && (!band || (r.mchat !== undefined && band.test(r.mchat))) &&
(!level || (r.css !== undefined && level.test(r.css))) && (!level || (r.css !== undefined && level.test(r.css))) &&
(!this.caseState() || r.case === this.caseState()) && (!this.caseState() || r.case === this.caseState()) &&
(!this.altered() || r.alterations.includes(this.altered())), (!this.altered() || r.alterations.includes(this.altered())) &&
matchesSearch(this.search(), [
r.name,
r.patient.id,
...(r.patient.name ?? []).map((n) => n.text),
...(r.patient.identifier ?? []).map((i) => i.value),
]),
); );
}); });
protected readonly shown = computed(() => protected readonly shown = computed(() =>
+130 -40
View File
@@ -1,4 +1,5 @@
<form class="filters card" (submit)="$event.preventDefault()"> <form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input <input
@@ -10,7 +11,31 @@
/> />
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label> <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)"> <mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@for (m of [1, 3, 6, 12]; track m) { @for (m of [1, 3, 6, 12]; track m) {
<mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option> <mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option>
@@ -18,7 +43,7 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label> <mat-label>Estatus de seguimiento</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)"> <mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option> <mat-option value="">Todos</mat-option>
@for (s of statuses; track s) { @for (s of statuses; track s) {
@@ -27,7 +52,7 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Horizonte</mat-label> <mat-label>Horizonte de la probabilidad</mat-label>
<mat-select [value]="horizon()" (selectionChange)="horizon.set($event.value)"> <mat-select [value]="horizon()" (selectionChange)="horizon.set($event.value)">
@for (h of [1, 2, 3, 4, 5]; track h) { @for (h of [1, 2, 3, 4, 5]; track h) {
<mat-option [value]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</mat-option> <mat-option [value]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</mat-option>
@@ -35,7 +60,7 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Orden</mat-label> <mat-label>Ordenar por</mat-label>
<mat-select [value]="sort()" (selectionChange)="sort.set($event.value)"> <mat-select [value]="sort()" (selectionChange)="sort.set($event.value)">
<mat-option value="-recent">Estudio más reciente</mat-option> <mat-option value="-recent">Estudio más reciente</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option> <mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option>
@@ -43,91 +68,157 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label> <mat-label>Registros por página</mat-label>
<mat-select [value]="size()" (selectionChange)="size.set($event.value)"> <mat-select [value]="size()" (selectionChange)="size.set($event.value)">
@for (n of [20, 50, 100]; track n) { @for (n of [20, 50, 100]; track n) {
<mat-option [value]="n">{{ n }}</mat-option> <mat-option [value]="n">{{ n }}</mat-option>
} }
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form> </form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) { @if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p> <p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
<button mat-button type="button" (click)="retry()">Reintentar seguimiento</button>
</p>
} @else if (!page() || loading()) {
<app-loading what="seguimiento" />
} @else if (applied()) {
<p class="muted window">Ventana consultada: {{ start() }} al {{ applied() }}.</p>
} }
<div class="table-wrap card"> <div class="table-wrap card">
<table class="plain worklist"> <table class="plain worklist">
<caption>
Resultados disponibles por paciente
</caption>
<thead> <thead>
<tr> <tr>
<th>Paciente</th> <th>Paciente</th>
<th>Grupo de edad</th> <th>Edad</th>
<th>Estatus</th> <th>Estatus de seguimiento</th>
<th>Etapas</th>
<th>Última citología</th> <th>Última citología</th>
<th>VPH</th> <th>Último resultado de VPH</th>
<th>Biopsia</th> <th>Última biopsia</th>
<th>Riesgo LIEAG+ ({{ horizon() }} a)</th> <th>Probabilidad a LIEAG+ a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Riesgo cáncer ({{ horizon() }} a)</th> <th>Probabilidad a cáncer a {{ horizon() }} {{ horizon() === 1 ? 'año' : 'años' }} (%)</th>
<th>Días toma → diagnóstico</th> <th>Estudio más reciente</th>
<th>Días de toma a diagnóstico</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (row of rows(); track row.patient.id) { @for (row of rows(); track row.patient.id) {
<tr> <tr>
<td> <td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{ <a
row.name ?? row.patient.id!.slice(0, 10) [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
}}</a> [queryParams]="{ corte: applied(), citologia: row.cytology?.date }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
>
@if (row.curp) { @if (row.curp) {
<div class="muted curp">{{ row.curp }}</div> <div class="muted curp">{{ row.curp }}</div>
} }
</td> </td>
<td>{{ row.ageGroup }}</td> <td>
{{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup }}</small>
</td>
<td>{{ name(row.status) }}</td> <td>{{ name(row.status) }}</td>
<td>
<app-stages [stages]="row.stages" />
<button
mat-button
type="button"
[attr.aria-expanded]="opened() === row.patient.id"
(click)="toggle(row)"
>
Detalle
</button>
</td>
<td> <td>
@if (row.cytology; as c) { @if (row.cytology; as c) {
{{ c.date }} · {{ result(c) }}
{{ <small>Fecha: {{ c.date }}</small>
c.result <small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
? name(c.result)
: c.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}}
} @else { } @else {
— No disponible
} }
</td> </td>
<td> <td>
@if (row.hpv; as h) { @if (row.hpv; as h) {
{{ h.positive ? 'Positivo' : 'Negativo' }}{{ h.types1618 ? ' (16/18)' : '' }} {{ h.positive ? 'Positivo' : 'Negativo' }}
<small>Fecha: {{ h.date }}</small>
<small
>Genotipo 16/18:
{{
h.types1618 === undefined
? 'No disponible'
: h.types1618
? 'Presente'
: 'No detectado'
}}</small
>
} @else { } @else {
— No disponible
} }
</td> </td>
<td> <td>
@if (row.biopsy; as b) { @if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin dato' }} {{ name(b.histology ?? '') || 'Sin grado' }}
<small>Fecha: {{ b.date }}</small>
} @else { } @else {
— No disponible
} }
</td> </td>
<td class="num"> <td class="num">
{{ row.risk.cin2 === undefined ? '—' : (row.risk.cin2 * 100 | number: '1.1-1') + ' %' }} {{
row.risk.cin2 === undefined
? 'No disponible'
: (row.risk.cin2 * 100 | number: '1.1-1') + ' %'
}}
</td> </td>
<td class="num"> <td class="num">
{{ {{
row.risk.cancer === undefined ? '—' : (row.risk.cancer * 100 | number: '1.1-1') + ' %' row.risk.cancer === undefined
? 'No disponible'
: (row.risk.cancer * 100 | number: '1.1-1') + ' %'
}} }}
</td> </td>
<td class="num">{{ row.daysToDiagnosis ?? '—' }}</td> <td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr> </tr>
@if (opened() === row.patient.id) {
<tr class="stage-detail">
<td colspan="11"><app-stages [stages]="row.stages" [detail]="true" /></td>
</tr>
}
} @empty { } @empty {
<tr> @if (page() && !loading()) {
<td colspan="9" class="muted"> <tr>
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} <td colspan="11" class="muted">No hay registros para los filtros aplicados.</td>
</td> </tr>
</tr> }
} }
</tbody> </tbody>
</table> </table>
@@ -136,8 +227,7 @@
<div class="pager"> <div class="pager">
<span class="muted"> <span class="muted">
@if (page()?.total; as total) { @if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
{{ applied() }}
} }
</span> </span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()"> <button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
+20
View File
@@ -10,6 +10,11 @@
margin-bottom: var(--space-4); margin-bottom: var(--space-4);
} }
// a field as wide as its label ("Horizonte de la probabilidad")
.filters mat-form-field {
min-width: 14.5rem;
}
.table-wrap { .table-wrap {
overflow-x: auto; overflow-x: auto;
padding: 0; padding: 0;
@@ -40,3 +45,18 @@ a {
.pager .muted { .pager .muted {
margin-right: auto; margin-right: auto;
} }
.worklist td small {
display: block;
white-space: nowrap;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
.worklist caption {
text-align: left;
font-weight: 500;
padding: 8px 0;
}
.window {
margin: 4px 0 8px;
}
+102 -18
View File
@@ -1,5 +1,13 @@
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import {
Component,
computed,
inject,
input,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
@@ -8,7 +16,12 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { 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 './measures';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']; const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
@@ -18,13 +31,16 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
@Component({ @Component({
selector: 'app-tab-riesgos', selector: 'app-tab-riesgos',
imports: [ imports: [
PatientSearch,
DecimalPipe, DecimalPipe,
FormsModule, FormsModule,
Loading,
MatButtonModule, MatButtonModule,
MatFormFieldModule, MatFormFieldModule,
MatInputModule, MatInputModule,
MatSelectModule, MatSelectModule,
RouterLink, RouterLink,
Stages,
], ],
templateUrl: './tab-riesgos.html', templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss', styleUrl: './tab-riesgos.scss',
@@ -39,33 +55,45 @@ export class TabRiesgos {
protected readonly horizon = signal(5); protected readonly horizon = signal(5);
protected readonly sort = signal('-recent'); protected readonly sort = signal('-recent');
protected readonly size = signal(20); protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
/** Completed years at the cut-off (none: no limit). */
protected readonly ageFrom = signal<number | null>(null);
protected readonly ageTo = signal<number | null>(null);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** Whose stages are shown in full. */
protected readonly opened = signal<string | undefined>(undefined);
/** A page the user moved to (`next`/`previous`), else the first. */ /** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined); private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
protected readonly name = name; protected readonly name = name;
protected readonly result = cytologyResult;
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
birthdate: bornFor(this.cutoff(), this.ageFrom(), this.ageTo()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({ private readonly first = resource({
params: () => ({ params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
domain: this.domain(), loader: ({ params: { domain, query, size } }) => {
'follow-up-window': this.window(),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined); this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', { return this.fhir.search(domain, 'Patient', { ...query, _count: size });
...params,
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
}, },
}); });
protected readonly loading = signal(false); protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value()); protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
/** The cut-off as applied (the server's default when none is given). */ /** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => { protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url; const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
@@ -84,6 +112,62 @@ export class TabRiesgos {
}); });
protected readonly error = computed(() => this.first.error()); protected readonly error = computed(() => this.first.error());
/** "Ventana consultada": the window's first day for the applied cut-off. */
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
/** "Estudio más reciente": her latest cytology or HPV sample. */
protected latest(row: Row): string | undefined {
return [row.cytology?.date, row.hpv?.date]
.filter((d) => !!d)
.sort()
.at(-1)
?.slice(0, 10);
}
protected retry(): void {
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 { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
+36 -20
View File
@@ -1,4 +1,5 @@
<form class="filters card" (submit)="$event.preventDefault()"> <form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input <input
@@ -10,7 +11,7 @@
/> />
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana</mat-label> <mat-label>Ventana de meses</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)"> <mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@for (m of [1, 3, 6, 12]; track m) { @for (m of [1, 3, 6, 12]; track m) {
<mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option> <mat-option [value]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</mat-option>
@@ -18,7 +19,7 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estatus</mat-label> <mat-label>Estatus de seguimiento</mat-label>
<mat-select [value]="status()" (selectionChange)="status.set($event.value)"> <mat-select [value]="status()" (selectionChange)="status.set($event.value)">
<mat-option value="">Todos</mat-option> <mat-option value="">Todos</mat-option>
@for (s of statuses; track s) { @for (s of statuses; track s) {
@@ -27,7 +28,7 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Por página</mat-label> <mat-label>Registros por página</mat-label>
<mat-select [value]="size()" (selectionChange)="size.set($event.value)"> <mat-select [value]="size()" (selectionChange)="size.set($event.value)">
@for (n of [20, 50, 100]; track n) { @for (n of [20, 50, 100]; track n) {
<mat-option [value]="n">{{ n }}</mat-option> <mat-option [value]="n">{{ n }}</mat-option>
@@ -37,18 +38,28 @@
</form> </form>
@if (error()) { @if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p> <p class="muted" role="alert">
No se pudo leer la lista de seguimiento.
<button mat-button type="button" (click)="retry()">Reintentar seguimiento</button>
</p>
} @else if (!page() || loading()) {
<app-loading what="seguimiento" />
} @else if (applied()) {
<p class="muted window">Ventana consultada: {{ start() }} al {{ applied() }}.</p>
} }
<div class="table-wrap card"> <div class="table-wrap card">
<table class="plain worklist"> <table class="plain worklist">
<caption>
Resultados disponibles por paciente
</caption>
<thead> <thead>
<tr> <tr>
<th>Paciente</th> <th>Paciente</th>
<th>Grupo de edad</th> <th>Grupo de edad</th>
<th>Mastografía</th> <th>Última mastografía</th>
<th>Biopsia</th> <th>Última biopsia</th>
<th>Estatus</th> <th>Estatus de seguimiento</th>
<th>Prioridad</th> <th>Prioridad</th>
</tr> </tr>
</thead> </thead>
@@ -56,31 +67,37 @@
@for (row of rows(); track row.patient.id) { @for (row of rows(); track row.patient.id) {
<tr> <tr>
<td> <td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{ <a
row.name ?? row.patient.id!.slice(0, 10) [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
}}</a> [queryParams]="{ ventana: window(), corte: applied() }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
>
@if (row.curp) { @if (row.curp) {
<div class="muted curp">{{ row.curp }}</div> <div class="muted curp">{{ row.curp }}</div>
} }
</td> </td>
<td>{{ row.ageGroup }}</td> <td>{{ row.ageGroup }}</td>
<td>{{ row.mammogram.date }} · {{ name(row.mammogram.birads ?? '') || 'Sin dato' }}</td> <td>
{{ name(row.mammogram.birads ?? '') || 'Sin dato' }}
<small>Fecha: {{ row.mammogram.date }}</small>
</td>
<td> <td>
@if (row.biopsy; as b) { @if (row.biopsy; as b) {
{{ b.date }} · {{ name(b.histology ?? '') || 'Sin resultado' }} {{ name(b.histology ?? '') || 'Sin resultado' }}
<small>Fecha: {{ b.date }}</small>
} @else { } @else {
— No disponible
} }
</td> </td>
<td>{{ name(row.status) }}</td> <td>{{ name(row.status) }}</td>
<td>{{ priority(row.priority) }}</td> <td>{{ priority(row.priority) }}</td>
</tr> </tr>
} @empty { } @empty {
<tr> @if (page() && !loading()) {
<td colspan="6" class="muted"> <tr>
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} <td colspan="6" class="muted">No hay registros para los filtros aplicados.</td>
</td> </tr>
</tr> }
} }
</tbody> </tbody>
</table> </table>
@@ -89,8 +106,7 @@
<div class="pager"> <div class="pager">
<span class="muted"> <span class="muted">
@if (page()?.total; as total) { @if (page()?.total; as total) {
{{ offset() + 1 }}–{{ offset() + rows().length }} de {{ total }} pacientes · corte Página {{ pageNumber() }} de {{ pageCount() }}, {{ total }} registros
{{ applied() }}
} }
</span> </span>
<button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()"> <button mat-stroked-button (click)="go('previous')" [disabled]="!has('previous') || loading()">
+22 -2
View File
@@ -7,7 +7,9 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { camaRows } from './follow-up'; import { camaRows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
import { name, PRIORITY } from './measures'; import { name, PRIORITY } from './measures';
const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy']; const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy'];
@@ -17,7 +19,9 @@ const STATUSES = ['cancer', 'pending_biopsy', 'biopsy_no_result', 'benign_biopsy
@Component({ @Component({
selector: 'app-tab-seguimiento', selector: 'app-tab-seguimiento',
imports: [ imports: [
PatientSearch,
FormsModule, FormsModule,
Loading,
MatButtonModule, MatButtonModule,
MatFormFieldModule, MatFormFieldModule,
MatInputModule, MatInputModule,
@@ -35,6 +39,8 @@ export class TabSeguimiento {
protected readonly window = signal(3); protected readonly window = signal(3);
protected readonly status = signal<string>(''); protected readonly status = signal<string>('');
protected readonly size = signal(20); protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
private readonly moved = signal<Bundle | undefined>(undefined); private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
@@ -45,6 +51,7 @@ export class TabSeguimiento {
params: () => ({ params: () => ({
domain: this.domain(), domain: this.domain(),
'follow-up-window': this.window(), 'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined, 'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined, 'follow-up-status': this.status() || undefined,
_count: this.size(), _count: this.size(),
@@ -59,7 +66,9 @@ export class TabSeguimiento {
}, },
}); });
protected readonly loading = signal(false); protected readonly loading = signal(false);
protected readonly page = computed(() => this.moved() ?? this.first.value()); protected readonly page = computed(
() => this.moved() ?? (this.first.hasValue() ? this.first.value() : undefined),
);
protected readonly applied = computed(() => { protected readonly applied = computed(() => {
const self = this.page()?.link?.find((l) => l.relation === 'self')?.url; const self = this.page()?.link?.find((l) => l.relation === 'self')?.url;
return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : ''; return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
@@ -75,6 +84,17 @@ export class TabSeguimiento {
}); });
protected readonly error = computed(() => this.first.error()); protected readonly error = computed(() => this.first.error());
protected readonly start = computed(() =>
this.applied() ? windowStart(this.applied(), this.window()) : '',
);
protected readonly pageNumber = computed(() => Math.floor(this.offset() / this.size()) + 1);
protected readonly pageCount = computed(() =>
Math.max(1, Math.ceil((this.page()?.total ?? 0) / this.size())),
);
protected retry(): void {
this.first.reload();
}
protected has(relation: 'next' | 'previous'): boolean { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
+90 -39
View File
@@ -1,58 +1,92 @@
import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure, MeasureReport } from 'fhir/r4'; import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { history, periods, PeriodType, periodTypes, reading } from './measures';
import { Loading } from '../loading'; 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';
/** Each measure over time: every period of the chosen kind, oldest first. */ interface Drawn {
panel: HistoryPanel;
/** the group's heading, on the first panel of its run */
heading?: string;
figure?: Figure;
}
/** Trazabilidad as the old tab: the domain's declared panels (pages.HISTORY), in their order,
* each measure period by period. */
@Component({ @Component({
selector: 'app-tab-trazabilidad', selector: 'app-tab-trazabilidad',
imports: [Loading, MatButtonToggleModule, MatCardModule, Plot], imports: [Loading, MatButtonToggleModule, Plot],
template: ` template: `
<div class="bar"> <section class="card filters" aria-labelledby="history-filters">
<h2 id="history-filters" class="filters-title">Filtros</h2>
<mat-button-toggle-group <mat-button-toggle-group
[value]="type()" [value]="type()"
(change)="type.set($event.value)" (change)="type.set($event.value)"
aria-label="Intervalo" aria-label="Intervalo de análisis"
> >
<mat-button-toggle value="month">Mensual</mat-button-toggle> <mat-button-toggle value="month">Mensual</mat-button-toggle>
<mat-button-toggle value="semester">Semestral</mat-button-toggle> <mat-button-toggle value="semester">Semestral</mat-button-toggle>
</mat-button-toggle-group> </mat-button-toggle-group>
</div> </section>
@if (series.isLoading()) { @if (series.isLoading()) {
<app-loading what="las series" text="Calculando las series del periodo…" /> <app-loading what="la trazabilidad" text="Cargando trazabilidad…" />
} } @else if (series.error()) {
<div class="grid"> <p class="muted" role="alert">
@for (item of figures(); track item.measure.id) { No se pudo cargar la trazabilidad.
<mat-card appearance="outlined" [attr.data-measure]="item.measure.name"> <button type="button" class="retry" (click)="series.reload()">Reintentar</button>
<mat-card-header </p>
><mat-card-title>{{ item.measure.title }}</mat-card-title></mat-card-header } @else {
> @for (d of drawn(); track d.panel.measure) {
<mat-card-content><app-plot [figure]="item.figure" [height]="280" /></mat-card-content> @if (d.heading) {
</mat-card> <h2 class="group-title">{{ d.heading }}</h2>
}
<section class="card panel" [attr.data-measure]="d.panel.measure">
@if (d.panel.group) {
<h3 class="panel-title">{{ d.panel.title }}</h3>
} @else {
<h2 class="panel-title">{{ d.panel.title }}</h2>
}
@if (d.figure) {
<app-plot [figure]="d.figure" [height]="320" />
} @else {
<p class="muted">Sin datos para el periodo.</p>
}
</section>
} }
</div> }
`, `,
styles: ` styles: `
:host { :host {
display: block; display: block;
padding-top: 16px; padding-top: 16px;
} }
.bar { .card {
background: var(--mat-sys-surface);
border: 1px solid var(--mat-sys-outline-variant);
border-radius: 12px;
padding: 16px 20px;
margin-bottom: 16px; margin-bottom: 16px;
} }
.grid { .filters-title {
display: grid; font-size: 16px;
gap: 16px; font-weight: 500;
grid-template-columns: 1fr; margin: 0 0 12px;
} }
@media (min-width: 1304px) { .panel-title,
.grid { .group-title {
grid-template-columns: repeat(2, 1fr); font-size: 20px;
} font-weight: 700;
margin: 0 0 8px;
}
h3.panel-title {
font-size: 16px;
}
.group-title {
margin: 24px 0 12px;
} }
`, `,
}) })
@@ -60,31 +94,48 @@ export class TabTrazabilidad {
private readonly fhir = inject(Fhir); private readonly fhir = inject(Fhir);
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly measures = input.required<Measure[]>(); readonly measures = input.required<Measure[]>();
protected readonly type = signal<PeriodType>('semester'); protected readonly type = signal<PeriodType>('month');
protected readonly series = resource({ protected readonly series = resource({
params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }), params: () => ({ domain: this.domain(), type: this.type(), measures: this.measures() }),
loader: async ({ params }) => { loader: async ({ params }) => {
const history = HISTORY[params.domain];
if (!history) return [];
const asked = periods(params.type).reverse(); const asked = periods(params.type).reverse();
const shown = params.measures.filter((m) => periodTypes(m).includes(params.type));
return Promise.all( return Promise.all(
shown.map(async (measure) => { history.panels.map(async (panel) => {
const measure = params.measures.find((m) => m.name === panel.measure);
if (!measure) return { panel, points: [] };
const pages = await this.fhir.all(params.domain, 'MeasureReport', { const pages = await this.fhir.all(params.domain, 'MeasureReport', {
measure: measure.id!, measure: measure.id!,
'reporting-period': asked.join(','), 'reporting-period': asked.join(','),
}); });
// One report per period asked, in the order asked.
const found = resources<MeasureReport>(pages, 'MeasureReport'); const found = resources<MeasureReport>(pages, 'MeasureReport');
return { measure, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) }; return { panel, points: asked.map((period, i) => ({ period, r: reading(found[i]) })) };
}), }),
); );
}, },
}); });
protected readonly figures = computed<{ measure: Measure; figure: Figure }[]>(() => protected readonly drawn = computed<Drawn[]>(() => {
(this.series.value() ?? []).map(({ measure, points }) => { const history = HISTORY[this.domain()];
// From the first period with data on. const xTitle = this.type() === 'month' ? 'Mes y año' : 'Semestre';
const first = points.findIndex((p) => (p.r?.populations['initial-population'] ?? 0) > 0); let group: string | undefined;
return { measure, figure: history(measure, first < 0 ? [] : points.slice(first)) }; if (!this.series.hasValue()) return [];
}), return this.series.value().map(({ panel, points }) => {
); const heading = panel.group && panel.group !== group ? panel.group : undefined;
group = panel.group;
const has = (p: (typeof points)[number]) => (p.r?.populations['initial-population'] ?? 0) > 0;
const first = points.findIndex(has);
if (first < 0 || !history) return { panel, heading };
const last = points.length - 1 - [...points].reverse().findIndex(has);
const shown =
history.months && this.type() === 'month'
? points.slice(Math.max(first, last + 1 - history.months), last + 1)
: points.slice(first, last + 1);
const series = shown.map((p) => ({ label: periodLabel(p.period), r: p.r }));
return { panel, heading, figure: historyFigure(panel, series, history.line, xTitle) };
});
});
} }
+128
View File
@@ -0,0 +1,128 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
/** One scenario's row of a model's scenario summary (models.factors.scenario_row). */
export interface ScenarioFactors {
escenario: string;
n_escenario: number;
horizonte_meses?: number;
riesgo_definitorios: string;
riesgo_mayoritarios: string;
incluye_factor_riesgo: boolean;
}
interface Entry {
text: string;
robust: boolean;
}
/** A listing cell, `variable=category (robusto|sugerente, share)` separated by `;`. */
export function entries(cell: string | null | undefined): Entry[] {
return (cell ?? '')
.split(';')
.map((e) => e.trim())
.filter(Boolean)
.map((text) => ({ text, robust: /\(\s*robusto\b/i.test(text) }));
}
/** "Factores de riesgo de este escenario", as the old record: per scenario of hers, the risk
* factors present in at least 95 % of it and those in 50 to 95 %, a robust one solid and a
* suggestive one outlined; with a horizon to choose when the model has several. */
@Component({
selector: 'app-factores',
imports: [MatFormFieldModule, MatSelectModule],
template: `
<h3>Factores de riesgo</h3>
@if (horizons().length > 1) {
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="horizon">
<mat-label>Horizonte</mat-label>
<mat-select [value]="horizon()" (selectionChange)="chosen.set($event.value)">
@for (h of horizons(); track h) {
<mat-option [value]="h">{{ h }} meses</mat-option>
}
</mat-select>
</mat-form-field>
}
@for (s of shown(); track s.escenario) {
<h4>
{{ s.escenario }} <span class="muted">(n = {{ s.n }})</span>
</h4>
@if (s.defining.length || s.majority.length) {
@if (s.defining.length) {
<p class="level">Presentes en al menos 95 % del escenario</p>
<ul class="factors">
@for (e of s.defining; track e.text) {
<li [class.robust]="e.robust">{{ e.text }}</li>
}
</ul>
}
@if (s.majority.length) {
<p class="level">Presentes en 50 a 95 % del escenario</p>
<ul class="factors">
@for (e of s.majority; track e.text) {
<li [class.robust]="e.robust">{{ e.text }}</li>
}
</ul>
}
} @else {
<p class="muted">Sin factores de riesgo identificados en este escenario.</p>
}
} @empty {
<p class="muted">El informe del modelo no describe factores de sus escenarios.</p>
}
`,
styles: `
.horizon {
margin: 4px 0 8px;
}
.level {
margin: 6px 0 2px;
font-size: 0.85rem;
color: var(--mat-sys-on-surface-variant);
}
.factors {
list-style: none;
padding: 0;
margin: 0 0 6px;
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.factors li {
padding: 2px 10px;
border-radius: 12px;
border: 1px solid var(--mat-sys-primary);
font-size: 0.85rem;
}
.factors li.robust {
background: var(--mat-sys-primary);
color: var(--mat-sys-on-primary);
}
`,
})
export class Factores {
/** Her scenarios' rows (every horizon when the model has several). */
readonly rows = input.required<ScenarioFactors[]>();
protected readonly chosen = signal<number | undefined>(undefined);
protected readonly horizons = computed(() =>
[
...new Set(
this.rows()
.map((r) => r.horizonte_meses)
.filter((h) => h !== undefined),
),
].sort((a, b) => a! - b!),
);
protected readonly horizon = computed(() => this.chosen() ?? this.horizons().at(-1));
protected readonly shown = computed(() =>
this.rows()
.filter((r) => r.horizonte_meses === undefined || r.horizonte_meses === this.horizon())
.map((r) => ({
escenario: r.escenario,
n: r.n_escenario,
defining: entries(r.riesgo_definitorios),
majority: entries(r.riesgo_mayoritarios),
})),
);
}
+270 -17
View File
@@ -6,7 +6,7 @@
<p class="muted" role="alert">No se encontró la paciente.</p> <p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) { } @else if (patient(); as p) {
<h1> <h1>
{{ identity().name ?? 'Paciente' }} <code class="muted">{{ p.id!.slice(0, 10) }}</code> {{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
</h1> </h1>
<dl class="summary"> <dl class="summary">
<div> <div>
@@ -21,16 +21,49 @@
<dt>Fecha de nacimiento</dt> <dt>Fecha de nacimiento</dt>
<dd>{{ p.birthDate ?? 'Sin dato' }}</dd> <dd>{{ p.birthDate ?? 'Sin dato' }}</dd>
</div> </div>
@if (stages()) {
<div>
<dt>Edad</dt>
<dd>{{ age() ?? 'Sin dato' }}</dd>
</div>
}
<div> <div>
<dt>Sexo</dt> <dt>Sexo</dt>
<dd> <dd>
{{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }} {{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }}
</dd> </dd>
</div> </div>
<div> @if (cama(); as c) {
<dt>Estatus de seguimiento</dt> <div>
<dd>{{ status() }}</dd> <dt>Grupo de edad</dt>
</div> <dd>{{ c.ageGroup || 'No disponible' }}</dd>
</div>
<div>
<dt>Escenario clínico</dt>
<dd>{{ c.scenario }}</dd>
</div>
<div>
<dt>Estatus de seguimiento</dt>
<dd>
{{ c.status ?? 'Fuera de la lista (' + c.window + ' meses al ' + c.cutoff + ')' }}
</dd>
</div>
<div>
<dt>Prioridad</dt>
<dd>{{ c.priority ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Días de mastografía a diagnóstico</dt>
<dd>{{ c.days ?? 'No disponible' }}</dd>
</div>
} @else {
@if (status()) {
<div>
<dt>Estatus de seguimiento</dt>
<dd>{{ status() }}</dd>
</div>
}
}
@if (p.deceasedDateTime) { @if (p.deceasedDateTime) {
<div> <div>
<dt>Defunción</dt> <dt>Defunción</dt>
@@ -40,6 +73,54 @@
</dl> </dl>
<div class="cards"> <div class="cards">
@if (cama(); as c) {
<mat-card appearance="outlined" data-section="mastografia">
<mat-card-header><mat-card-title>Mastografía</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Última mastografía</h3>
<dl class="facts">
<div>
<dt>Categoría BI-RADS</dt>
<dd>{{ c.birads ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Fecha</dt>
<dd>{{ c.mammogram ?? 'No disponible' }}</dd>
</div>
</dl>
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" data-section="histopatologia">
<mat-card-header><mat-card-title>Histopatología</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Resultado histopatológico</h3>
<dl class="facts">
<div>
<dt>Resultado</dt>
<dd>{{ c.histology ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Fecha de reporte de la biopsia</dt>
<dd>{{ c.biopsy ?? 'No disponible' }}</dd>
</div>
</dl>
</mat-card-content>
</mat-card>
}
@if (stages(); as s) {
<mat-card appearance="outlined" class="wide" data-section="etapas">
<mat-card-header><mat-card-title>Etapas del tamizaje</mat-card-title></mat-card-header>
<mat-card-content>
<app-stages [stages]="s" [detail]="true" />
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
</mat-card-content>
</mat-card>
}
<mat-card appearance="outlined"> <mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content> <mat-card-content>
@@ -108,6 +189,7 @@
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header ><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
> >
<mat-card-content> <mat-card-content>
<app-risk-scales [scales]="scales()" />
@if (models().length) { @if (models().length) {
<table class="plain"> <table class="plain">
<thead> <thead>
@@ -142,7 +224,7 @@
</table> </table>
<app-plot [figure]="curve()" [height]="300" /> <app-plot [figure]="curve()" [height]="300" />
} @else { } @else {
<p class="muted">Ningún modelo vigente la ha evaluado.</p> <p class="muted">Sin evaluación de un modelo en producción.</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
@@ -178,16 +260,14 @@
Estudio del {{ st.study_date }}: Estudio del {{ st.study_date }}:
<strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong> <strong>{{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }}</strong>
@if (st.level) { @if (st.level) {
({{ st.level }}) ({{ levelNames[st.level] ?? st.level }})
} }
</p> </p>
<h3>Alteraciones del EEG</h3> <h3>Alteraciones del EEG</h3>
@if (!st.valid) { @if (!st.valid) {
<p class="muted">Un EEG no aceptable no se compara con la norma por edad.</p> <p class="muted">EEG no aceptable: no se compara con la norma por edad.</p>
} @else if (!scored()) { } @else if (!scored()) {
<p class="muted"> <p class="muted">Sin curva por edad en producción para este EEG.</p>
Ninguna curva por edad vigente ha evaluado este EEG (se promueven en Gobernanza).
</p>
} @else if (alterations().length) { } @else if (alterations().length) {
<table class="plain"> <table class="plain">
<thead> <thead>
@@ -202,8 +282,18 @@
</thead> </thead>
<tbody> <tbody>
@for (m of alterations(); track m.code) { @for (m of alterations(); track m.code) {
<tr> <tr [class.chosen]="zoned()?.code === m.code">
<td>{{ m.code }}</td> <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.value | number: '1.0-3' }}</td>
<td>{{ m.p5 | number: '1.0-3' }} – {{ m.p95 | 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.median | number: '1.0-3' }}</td>
@@ -213,9 +303,125 @@
} }
</tbody> </tbody>
</table> </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 { } @else {
<p>Sin alteraciones: todas sus métricas están dentro de la norma por edad.</p> <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">Sin modelo de asociación en producción para este EEG.</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>Resultado en 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 &lt; 0.05).
Versión del modelo: {{ related()[0].model }}.
</p>
}
</section>
}
} @else { } @else {
<p class="muted">Sin EEG analizado.</p> <p class="muted">Sin EEG analizado.</p>
} }
@@ -223,12 +429,58 @@
</mat-card> </mat-card>
} }
@if (models().some((m) => m.scenarios.length)) { @if (recurrenceModel(); as rm) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia"> <mat-card appearance="outlined" class="wide" data-section="recurrencia">
<mat-card-header <mat-card-header
><mat-card-title>Análisis de supervivencia</mat-card-title></mat-card-header ><mat-card-title>Pronóstico y recomendaciones</mat-card-title></mat-card-header
> >
<mat-card-content> <mat-card-content>
<h3>Análisis de recurrencia</h3>
<table class="plain">
<thead>
<tr>
<th>Horizonte</th>
<th>Probabilidad de recurrencia</th>
</tr>
</thead>
<tbody>
@for (p of rm.predictions; track p.years) {
<tr>
<td>{{ p.years | number: '1.0-1' }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td class="num">{{ p.p * 100 | number: '1.1-1' }} %</td>
</tr>
}
</tbody>
</table>
@if (recurrence.isLoading()) {
<app-loading what="las curvas de recurrencia" [figure]="true" />
} @else if (recurrence.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 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 (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>Riesgo de muerte</mat-card-title></mat-card-header>
<mat-card-content>
<h3>Análisis de supervivencia</h3>
@if (survival.isLoading()) { @if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" /> <app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) { } @else if (survival.value(); as s) {
@@ -243,9 +495,10 @@
<app-plot [figure]="f.figure" [height]="340" /> <app-plot [figure]="f.figure" [height]="340" />
} @empty { } @empty {
<p class="muted"> <p class="muted">
Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas. Sus escenarios no tienen fallecimientos suficientes para trazar curvas.
</p> </p>
} }
<app-factores [rows]="s.factors" />
} @else if (survival.error()) { } @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} }
+45 -3
View File
@@ -1,16 +1,19 @@
.summary { .summary,
.facts {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: var(--space-6); gap: var(--space-6);
margin: var(--space-3) 0 var(--space-4); margin: var(--space-3) 0 var(--space-4);
} }
.summary dt { .summary dt,
.facts dt {
color: var(--color-text-secondary); color: var(--color-text-secondary);
font-size: 12px; font-size: 12px;
} }
.summary dd { .summary dd,
.facts dd {
font-weight: 500; font-weight: 500;
margin: 0; margin: 0;
} }
@@ -56,3 +59,42 @@ mat-card-content {
flex-wrap: wrap; flex-wrap: wrap;
gap: 16px; 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);
}
li.marked {
font-weight: 600;
color: var(--mat-sys-error);
}
}
tr.chosen td {
background: var(--mat-sys-surface-container);
}
.relation {
margin-top: 16px;
td small {
display: block;
color: var(--mat-sys-on-surface-variant);
font-size: 0.8em;
}
}
h1 .id {
font-size: 14px;
font-weight: 400;
margin-left: var(--space-2);
vertical-align: middle;
}
+260 -38
View File
@@ -19,16 +19,34 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain'; import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures'; import { scenarioFigure } from '../gobernanza/figures';
import { CURP } from '../indicadores/follow-up'; import { savePdf } from '../export';
import { name } from '../indicadores/measures'; import { recordSheets } from './record-sheets';
import { riskScales, RiskScales } from './risk-scales';
import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
import {
BIOMARKER_NAMES,
byDeviation,
headMap,
METRIC_NAMES,
OUTCOME_NAMES,
ZONE_NAMES,
LEVEL_NAMES,
} from '../eeg-labels';
import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot'; import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading'; import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores';
/** An Observation's value as the screens say it, whatever its type. */ /** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string { function shown(o: Observation): string {
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo'; if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
if (o.valueCodeableConcept) if (o.valueCodeableConcept) {
return name(code(o.valueCodeableConcept) ?? '') || label(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(); if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim();
return o.valueString ?? o.valueDateTime ?? ''; return o.valueString ?? o.valueDateTime ?? '';
} }
@@ -37,7 +55,18 @@ function shown(o: Observation): string {
* champion models' risks with their curves. Everything read from the FHIR API. */ * champion models' risks with their curves. Everything read from the FHIR API. */
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [Loading, DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot], imports: [
Factores,
Loading,
DecimalPipe,
MatButtonModule,
MatCardModule,
MatIconModule,
RouterLink,
Plot,
RiskScales,
Stages,
],
templateUrl: './paciente.html', templateUrl: './paciente.html',
styleUrl: './paciente.scss', styleUrl: './paciente.scss',
}) })
@@ -46,6 +75,11 @@ export class Paciente {
private readonly api = inject(Api); private readonly api = inject(Api);
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly id = input.required<string>(); readonly id = input.required<string>();
/** The follow-up list she was opened from: its window (months) and cut-off. */
readonly ventana = input<string>();
readonly corte = input<string>();
/** CaCu: the day of the cytology the list showed of her. */
readonly citologia = input<string>();
private readonly data = resource({ private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }), params: () => ({ domain: this.domain(), id: this.id() }),
@@ -82,7 +116,8 @@ export class Paciente {
date: c.recordedDate ?? '', date: c.recordedDate ?? '',
kind: 'Diagnóstico', kind: 'Diagnóstico',
text: label(c.code), text: label(c.code),
code: code(c.code), // the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid)
code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code,
})), })),
...d.procedures.map((p) => ({ ...d.procedures.map((p) => ({
date: p.performedDateTime ?? '', date: p.performedDateTime ?? '',
@@ -92,6 +127,50 @@ export class Paciente {
})), })),
].sort((a, b) => b.date.localeCompare(a.date)); ].sort((a, b) => b.date.localeCompare(a.date));
}); });
private readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
protected readonly stages = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
(r) => code(r.code) === 'cervical_cytology',
);
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
});
protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.models()) : [],
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** CaCu: her record as a PDF. */
protected async save(): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
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()],
];
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected readonly tests = computed(() => { protected readonly tests = computed(() => {
const d = this.data.value(); const d = this.data.value();
if (!d) return []; if (!d) return [];
@@ -104,7 +183,11 @@ export class Paciente {
reported: ext(r, 'report-date')?.valueDate, reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code), kind: label(r.code),
status: r.status, status: r.status,
results: [...results.map((o) => `${label(o.code)}: ${shown(o)}`)], // "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
results: results.map((o) => {
const [name, value] = [label(o.code), shown(o)];
return value.startsWith(name) ? value : `${name}: ${value}`;
}),
}; };
}); });
}); });
@@ -136,36 +219,68 @@ export class Paciente {
})), })),
})); }));
}); });
/** "Análisis de supervivencia": the curves of her clinical scenarios, from the report of /** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical
* the model version that scored her. */ * scenarios, from the report of the model version that scored her. */
protected readonly survival = resource({ protected readonly survival = this.analysis('survival');
params: () => { protected readonly recurrence = this.analysis('recurrence');
const m = this.models().find((x) => x.scenarios.length && x.version); protected readonly recurrenceModel = computed(() =>
return m ? { m, domain: this.domain() } : undefined; this.models().find((m) => m.model.endsWith('.recurrence') && m.version),
}, );
loader: async ({ params: { m, domain } }) => {
const report = await this.api.invoke(readReport$Json, { private analysis(name: 'survival' | 'recurrence') {
domain: domain as Domain, return resource({
name: m.model.replace(`${domain}.`, ''), params: () => {
version: m.version, const m = this.models().find(
report: 'interpretability', (x) => x.model === `${this.domain()}.${name}` && x.scenarios.length && x.version,
}); );
const drawn = ((report?.['escenarios'] ?? []) as any[]).filter((e) => return m ? { m, domain: this.domain() } : undefined;
m.scenarios.includes(e.escenario), },
); loader: async ({ params: { m, domain } }) => {
return { const report = await this.api.invoke(readReport$Json, {
scenarios: m.scenarios, domain: domain as Domain,
figures: drawn.map((e) => name,
scenarioFigure( version: m.version,
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, report: 'interpretability',
e, });
e.horizons_months, const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario));
'Supervivencia S(t)', if (name === 'recurrence') {
const r = (report?.['recurrencia'] ?? {}) as any;
// The risk factors of her scenarios, by horizon (the development tables).
const technical = (await this.api.invoke(readReport$Json, {
domain: domain as Domain,
name,
version: m.version,
report: 'technical_validation',
})) as any;
const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen'];
return {
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
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 {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
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)',
),
), ),
), };
}; },
}, });
}); }
/** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's /** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's
* `ados2.*` fields), item by item, and its totals. */ * `ados2.*` fields), item by item, and its totals. */
protected readonly ados2 = computed(() => { protected readonly ados2 = computed(() => {
@@ -233,6 +348,47 @@ export class Paciente {
(this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined), (this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined),
); );
protected readonly shown = signal<string | undefined>(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 la asociación de la cohorte'
: 'No coincide con la asociación de la cohorte';
}
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
protected readonly curve = computed<Figure>(() => { protected readonly curve = computed<Figure>(() => {
const models = this.models().filter((m) => m.predictions.length > 1); const models = this.models().filter((m) => m.predictions.length > 1);
return { return {
@@ -262,7 +418,7 @@ export class Paciente {
x, x,
y: m.predictions.map((p) => p.p * 100), y: m.predictions.map((p) => p.p * 100),
mode: 'lines+markers', mode: 'lines+markers',
name: m.model.replace('cacu.', ''), name: m.text.replace(/ v\d+$/, ''),
line: { color }, line: { color },
}, },
]; ];
@@ -282,12 +438,78 @@ export class Paciente {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
} }
protected readonly name = name; protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES;
protected readonly identity = computed(() => { protected readonly identity = computed(() => {
const p = this.patient(); const p = this.patient();
return { return {
name: p?.name?.[0]?.text, name: p?.name?.[0]?.text,
curp: p?.identifier?.find((i) => i.system === CURP)?.value, curp: p?.identifier?.find((i) => i.system === CURP)?.value,
numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value), // each record number once (several sources may carry the same one)
numbers: [
...new Set(
(p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''),
),
].filter(Boolean),
};
});
/** CaMa: her row on the follow-up list (window and cut-off as opened, else the widest
* window up to the last day with data), as the list shows it: the old record's card. */
private readonly listed = resource({
params: () =>
this.domain() === 'cama'
? {
domain: this.domain(),
id: this.id(),
window: Number(this.ventana()) || 12,
cutoff: this.corte() || undefined,
}
: undefined,
loader: async ({ params: { domain, id, window, cutoff } }) => {
const page = await this.fhir.search(domain, 'Patient', {
_id: id,
'follow-up-window': window,
'follow-up-cutoff': cutoff,
_revinclude: ['DiagnosticReport:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
const self = page.link?.find((l) => l.relation === 'self')?.url;
const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : '';
return { window, cutoff: applied, row: camaRows(page, applied)[0] };
},
});
protected readonly cama = computed(() => {
const found = this.listed.value();
const d = this.data.value();
if (!found || !d) return undefined;
// Her own latest mammogram and biopsy, on the list or not.
const latest = (study: string) =>
d.reports
.filter((r) => code(r.code) === study)
.sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''))
.at(-1);
const value = (r: DiagnosticReport | undefined, field: string) => {
const o = (r?.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.find((x) => code(x?.code) === field);
return o ? shown(o) : undefined;
};
const mammogram = latest('mammography');
const biopsy = latest('breast_biopsy');
const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff);
const r = found.row;
return {
...found,
ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS),
scenario: treated ? 'Post-tratamiento' : 'En observación',
status: r ? name(r.status) : undefined,
priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined,
birads: value(mammogram, 'mammography.birads'),
mammogram: mammogram?.effectiveDateTime?.slice(0, 10),
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
histology: value(biopsy, 'breast_biopsy.histology'),
biopsy: biopsy
? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime)
: undefined,
}; };
}); });
protected readonly status = computed(() => { protected readonly status = computed(() => {
+59
View File
@@ -0,0 +1,59 @@
import type { Sheet } from '../export';
import type { RiskScale } from './risk-scales';
import { Stage, STATES } from './stages';
const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
interface Event {
date: string;
kind: string;
text: string;
}
interface Test {
date: string;
kind: string;
reported?: string;
results: string[];
}
/** A patient's record as the tables of her PDF, in the page's order. */
export function recordSheets(
facts: [string, string | undefined][],
stages: Stage[],
history: Event[],
tests: Test[],
scales: RiskScale[],
): Sheet[] {
return [
{
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Etapas del tamizaje',
head: ['Etapa', 'Estado', 'Fecha'],
rows: stages.map((s) => [s.label, STATES[s.state], s.day ?? '']),
},
{
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados'],
rows: tests.map((t) => [t.date, t.kind, t.reported ?? 'Pendiente', t.results.join(' · ')]),
},
{
title: 'Riesgos',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [
label,
risk ? percent(risk.p) : NONE,
risk?.low === undefined ? NONE : `${percent(risk.low)} a ${percent(risk.high!)}`,
]),
},
];
}
+75
View File
@@ -0,0 +1,75 @@
import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core';
interface Prediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface RiskScale {
label: string;
risk?: Prediction;
}
/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) =>
[0, 5].map((years) => ({
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`,
risk: m.predictions.find((p) => p.years === years),
})),
);
}
@Component({
selector: 'app-risk-scales',
imports: [DecimalPipe],
template: `
@for (s of scales(); track s.label) {
<div class="scale">
<span>{{ s.label }}</span>
<div class="line">
@if (s.risk; as r) {
<span class="mark" [style.left.%]="r.p * 100"></span>
}
</div>
@if (s.risk; as r) {
<strong>{{ r.p * 100 | number: '1.1-2' }} %</strong>
@if (r.low !== undefined) {
<span>
IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high! * 100 | number: '1.1-2' }} %
</span>
}
} @else {
<strong>No disponible</strong>
}
</div>
}
`,
styles: `
.scale {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 8px;
}
.line {
background: linear-gradient(to right, #a8c243, #c24269);
flex: 1 1 200px;
height: 8px;
position: relative;
}
.mark {
background: #333;
height: 16px;
position: absolute;
top: -4px;
width: 3px;
}
`,
})
export class RiskScales {
readonly scales = input.required<RiskScale[]>();
}
+26
View File
@@ -0,0 +1,26 @@
import { EXT } from '../fhir';
import { route } from './stages';
const ext = (name: string, value: object) => ({ url: EXT + name, ...value });
const cytology = (...extension: object[]): any => ({ effectiveDateTime: '2026-01-10', extension });
describe('the route of a cytology', () => {
it('says what is recorded, inferred, pending and unknown, by the cut-off', () => {
const report = cytology(
ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-date', { valueDate: '2026-03-01' }),
ext('biopsy-link', { valueCode: 'recorded' }),
);
const states = (cutoff: string) => route(report, cutoff).map((s) => s.state);
expect(states('2026-12-31')).toEqual([
'recorded',
'unknown',
'inferred',
'recorded',
'unknown',
]);
expect(states('2026-02-15')[3]).toBe('pending');
expect(states('2026-01-15').slice(2)).toEqual(['unknown', 'unknown', 'unknown']);
});
});
+121
View File
@@ -0,0 +1,121 @@
import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4';
import { ext } from '../fhir';
/** A step of the route that a cytology starts. A day with no state is unknown. */
export interface Stage {
label: string;
day?: string;
state: 'recorded' | 'inferred' | 'pending' | 'unknown';
}
export const STATES: Record<Stage['state'], string> = {
recorded: 'Registrada',
inferred: 'Inferida por fechas',
pending: 'Pendiente',
unknown: 'Sin dato',
};
/** The route of one cytology, as its report says it, by `cutoff`. */
export function route(cytology: DiagnosticReport | undefined, cutoff: string): Stage[] {
const by = (day?: string) => (day && day.slice(0, 10) <= cutoff ? day.slice(0, 10) : undefined);
const at = (name: string) => by(ext(cytology, name)?.valueDate);
const step = (label: string, day: string | undefined, known: Stage['state']): Stage => ({
label,
day,
state: day ? known : 'unknown',
});
const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded' ? 'recorded' : 'inferred';
const biopsy = step('Reporte de biopsia', at('biopsy-date'), linked);
if (!biopsy.day && at('biopsy-request-date')) biopsy.state = 'pending';
return [
step('Toma de muestra', by(cytology?.effectiveDateTime), 'recorded'),
step('Resultado de citología', at('report-date'), 'recorded'),
step('Colposcopía', at('colposcopy-date'), 'inferred'),
biopsy,
step('Diagnóstico', at('diagnosis-date'), 'inferred'),
];
}
/** Whole days between two days; none when either is missing or they are out of order. */
export function between(from?: string, to?: string): number | undefined {
if (!from || !to || to < from) return undefined;
return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);
}
/** The stages as a line of dots; `detail` adds each one's state, day and days elapsed. */
@Component({
selector: 'app-stages',
template: `
<ol [class.detail]="detail()">
@for (s of shown(); track s.label) {
<li [title]="s.label + ': ' + s.text">
<span class="dot" [class]="s.state"></span>
@if (detail()) {
<strong>{{ s.label }}</strong>
<span>{{ s.text }}</span>
@if (s.day) {
<span>{{ s.day }}</span>
}
@if (s.previous !== undefined) {
<span>{{ s.previous }} días desde la etapa anterior</span>
}
@if (s.sample !== undefined) {
<span>{{ s.sample }} días desde la toma</span>
}
}
</li>
}
</ol>
`,
styles: `
ol {
display: flex;
gap: 6px;
list-style: none;
margin: 0;
padding: 0;
}
ol.detail {
flex-wrap: wrap;
gap: 16px;
}
.detail li {
display: flex;
flex: 1 1 120px;
flex-direction: column;
font-size: 0.85rem;
}
.dot {
border: 2px solid #9aa3ab;
border-radius: 50%;
display: inline-block;
height: 12px;
width: 12px;
}
.recorded {
background: #6a8000;
border-color: #6a8000;
}
.inferred {
background: #a8c243;
border-color: #6a8000;
}
.pending {
border-color: #c24269;
}
`,
})
export class Stages {
readonly stages = input.required<Stage[]>();
readonly detail = input(false);
protected readonly shown = computed(() => {
const all = this.stages();
return all.map((s, i) => ({
...s,
text: STATES[s.state],
previous: i ? between(all[i - 1].day, s.day) : undefined,
sample: i > 1 ? between(all[0].day, s.day) : undefined,
}));
});
}
+39 -7
View File
@@ -21,8 +21,45 @@ const LAYOUT: Partial<Plotly.Layout> = {
margin: { t: 24, r: 16, b: 48, l: 56 }, margin: { t: 24, r: 16, b: 48, l: 56 },
paper_bgcolor: 'rgba(0,0,0,0)', paper_bgcolor: 'rgba(0,0,0,0)',
plot_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
legend: { orientation: 'h', y: -0.2 }, // Above the plot, left-aligned: Plotly reserves its room, so it never meets an axis title.
legend: { orientation: 'h', x: 0, xanchor: 'left', y: 1.02, yanchor: 'bottom' },
hoverlabel: { font: { family: 'Roboto, Arial, sans-serif', size: 13 } },
}; };
// Axes make room for their labels and titles; a title keeps clear of the tick labels.
// (`ticklabelstandoff` is Plotly's, newer than its published types.)
const AXIS = {
automargin: true,
title: { standoff: 12 },
ticklabelstandoff: 4, // the lowest y label and the first x label never touch
} as Partial<Plotly.LayoutAxis>;
/** The platform's layout under a figure's own: legend, margins and axes merged key by key,
* so a figure that sets one of their keys keeps the others. */
export function layoutOf(layout: Partial<Plotly.Layout> = {}): Partial<Plotly.Layout> {
const axes = Object.fromEntries(
Object.entries(layout)
.filter(([k]) => /^[xy]axis\d*$/.test(k))
.map(([k, v]) => {
const axis = (v ?? {}) as Partial<Plotly.LayoutAxis>;
const title = typeof axis.title === 'string' ? { text: axis.title } : axis.title;
return [k, { ...AXIS, ...axis, title: { ...AXIS.title, ...title } }];
}),
);
return {
...LAYOUT,
xaxis: AXIS,
yaxis: AXIS,
...layout,
...axes,
legend: { ...LAYOUT.legend, ...layout.legend },
margin: { ...LAYOUT.margin, ...layout.margin },
};
}
/** Pie labels that sit outside take the room they need instead of being clipped. */
function withRoom(data: Partial<Plotly.Data>[]): Plotly.Data[] {
return data.map((d) => (d.type === 'pie' ? { automargin: true, ...d } : d)) as Plotly.Data[];
}
const CONFIG: Partial<Plotly.Config> = { const CONFIG: Partial<Plotly.Config> = {
responsive: true, responsive: true,
displaylogo: false, displaylogo: false,
@@ -43,12 +80,7 @@ export class Plot implements OnDestroy {
constructor() { constructor() {
effect(() => { effect(() => {
const { data, layout } = this.figure(); const { data, layout } = this.figure();
void Plotly.react( void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG);
this.host().nativeElement,
data as Plotly.Data[],
{ ...LAYOUT, ...layout },
CONFIG,
);
}); });
} }
+57 -12
View File
@@ -1,8 +1,8 @@
<section class="page"> <section class="page">
<h1>Revisión</h1> <h1>Revisión</h1>
<p class="subtitle"> <p class="subtitle">
Lo que la carga retuvo para que una persona decida. Cada decisión queda registrada y se aplica Registros retenidos durante la carga que requieren una decisión. Cada decisión queda registrada
en la siguiente ejecución. y se aplica en la siguiente ejecución.
</p> </p>
@if (message()) { @if (message()) {
<p class="message" role="status">{{ message() }}</p> <p class="message" role="status">{{ message() }}</p>
@@ -30,14 +30,14 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (row of held.value() ?? []; track row['_record']) { @for (row of held.value() ?? []; track $index) {
<tr> <tr>
<td>{{ row['_pipeline'] }} · {{ row['_target'] }}</td> <td>{{ row['_pipeline'] }} · {{ row['_target'] }}</td>
<td>{{ reasons(row) }}</td> <td>{{ said(row) }}</td>
<td class="values"> <td class="values">
@for (v of values(row) | keyvalue; track v.key) { @for (v of values(row) | keyvalue; track v.key) {
<span <span
><b>{{ v.key }}</b ><b>{{ title(v.key) }}</b
>: {{ text(v.value) }}</span >: {{ text(v.value) }}</span
> >
} }
@@ -84,7 +84,7 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (row of conflicts.value() ?? []; track row['_record']) { @for (row of conflicts.value() ?? []; track $index) {
<tr> <tr>
<td> <td>
<code>{{ text(row['person_id']).slice(0, 10) }}</code> <code>{{ text(row['person_id']).slice(0, 10) }}</code>
@@ -92,7 +92,7 @@
<td class="values"> <td class="values">
@for (v of values(row) | keyvalue; track v.key) { @for (v of values(row) | keyvalue; track v.key) {
<span <span
><b>{{ v.key }}</b ><b>{{ title(v.key) }}</b
>: {{ text(v.value) }}</span >: {{ text(v.value) }}</span
> >
} }
@@ -116,6 +116,51 @@
</table> </table>
</mat-tab> </mat-tab>
<mat-tab [label]="'Documentos no reconocidos (' + (unrecognised.value()?.length ?? 0) + ')'">
<div class="bar">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Canalización</mat-label>
<mat-select [value]="pipeline()" (selectionChange)="pipeline.set($event.value)">
@for (p of pipelines.value() ?? []; track p['pipeline_id']) {
<mat-option [value]="p['pipeline_id']">{{ p['pipeline_id'] }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<p class="muted">
Documentos recibidos que ninguna ruta reconoce: un formato nuevo, un estudio fuera del
catálogo o un escaneo ilegible. Para incluirlos, agregue o ajuste una ruta en Conectar.
</p>
@if (unrecognised.isLoading()) {
<app-loading what="los documentos no reconocidos" />
} @else {
<table class="plain">
<thead>
<tr>
<th>Ruta</th>
<th>Origen</th>
<th>Inicio del texto</th>
</tr>
</thead>
<tbody>
@for (row of unrecognised.value() ?? []; track $index) {
<tr>
<td>{{ row['route'] }}</td>
<td class="muted">{{ details(row) }}</td>
<td>
<pre class="preview">{{ row['preview'] || '(sin texto legible)' }}</pre>
</td>
</tr>
} @empty {
<tr>
<td colspan="3" class="muted">Sin documentos no reconocidos.</td>
</tr>
}
</tbody>
</table>
}
</mat-tab>
<mat-tab label="Personas"> <mat-tab label="Personas">
<div class="bar"> <div class="bar">
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -158,7 +203,7 @@
@for (entry of p['to_settle']; track entry['person']) { @for (entry of p['to_settle']; track entry['person']) {
<div class="card person"> <div class="card person">
<div> <div>
<b>Registro</b> <code>{{ text(entry['person']).slice(0, 10) }}</code> · <b>Registro</b>&ngsp;<code>{{ text(entry['person']).slice(0, 10) }}</code> ·
{{ text(entry['record_number']) }} · {{ text(entry['full_name']) }} · {{ text(entry['record_number']) }} · {{ text(entry['full_name']) }} ·
{{ text(entry['birth_date']) }} {{ text(entry['birth_date']) }}
</div> </div>
@@ -170,7 +215,7 @@
}} }}
· {{ text(c['full_name']) }} · {{ text(c['birth_date']) }})? · {{ text(c['full_name']) }} · {{ text(c['birth_date']) }})?
<span class="muted" <span class="muted"
>{{ c['reason'] }} >{{ candidateReason(c['reason']) }}
@if (c['probability'] !== null) { @if (c['probability'] !== null) {
· p = {{ $any(c['probability']) | number: '1.2-2' }} · p = {{ $any(c['probability']) | number: '1.2-2' }}
} }
@@ -194,13 +239,13 @@
} }
</div> </div>
} @empty { } @empty {
<p class="muted">Nada que decidir.</p> <p class="muted">Sin decisiones pendientes.</p>
} }
<h2>Registros que no coinciden en fecha de nacimiento o sexo ({{ p['torn'].length }})</h2> <h2>Registros que no coinciden en fecha de nacimiento o sexo ({{ p['torn'].length }})</h2>
@for (entry of p['torn']; track entry['person']) { @for (entry of p['torn']; track entry['person']) {
<div class="card person"> <div class="card person">
@for (r of records(entry); track r['_record']) { @for (r of records(entry); track $index) {
<div class="candidate"> <div class="candidate">
<span class="values"> <span class="values">
@for (v of values(r) | keyvalue; track v.key) { @for (v of values(r) | keyvalue; track v.key) {
@@ -239,7 +284,7 @@
} }
</div> </div>
} @empty { } @empty {
<p class="muted">Nada que decidir.</p> <p class="muted">Sin decisiones pendientes.</p>
} }
} }
</mat-tab> </mat-tab>
+8
View File
@@ -46,3 +46,11 @@ h2 {
.small { .small {
width: 160px; width: 160px;
} }
.preview {
margin: 0;
max-height: 8em;
overflow: auto;
white-space: pre-wrap;
font-size: 12px;
}
+94
View File
@@ -15,6 +15,9 @@ import { conflicts } from '../api/fn/review/conflicts';
import { correct } from '../api/fn/review/correct'; import { correct } from '../api/fn/review/correct';
import { decidePersons } from '../api/fn/review/decide-persons'; import { decidePersons } from '../api/fn/review/decide-persons';
import { held } from '../api/fn/review/held'; import { held } from '../api/fn/review/held';
import { Loading } from '../loading';
import { schema } from '../api/fn/ingest/schema';
import { unrecognised } from '../api/fn/review/unrecognised';
import { persons } from '../api/fn/review/persons'; import { persons } from '../api/fn/review/persons';
import { reject } from '../api/fn/review/reject'; import { reject } from '../api/fn/review/reject';
import { runStatus } from '../api/fn/runs/run-status'; import { runStatus } from '../api/fn/runs/run-status';
@@ -33,6 +36,7 @@ const ENTITIES: Record<Entity, string> = {
mammography: 'Mastografía', mammography: 'Mastografía',
breast_biopsy: 'Biopsia de mama', breast_biopsy: 'Biopsia de mama',
breast_treatment: 'Tratamiento de cáncer de mama', breast_treatment: 'Tratamiento de cáncer de mama',
breast_recurrence: 'Recurrencia de cáncer de mama',
mchat: 'M-CHAT', mchat: 'M-CHAT',
ados2: 'ADOS-2', ados2: 'ADOS-2',
eeg: 'Electroencefalograma', eeg: 'Electroencefalograma',
@@ -45,6 +49,39 @@ const IDENTITY_FIELDS: Correction['field'][] = [
'birth_date', 'birth_date',
'sex', 'sex',
]; ];
/** Identity fields as linkage names them (core.schema.Identity). */
const IDENTITY_TITLES: Record<string, string> = {
record_number: 'Expediente',
curp: 'CURP',
nss: 'NSS',
full_name: 'Nombre',
};
/** The platform's hold reasons (English in its logs) as the reviewer reads them. */
const REASONS: [RegExp, (m: RegExpExecArray) => string][] = [
[/^Field required$/, () => 'falta el dato'],
[
/^Input should be (.+)$/,
(m) => `valor fuera del catálogo (se espera ${m[1].replace(/ or /g, ' o ')})`,
],
[/^not found in the document as quoted$/, () => 'no está en el documento tal como se citó'],
[/^Value error, a date is not a record number$/, () => 'una fecha no es un expediente'],
[
/^records of this person disagree on birth date or sex$/,
() => 'sus registros no coinciden en fecha de nacimiento o sexo',
],
[
/^no name, birth date or record number was read$/,
() => 'no se leyó nombre, fecha de nacimiento ni expediente',
],
[/^no identity linked to this record$/, () => 'ninguna identidad vinculada a este registro'],
[/^nothing found$/, () => 'no se encontró nada en el documento'],
[
/^no LLM answering and no patterns set$/,
() => 'sin modelo de lenguaje disponible ni patrones configurados',
],
];
/** Bookkeeping columns, not values a reviewer judges. */ /** Bookkeeping columns, not values a reviewer judges. */
const HIDDEN = [ const HIDDEN = [
'_pipeline', '_pipeline',
@@ -63,6 +100,7 @@ const HIDDEN = [
@Component({ @Component({
selector: 'app-revision', selector: 'app-revision',
imports: [ imports: [
Loading,
DecimalPipe, DecimalPipe,
KeyValuePipe, KeyValuePipe,
FormsModule, FormsModule,
@@ -114,6 +152,20 @@ export class Revision {
: Promise.resolve({ to_settle: [], torn: [] } as Record<string, Row[]>), : Promise.resolve({ to_settle: [], torn: [] } as Record<string, Row[]>),
}); });
/** Documents the chosen pipeline's routes don't recognise (its `otherwise` routes). */
protected readonly unrecognised = resource({
params: () => this.pipeline(),
loader: ({ params }) =>
params ? this.api.invoke(unrecognised, { pipeline: params }) : Promise.resolve([] as Row[]),
});
/** A row's fields but its route and preview, as `name: value`. */
protected details(row: Row): string {
return Object.entries(row)
.filter(([k, v]) => !['route', 'preview'].includes(k) && v !== null && v !== '')
.map(([k, v]) => `${k}: ${v}`)
.join(' · ');
}
protected readonly message = signal(''); protected readonly message = signal('');
protected readonly decided = signal(new Set<string>()); protected readonly decided = signal(new Set<string>());
protected readonly run = signal<string>(''); protected readonly run = signal<string>('');
@@ -129,6 +181,48 @@ export class Revision {
const found = row['_held']; const found = row['_held'];
return Array.isArray(found) ? found.join('; ') : String(found ?? ''); return Array.isArray(found) ? found.join('; ') : String(found ?? '');
} }
/** The platform's field titles (the catalog's), by entity: what the page calls a field. */
protected readonly titles = resource({
loader: async () => {
const found = (await this.api.invoke(schema)) as Record<string, any>;
return Object.fromEntries(
Object.entries((found['entities'] ?? {}) as Record<string, any>).map(([e, s]) => [
e,
Object.fromEntries(
Object.entries((s['properties'] ?? {}) as Record<string, any>).map(([f, p]) => [
f,
p['title'] as string,
]),
),
]),
) as Record<string, Record<string, string>>;
},
});
protected title(field: string): string {
return this.titles.value()?.[this.entity()]?.[field] ?? field;
}
/** A hold's reasons as the reviewer reads them (the platform logs them in English). */
protected said(row: Row): string {
const found = row['_held'];
const all = Array.isArray(found) ? (found as string[]) : [String(found ?? '')];
return all.map((r) => this.spanish(r)).join('; ');
}
/** Why linkage proposes two records as one person, in the reviewer's words. */
protected candidateReason(reason: unknown): string {
const text = String(reason ?? '');
const typo = /^(\w+) one typo apart$/.exec(text);
if (typo) return `${IDENTITY_TITLES[typo[1]] ?? typo[1]} a una letra de distancia`;
return text === 'same birth date' ? 'misma fecha de nacimiento' : text;
}
private spanish(reason: string): string {
const field = /^(\w+): (.*)$/.exec(reason);
const [name, message] = field ? [this.title(field[1]) + ': ', field[2]] : ['', reason];
for (const [pattern, text] of REASONS) {
const m = pattern.exec(message);
if (m) return name + text(m);
}
return reason;
}
protected text(value: unknown): string { protected text(value: unknown): string {
return typeof value === 'object' && value !== null return typeof value === 'object' && value !== null
? JSON.stringify(value) ? JSON.stringify(value)
+1 -1
View File
@@ -103,7 +103,7 @@ table.plain td {
border-bottom: 1px solid var(--color-border); border-bottom: 1px solid var(--color-border);
padding: 6px 8px; padding: 6px 8px;
text-align: left; text-align: left;
vertical-align: top; vertical-align: middle;
} }
table.plain th { table.plain th {